/**
 * Admin Sidebar Navigation
 * Collapsible sections with localStorage persistence and search filtering.
 */
(function ($) {
    'use strict';

    const STORAGE_KEY = 'admin_sidebar_sections';
    const DEBOUNCE_MS = 150;

    /**
     * Load saved section states from localStorage.
     * Returns an object keyed by section-id with boolean open/closed values.
     */
    function loadSavedStates() {
        try {
            const raw = localStorage.getItem(STORAGE_KEY);
            return raw ? JSON.parse(raw) : {};
        } catch (e) {
            return {};
        }
    }

    /**
     * Persist section states to localStorage.
     */
    function saveStates(states) {
        try {
            localStorage.setItem(STORAGE_KEY, JSON.stringify(states));
        } catch (e) {
            // localStorage unavailable — silently ignore
        }
    }

    /**
     * Check whether a section <li> has an active child.
     */
    function hasActiveChild($section) {
        return $section.find('li.active').length > 0 || $section.find('ul.show').length > 0;
    }

    /**
     * Open a section (add class).
     */
    function openSection($section) {
        $section.addClass('sidebar-section--open');
    }

    /**
     * Close a section (remove class).
     */
    function closeSection($section) {
        $section.removeClass('sidebar-section--open');
    }

    /**
     * Simple debounce helper.
     */
    function debounce(fn, delay) {
        let timer;
        return function () {
            const context = this;
            const args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        };
    }

    $(document).ready(function () {
        const $sidebar = $('.sidebar').last();
        const $sections = $sidebar.find('.topnav > li').filter(function () {
            return $(this).find('.sectionHeader').length > 0;
        });
        const $searchInput = $sidebar.find('.sidebar-search__input');
        const $clearBtn = $sidebar.find('.sidebar-search__clear');
        let $noResults = null;

        // --- Initialise collapse states ---
        const savedStates = loadSavedStates();

        $sections.each(function () {
            const $section = $(this);
            const sectionId = $section.attr('data-section-id');

            if (hasActiveChild($section)) {
                // Always open the section containing the current page
                openSection($section);
            } else if (sectionId && savedStates[sectionId] === true) {
                openSection($section);
            }
            // Otherwise leave collapsed (no class)
        });

        // --- Section header click ---
        $sections.find('.sectionHeader').on('click', function (e) {
            // Don't toggle during search mode
            if ($searchInput.val().trim() !== '') {
                return;
            }

            const $section = $(this).closest('li');
            const sectionId = $section.attr('data-section-id');
            const isOpen = $section.hasClass('sidebar-section--open');

            if (isOpen) {
                closeSection($section);
            } else {
                openSection($section);
            }

            // Persist
            if (sectionId) {
                const states = loadSavedStates();
                states[sectionId] = !isOpen;
                saveStates(states);
            }
        });

        // --- Search ---

        function clearSearch() {
            $searchInput.val('');
            $clearBtn.hide();

            // Remove search-mode classes
            $sections.removeClass('sidebar-section--search-visible sidebar-section--search-hidden');
            $sections.find('li').show();
            $sections.find('.sidebar-search-highlight').removeClass('sidebar-search-highlight');

            // Remove no-results message
            if ($noResults) {
                $noResults.remove();
                $noResults = null;
            }

            // Restore saved collapse states
            const states = loadSavedStates();
            $sections.each(function () {
                const $section = $(this);
                const sectionId = $section.attr('data-section-id');

                $section.removeClass('sidebar-section--open');

                if (hasActiveChild($section)) {
                    openSection($section);
                } else if (sectionId && states[sectionId] === true) {
                    openSection($section);
                }
            });
        }

        function performSearch(query) {
            query = query.trim().toLowerCase();

            if (query === '') {
                clearSearch();
                return;
            }

            $clearBtn.show();

            // Remove previous no-results
            if ($noResults) {
                $noResults.remove();
                $noResults = null;
            }

            let totalMatches = 0;

            $sections.each(function () {
                const $section = $(this);
                const $header = $section.find('.sectionHeader');
                const headerText = $header.text().trim().toLowerCase();
                const headerMatches = headerText.indexOf(query) !== -1;
                const $items = $section.find('ul > li');
                let sectionMatchCount = 0;

                $items.each(function () {
                    const $item = $(this);
                    const $link = $item.find('a');
                    const linkText = $link.text().trim().toLowerCase();

                    // Always keep CMS tree items visible
                    const hasSiteTree = $link.attr('href') && $link.attr('href').indexOf('#site-tree') !== -1;

                    if (headerMatches || linkText.indexOf(query) !== -1 || hasSiteTree) {
                        $item.show();
                        if (linkText.indexOf(query) !== -1 && !hasSiteTree) {
                            $item.find('a').addClass('sidebar-search-highlight');
                        } else {
                            $item.find('a').removeClass('sidebar-search-highlight');
                        }
                        sectionMatchCount++;
                    } else {
                        $item.hide();
                        $item.find('a').removeClass('sidebar-search-highlight');
                    }
                });

                if (sectionMatchCount > 0 || headerMatches) {
                    $section.removeClass('sidebar-section--search-hidden sidebar-section--open');
                    $section.addClass('sidebar-section--search-visible');
                    totalMatches += Math.max(sectionMatchCount, 1);
                } else {
                    $section.removeClass('sidebar-section--search-visible sidebar-section--open');
                    $section.addClass('sidebar-section--search-hidden');
                }
            });

            if (totalMatches === 0) {
                $noResults = $('<div class="sidebar-no-results">No menu items found</div>');
                $sidebar.find('.topnav').last().after($noResults);
            }
        }

        $searchInput.on('keyup input', debounce(function () {
            performSearch($(this).val());
        }, DEBOUNCE_MS));

        $clearBtn.on('click', function () {
            clearSearch();
            $searchInput.focus();
        });

        // Escape key clears search
        $searchInput.on('keydown', function (e) {
            if (e.keyCode === 27) { // Escape
                clearSearch();
                $searchInput.blur();
            }
        });
    });
})(jQuery);
