/**
 * KooKoa Folders — Sidebar UI (Sort, More Menu, Empty State, Free Limits, Folder IDs)
 *
 * Extracted from admin.js (block 8).
 * IIFE that adds methods directly to FO (window.KookoaWPF).
 *
 * Depends on: kookoawpf-admin (FO.data, FO.tree, FO.treeData, FO.ajax, FO.showNotice,
 *             FO.refreshTree, FO.applyFolderIcons, FO.applyActiveFolderColor, FO._fbActive)
 *
 * @since 1.0.0
 */
(function($) {
    'use strict';

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

    // ========================
    // Sort Folders
    // ========================

    FO._sortBy = 'custom';
    FO._sortDir = 'ASC';

    FO.initSort = function() {
        const self = this;

        $(document).on('click', '#kookoawpf-btn-sort', function(e) {
            e.stopPropagation();
            if ($(this).hasClass('kookoawpf-ui-disabled')) return;
            $('#kookoawpf-more-dropdown').hide(); // close more menu
            $('#kookoawpf-context-menu').hide();  // close context menu
            const $dd = $('#kookoawpf-sort-dropdown');
            $dd.toggle();
            if ($dd.is(':visible')) self._updateSortUI();
        });

        $(document).on('click', function(e) {
            if (!$(e.target).closest('.kookoawpf-sidebar-sort').length) {
                $('#kookoawpf-sort-dropdown').hide();
                $('#kookoawpf-more-dropdown').hide();
            }
        });

        $(document).on('click', '.kookoawpf-sort-option', function(e) {
            e.preventDefault();
            self._sortBy = $(this).data('sort');
            self._applySort();
        });

        $(document).on('click', '.kookoawpf-sort-dir', function(e) {
            e.preventDefault();
            self._sortDir = $(this).data('dir');
            if (self._sortBy !== 'custom') self._applySort();
            else self._updateSortUI();
        });
    };

    FO._applySort = function() {
        const self = this;
        $('#kookoawpf-sort-dropdown').hide();
        self.ajax('kookoawpf_sort_folders', {
            sort_by: self._sortBy, sort_dir: self._sortDir, post_type: self.data.postType
        }, function(r) {
            if (r.success) { self.showNotice(self.data.strings.sorted, 'success'); self.refreshTree(); }
            else { self.showNotice((r.data && r.data.message) || self.data.strings.errorGeneric, 'error'); }
            self._updateSortUI();
        });
    };

    FO._updateSortUI = function() {
        const self = this;
        $('.kookoawpf-sort-option').removeClass('kookoawpf-sort-active');
        $('.kookoawpf-sort-option[data-sort="' + self._sortBy + '"]').addClass('kookoawpf-sort-active');
        $('.kookoawpf-sort-dir').removeClass('kookoawpf-sort-active');
        $('.kookoawpf-sort-dir[data-dir="' + self._sortDir + '"]').addClass('kookoawpf-sort-active');

        if (self._sortBy === 'custom') { $('.kookoawpf-sort-dir').addClass('kookoawpf-sort-disabled'); }
        else { $('.kookoawpf-sort-dir').removeClass('kookoawpf-sort-disabled'); }

        // Sort direction hints (e.g. A–Z / Z–A, Old–New / New–Old, 0–9 / 9–0)
        const hintMap = {
            name:  ['A\u2013Z', 'Z\u2013A'],
            date:  ['OLD\u2013NEW', 'NEW\u2013OLD'],
            count: ['<span style="font-size:10px">\u25CF</span><span style="font-size:16px">\u25CF</span><span style="font-size:23px">\u25CF</span>', '<span style="font-size:23px">\u25CF</span><span style="font-size:16px">\u25CF</span><span style="font-size:10px">\u25CF</span>']
        };
        const hints = hintMap[self._sortBy] || ['', ''];
        $('.kookoawpf-sort-dir[data-dir="ASC"] .kookoawpf-sort-hint').html(hints[0]);
        $('.kookoawpf-sort-dir[data-dir="DESC"] .kookoawpf-sort-hint').html(hints[1]);

        const iconMap = {
            custom: 'dashicons-move',
            name:   'dashicons-editor-textcolor',
            date:   'dashicons-calendar-alt',
            count:  'dashicons-editor-ol'
        };
        const dirIcon = self._sortDir === 'DESC' ? 'dashicons-arrow-down-alt' : 'dashicons-arrow-up-alt';
        const sortIcon = iconMap[self._sortBy] || '';
        let html = sortIcon ? '<span class="dashicons ' + sortIcon + '"></span>' : '';
        if (self._sortBy !== 'custom') html += ' <span class="dashicons ' + dirIcon + '"></span>';
        $('#kookoawpf-sort-current').html(html);
    };

    // ========================
    // Three-Dot More Menu
    // ========================

    FO._moreShowIds = false;

    FO.initMoreMenu = function() {
        const self = this;

        // Submenu delay — prevent close on diagonal mouse movement
        let moreSubTimer = null;
        $(document).on('mouseenter.kwpfMoreSub', '.kookoawpf-more-has-sub', function() {
            clearTimeout(moreSubTimer);
            $('.kookoawpf-more-has-sub').removeClass('kookoawpf-more-sub-open');
            $(this).addClass('kookoawpf-more-sub-open');
        }).on('mouseleave.kwpfMoreSub', '.kookoawpf-more-has-sub', function() {
            const $el = $(this);
            moreSubTimer = setTimeout(function() {
                $el.removeClass('kookoawpf-more-sub-open');
            }, 100);
        });

        // Toggle the ⋮ dropdown
        $(document).on('click', '#kookoawpf-btn-more', function(e) {
            e.stopPropagation();
            if ($(this).hasClass('kookoawpf-ui-disabled')) return;
            $('#kookoawpf-sort-dropdown').hide(); // close sort menu
            $('#kookoawpf-context-menu').hide();  // close context menu
            const $dd = $('#kookoawpf-more-dropdown');
            if (!$dd.is(':visible')) self._updateMoreUI();
            $dd.toggle();
        });

        // Bulk Select
        $(document).on('click', '#kookoawpf-more-bulk-select', function(e) {
            e.preventDefault();
            if ($(this).hasClass('kookoawpf-ui-disabled')) return;
            $('#kookoawpf-more-dropdown').hide();

            const $master = $('#kookoawpf-fb-master');
            if (self._fbActive) {
                // Exit bulk mode
                $master.prop('checked', false).trigger('change');
            } else {
                // Enter bulk mode
                $master.prop('checked', true).trigger('change');
            }
        });

        // Expand All / Collapse All
        $(document).on('click', '#kookoawpf-more-expand', function(e) {
            e.preventDefault();
            if ($(this).hasClass('kookoawpf-ui-disabled')) {
                $('#kookoawpf-more-dropdown').hide();
                return;
            }
            $('#kookoawpf-more-dropdown').hide();

            if (!self.tree || !self.tree.jstree(true)) return;
            const inst = self.tree.jstree(true);

            // Check if all nodes are already open
            const allOpen = self._isTreeFullyExpanded(inst);

            if (allOpen) {
                inst.close_all();
            } else {
                inst.open_all();
            }

            // Re-apply icons after open/close (jsTree redraws nodes)
            setTimeout(function() {
                self.applyFolderIcons();
                self.applyActiveFolderColor();
            }, 100);
        });

        // Display / Hide Folder ID
        $(document).on('click', '#kookoawpf-more-folder-id', function(e) {
            e.preventDefault();
            if ($(this).hasClass('kookoawpf-ui-disabled')) return;
            $('#kookoawpf-more-dropdown').hide();

            self._moreShowIds = !self._moreShowIds;
            self._applyFolderIdBadges();
        });
    };

    /**
     * Check if the tree is fully expanded (all parent nodes open).
     */
    FO._isTreeFullyExpanded = function(inst) {
        let allOpen = true;
        const all = inst.get_json('#', { flat: true });
        for (let i = 0; i < all.length; i++) {
            const node = inst.get_node(all[i].id);
            if (node && node.children && node.children.length > 0 && !node.state.opened) {
                allOpen = false;
                break;
            }
        }
        return allOpen;
    };

    /**
     * Update the ⋮ menu labels based on current state.
     */
    FO._updateMoreUI = function() {
        const self = this;
        const s = self.data.strings;

        // Bulk Select label
        const $bulk = $('#kookoawpf-more-bulk-select');
        if (self._fbActive) {
            $bulk.find('.kookoawpf-more-label').text(s.exitSelection);
            $bulk.find('.dashicons').attr('class', 'dashicons dashicons-dismiss');
            $bulk.addClass('kookoawpf-more-active');
        } else {
            $bulk.find('.kookoawpf-more-label').text(s.bulkSelect);
            $bulk.find('.dashicons').attr('class', 'dashicons dashicons-screenoptions');
            $bulk.removeClass('kookoawpf-more-active');
        }

        // Expand / Collapse label
        const $expand = $('#kookoawpf-more-expand');
        const inst = self.tree && self.tree.jstree(true);
        const allOpen = inst ? self._isTreeFullyExpanded(inst) : false;
        if (allOpen) {
            $expand.find('.kookoawpf-more-label').text(s.collapseAll);
            $expand.find('.dashicons').attr('class', 'dashicons dashicons-arrow-up-alt2');
        } else {
            $expand.find('.kookoawpf-more-label').text(s.expandAll);
            $expand.find('.dashicons').attr('class', 'dashicons dashicons-arrow-down-alt2');
        }

        // Disable Expand/Collapse if no subfolders exist
        let hasSubfolders = false;
        if (inst) {
            const allNodes = inst.get_json('#', { flat: true });
            for (let i = 0; i < allNodes.length; i++) {
                const node = inst.get_node(allNodes[i].id);
                if (node && node.children && node.children.length > 0) {
                    hasSubfolders = true;
                    break;
                }
            }
        }
        if (!hasSubfolders) {
            $expand.addClass('kookoawpf-ui-disabled');
        } else {
            $expand.removeClass('kookoawpf-ui-disabled');
        }

        // Folder ID label
        const $fid = $('#kookoawpf-more-folder-id');
        if (self._moreShowIds) {
            $fid.find('.kookoawpf-more-label').text(s.hideFolderId);
            $fid.addClass('kookoawpf-more-active');
        } else {
            $fid.find('.kookoawpf-more-label').text(s.displayFolderId);
            $fid.removeClass('kookoawpf-more-active');
        }
    };

    /**
     * Show or hide the empty-state panel based on folder count.
     */
    FO._toggleEmptyState = function(count) {
        const $empty = $('#kookoawpf-empty-state');
        const $tree  = $('#kookoawpf-tree-container');
        if (parseInt(count, 10) === 0) {
            $tree.hide();
            // Always reset to the base image when the empty state (re)appears,
            // e.g. after deleting the last folder. The `--active` class only
            // applies while the "first folder" modal is open.
            $empty.removeClass('kookoawpf-empty-state--active').show();
        } else {
            $empty.hide();
            $tree.show();
        }
    };

    /**
     * Repaint the bottom-of-sidebar stats panel: Folders / Smart / Pin / Lock
     * counts. Hidden when the user disables the "Folder stats" setting.
     *
     * @param {boolean} fromTree Read counts from FO.treeData (initial paint)
     *                           instead of the live jstree instance.
     */
    FO._updateFreeLimits = function(fromTree) {
        const $box = $('#kookoawpf-free-limits');
        if (!$box.length) return;

        if (!this.data.showFolderStats) { $box.hide(); return; }

        let folders = 0, smart = 0, pin = 0, lock = 0;
        if (fromTree) {
            const tree = this.treeData || [];
            (function walk(nodes) {
                for (let i = 0; i < nodes.length; i++) {
                    const n = nodes[i];
                    const d = n.data || {};
                    if (d.is_dynamic) { smart++; } else { folders++; }
                    if (d.pinned) pin++;
                    if (d.locked) lock++;
                    if (n.children && n.children.length) walk(n.children);
                }
            })(tree);
        } else {
            const inst = this.tree ? this.tree.jstree(true) : null;
            const allNodes = inst ? inst.get_json('#', { flat: true }) : [];
            for (let j = 0; j < allNodes.length; j++) {
                const d2 = allNodes[j].data || {};
                if (d2.is_dynamic) { smart++; } else { folders++; }
                if (d2.pinned) pin++;
                if (d2.locked) lock++;
            }
        }

        const isPremium = !!(this.data && this.data.isPremium);
        // FASE 4 — paid license ever activated. When the live Freemius
        // state is still premium, we render "Thanks for going PRO" as
        // usual. When premium has lapsed (Freemius disconnect, license
        // detached, etc.) but FASE 4 is set, we render an "ACTIVATE
        // LICENSE" CTA pointing to the settings/license-entry page —
        // no upsell, no trial nudge, just "click here to reconnect".
        const paidEver = !!(this.data && this.data.paidCustomerEver);
        let html = '';
        if (isPremium) {
            // Active license or trial — full PRO. Just say thanks.
            html += '<div class="kookoawpf-free-limits-upgrade-wrap"><span class="kookoawpf-free-limits-upgrade kookoawpf-free-limits-thanks">Thanks for going PRO</span></div>';
        } else if (paidEver) {
            // FASE 4 customer, not currently premium. Two flavours:
            //  - PRO loaded but disconnected → "ACTIVATE LICENSE", link
            //    goes to Settings (license-entry form, upgradeUrl
            //    overridden by PRO to ?page=kookoa-folders).
            //  - PRO uninstalled → "Upgrade to PRO", link goes to the
            //    pricing page which now renders the "you're already a
            //    PRO customer, reinstall + activate" message.
            const proLoaded   = !!(this.data && this.data.proLoaded);
            const fase4Url    = (this.data && this.data.upgradeUrl) ? this.data.upgradeUrl : '#';
            const fase4Label  = proLoaded ? 'ACTIVATE LICENSE' : 'Upgrade to PRO';
            html += '<div class="kookoawpf-free-limits-upgrade-wrap"><span class="kookoawpf-free-limits-version">KK&gt;<span class="kookoawpf-brand-cursor">_</span> Lite Version</span><a href="' + fase4Url + '" class="kookoawpf-free-limits-upgrade">' + fase4Label + '</a></div>';
        } else {
            const upgradeUrl = (this.data && this.data.upgradeUrl) ? this.data.upgradeUrl : '#';
            // CTA label priority:
            //   1. PRO-injected override (`upgradeLabel`) — wins when set.
            //      Used by PRO for the "pre-engagement" state (PRO installed,
            //      no license, no trial, no consumed trial) to show
            //      "ACTIVATE LICENSE" instead of nudging toward a trial.
            //   2. trial_used flag — fase 3 (trial consumed) → "Upgrade to PRO".
            //   3. default — fase 1 (trial never used) → "TRY PRO FREE".
            const ctaLabel = (this.data && this.data.upgradeLabel)
                ? this.data.upgradeLabel
                : ((this.data && this.data.trialUsed) ? 'Upgrade to PRO' : 'TRY PRO FREE');
            html += '<div class="kookoawpf-free-limits-upgrade-wrap"><span class="kookoawpf-free-limits-version">KK&gt;<span class="kookoawpf-brand-cursor">_</span> Lite Version</span><a href="' + upgradeUrl + '" class="kookoawpf-free-limits-upgrade">' + ctaLabel + '</a></div>';
        }
        html += '<div class="kookoawpf-free-limits-row">';
        html += '<span>Folders <em>' + folders + '</em></span>';
        html += '<span>Smart <em>' + smart + '</em></span>';
        html += '<span>Pin <em>' + pin + '</em></span>';
        html += '<span>Lock <em>' + lock + '</em></span>';
        html += '</div>';
        $box.html(html).show();
    };

    FO._updateNoFolderState = function() {
        const self = this;
        const inst = self.tree && self.tree.jstree(true);
        const allNodes = inst ? inst.get_json('#', { flat: true }) : [];
        const folderCount = allNodes.length;
        $('#kookoawpf-folder-count').text(folderCount);
        self._toggleEmptyState(folderCount);
        const cls = 'kookoawpf-ui-disabled';

        // ── Sidebar controls ──
        const $search = $('#kookoawpf-search-folders');
        const $sort   = $('#kookoawpf-btn-sort');
        const $more   = $('#kookoawpf-btn-more');
        const $fbToggle = $('.kookoawpf-fb-toggle');

        // ── ⋮ menu items ──
        const $bulkSelect = $('#kookoawpf-more-bulk-select');
        const $folderId   = $('#kookoawpf-more-folder-id');
        const $export     = $('#kookoawpf-more-export');

        // ⋮ menu is ALWAYS enabled (Import is always available)
        $more.removeClass(cls);

        if (folderCount === 0) {
            $search.addClass(cls).prop('disabled', true);
            $sort.addClass(cls);
            $fbToggle.addClass(cls);
            // Close sort dropdown
            $('#kookoawpf-sort-dropdown').hide();

            // Inside ⋮: disable everything except Import (and Export if folders exist in other post types)
            $bulkSelect.addClass(cls);
            $folderId.addClass(cls);
            if (self._totalFoldersAll > 0) {
                $export.removeClass(cls);
            } else {
                $export.addClass(cls);
            }
        } else {
            $fbToggle.removeClass(cls);
            $bulkSelect.removeClass(cls);
            $folderId.removeClass(cls);
            $export.removeClass(cls);

            // ── Search: enable only if at least 2 folders total ──
            if (folderCount >= 2) {
                $search.removeClass(cls).prop('disabled', false);
            } else {
                $search.addClass(cls).prop('disabled', true);
            }

            // ── Sort: enable only if at least 2 siblings at any level ──
            let hasSortableSiblings = false;
            if (inst) {
                // Check root level: 2+ top-level folders
                const rootChildren = inst.get_node('#').children;
                if (rootChildren && rootChildren.length >= 2) {
                    hasSortableSiblings = true;
                }
                // Check child levels: any parent with 2+ children
                if (!hasSortableSiblings) {
                    for (let i = 0; i < allNodes.length; i++) {
                        const node = inst.get_node(allNodes[i].id);
                        if (node && node.children && node.children.length >= 2) {
                            hasSortableSiblings = true;
                            break;
                        }
                    }
                }
            }
            if (hasSortableSiblings) {
                $sort.removeClass(cls);
            } else {
                $sort.addClass(cls);
                $('#kookoawpf-sort-dropdown').hide();
            }
        }

        // ── Has subfolders check for Expand/Collapse All ──
        let hasSubfolders = false;
        if (inst && folderCount > 0) {
            for (let i = 0; i < allNodes.length; i++) {
                const node = inst.get_node(allNodes[i].id);
                if (node && node.children && node.children.length > 0) {
                    hasSubfolders = true;
                    break;
                }
            }
        }
        const $expand = $('#kookoawpf-more-expand');
        if (!hasSubfolders) {
            $expand.addClass(cls);
        } else {
            $expand.removeClass(cls);
        }
    };

    /**
     * Add or remove folder ID badges (#N) before the folder name.
     */
    FO._applyFolderIdBadges = function() {
        const self = this;
        // Remove existing badges
        self.tree.find('.kookoawpf-folder-id-badge').remove();

        if (!self._moreShowIds) return;

        self.tree.find('.jstree-node').each(function() {
            const $node = $(this);
            const nodeData = self.tree.jstree('get_node', $node.attr('id'));
            if (nodeData && nodeData.data) {
                const folderId = nodeData.data.folder_id;
                if (folderId) {
                    const $textSpan = $node.children('.jstree-anchor').find('.kookoawpf-folder-text');
                    if ($textSpan.length && !$textSpan.prev('.kookoawpf-folder-id-badge').length) {
                        $textSpan.before('<span class="kookoawpf-folder-id-badge">#' + folderId + '</span>');
                    }
                }
            }
        });
    };

})(jQuery);
