/**
 * KooKoa Folders — Download ZIP UI glue.
 *
 * Adds:
 *   - "Download ZIP" entry in the folder context menu
 *   - "Download Selected" button in the bulk-organize toolbar
 *
 * Both submit a hidden form so the browser handles the download dialog
 * natively instead of going through XHR.
 */
(function($) {
    'use strict';

    const FO = window.KookoaWPF;
    if (!FO) return;

    /**
     * Submit a hidden form that triggers the ZIP stream from the AJAX
     * endpoint. Using a real form POST (instead of XHR) lets the browser
     * handle the download dialog natively.
     *
     * @param {string} wpAction wp_ajax_ action slug.
     * @param {Object} fields   Extra POST fields.
     */
    function submitDownloadForm(wpAction, fields) {
        const $form = $('<form>', {
            method: 'POST',
            action: FO.data.ajaxUrl,
            style: 'display:none'
        });
        $form.append($('<input>', { type: 'hidden', name: 'action', value: wpAction }));
        $form.append($('<input>', { type: 'hidden', name: 'nonce', value: FO.data.nonce }));
        $.each(fields || {}, function(k, v) {
            $form.append($('<input>', { type: 'hidden', name: k, value: String(v) }));
        });
        $('body').append($form);
        $form.submit();
        $form.remove();
    }

    /**
     * Recursively check whether a folder (or any of its descendants) has at
     * least one attachment. A parent with count=0 but non-empty subfolders
     * should still offer Download ZIP — the ZIP archiver recurses into the
     * whole subtree.
     */
    function hasAnyContent(node, inst) {
        if (!node || !node.data) return false;
        if (parseInt(node.data.count, 10) > 0) return true;
        if (inst && node.children && node.children.length) {
            for (let i = 0; i < node.children.length; i++) {
                const child = inst.get_node(node.children[i]);
                if (hasAnyContent(child, inst)) return true;
            }
        }
        return false;
    }

    // ---- Context menu: inject "Download ZIP" before Delete ----
    $(document).on('kookoawpf:context-menu-build', function(e, items, node, ctx) {
        if (!node || !node.data) return;
        // Media Library only — posts/pages/CPT can't be packaged into a ZIP.
        const postType = (FO.data && FO.data.postType) || 'attachment';
        if ('attachment' !== postType) return;
        // Hide on empty folders (including subtree) — an empty ZIP is worse UX.
        // For smart folders the count reflects the matching set, so this works
        // identically without recursing into children.
        const inst = (ctx && ctx.tree) ? ctx.tree.jstree(true) : (FO.tree ? FO.tree.jstree(true) : null);
        if (!hasAnyContent(node, inst)) return;

        const S = FO.data.strings || {};
        const label = S.downloadZip || 'Download ZIP';
        const item = (typeof FO._ctxItem === 'function')
            ? FO._ctxItem('download', 'download', label)
            : { action: 'download', icon: 'download', label: label };

        // Insert separator + item just before the final separator+Delete pair.
        let insertAt = items.length - 2;
        if (insertAt < 0) insertAt = items.length;
        items.splice(insertAt, 0, { sep: true }, item);
    });

    // ---- Bulk toolbar: append "Download Selected" ----
    $(document).on('kookoawpf:bulk-toolbar-build', function(e, $wrapper) {
        if (!$wrapper || !$wrapper.length) return;
        const S = FO.data.strings || {};
        const $btn = $('<button>', {
            type: 'button',
            id: 'kookoawpf-btn-download-selected',
            'class': 'button kookoawpf-btn-bulk-action kookoawpf-btn-download',
            disabled: true
        });
        const $icon = $('<span>', {
            'class': 'dashicons dashicons-download',
            style: 'vertical-align:middle;margin-top:-2px;margin-right:2px;'
        });
        $btn.append($icon).append(document.createTextNode(S.downloadSelected || 'Download'));
        // Place it right after Select All so the primary "Move to" UI stays last.
        const $selectAll = $wrapper.find('#kookoawpf-btn-select-all');
        if ($selectAll.length) {
            $btn.insertAfter($selectAll);
        } else {
            $btn.appendTo($wrapper);
        }
        $btn.after(document.createTextNode(' '));
    });

    // ---- Dispatch: handle 'download' action (context menu) ----
    const origExecute = FO._executeContextAction;
    FO._executeContextAction = function(action, fid, node, ctx) {
        if ('download' === action) {
            submitDownloadForm('kookoawpf_download_zip', {
                folder_id: fid,
                post_type: (FO.data && FO.data.postType) || 'attachment'
            });
            return;
        }
        if (typeof origExecute === 'function') {
            origExecute.call(this, action, fid, node, ctx);
        }
    };

    // ---- Click handler: Download Selected (bulk toolbar) ----
    $(document).on('click', '#kookoawpf-btn-download-selected', function() {
        let selected = [];
        if (typeof FO.getSelectedAttachmentIds === 'function') {
            selected = FO.getSelectedAttachmentIds();
        } else {
            // Fallback: read from native WP grid selection.
            $('.attachment.selected').each(function() {
                const id = $(this).data('id');
                if (id) selected.push(id);
            });
        }
        if (!selected.length) {
            if (typeof FO.showNotice === 'function') {
                FO.showNotice((FO.data.strings && FO.data.strings.noItemsSelected) || 'No items selected.', 'error');
            }
            return;
        }
        submitDownloadForm('kookoawpf_download_selected', {
            ids: selected.join(',')
        });
    });

})(jQuery);
