/**
 * 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;
    }

    function openSection($section) {
        $section.addClass('sidebar-section--open');
        $section.children('.sectionHeader').attr('aria-expanded', 'true');
    }

    function closeSection($section) {
        $section.removeClass('sidebar-section--open');
        $section.children('.sectionHeader').attr('aria-expanded', 'false');
    }

    /**
     * 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;

        // Platform-aware placeholder (⌘K on Mac, Ctrl+K elsewhere)
        const isMac = /Mac|iPod|iPhone|iPad/.test(navigator.platform || navigator.userAgent);
        $searchInput.attr('placeholder', isMac ? 'Search menu (⌘K)' : 'Search menu (Ctrl+K)');

        // --- 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 (guard for pages that don't
            // render the search input — .val() is undefined on an empty set).
            const searchValue = $searchInput.val();
            if (searchValue && searchValue.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');

                closeSection($section);

                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');
                    closeSection($section);
                    $section.addClass('sidebar-section--search-visible');
                    $section.children('.sectionHeader').attr('aria-expanded', 'true');
                    totalMatches += Math.max(sectionMatchCount, 1);
                } else {
                    $section.removeClass('sidebar-section--search-visible');
                    closeSection($section);
                    $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();
            } else if (e.keyCode === 13) { // Enter — open highlighted/first visible link
                e.preventDefault();
                let $target = $sections.find('a.sidebar-search-highlight').filter(':visible').first();
                if (!$target.length) {
                    $target = $sections.find('ul > li:visible > a').first();
                }
                const href = $target.attr('href');
                if (href) {
                    window.location.href = href;
                }
            }
        });

        // Ctrl/Cmd+K focuses search
        $(document).on('keydown', function (e) {
            if ((e.ctrlKey || e.metaKey) && (e.keyCode === 75 || e.key === 'k' || e.key === 'K')) {
                if ($searchInput.length && $searchInput.is(':visible')) {
                    e.preventDefault();
                    $searchInput.focus().select();
                }
            }
        });
    });
})(jQuery);
