/**
 * Elementor frontend handler for the Side Menu ( dashboard sidebar ) widget.
 *
 * Handles expandable accordion sub-menus, the collapse ( icons-only ) toggle
 * with optional localStorage persistence, and a smart collapsed-state click that
 * first expands the sidebar before opening a group. Keeps ARIA in sync and tears
 * down cleanly on editor re-render.
 *
 * @package captain-widgets-kit
 * @since   1.6.0
 */

(function ($) {
    'use strict';

    /**
     * Per-instance handler — called by Elementor for every widget instance.
     *
     * @param {jQuery} $scope - The widget wrapper element.
     */
    var CaptwikiSideNavHandler = function ($scope) {

        var root = $scope[0].querySelector('.captwiki-sidenav');
        if (!root) {
            return;
        }

        // Re-run safe: tear down a previous controller on editor re-render.
        if (root._cwkSideNavTeardown) {
            root._cwkSideNavTeardown();
        }

        var accordion = root.getAttribute('data-accordion') === 'yes';
        var remember = root.getAttribute('data-remember') === 'yes';
        var uid = root.getAttribute('data-uid') || '';
        var storageKey = 'captwiki-sidenav-' + uid;

        var toggle = root.querySelector('.captwiki-sidenav__toggle');
        var parents = Array.prototype.slice.call(root.querySelectorAll('.captwiki-sidenav__item--has-sub'));

        var handlers = [];

        var on = function (el, evt, fn) {
            el.addEventListener(evt, fn);
            handlers.push(function () {
                el.removeEventListener(evt, fn);
            });
        };

        var isCollapsed = function () {
            return root.classList.contains('is-collapsed');
        };

        /**
         * Open / close a parent group.
         *
         * @param {Element} item - The parent list item.
         * @param {boolean} open - Desired state.
         */
        var setGroup = function (item, open) {
            item.classList.toggle('is-open', open);
            var btn = item.querySelector('.captwiki-sidenav__link--parent');
            if (btn) {
                btn.setAttribute('aria-expanded', open ? 'true' : 'false');
            }
        };

        /**
         * Restore persisted collapsed state ( if remembering ).
         */
        var restoreState = function () {
            if (!remember) {
                return;
            }
            try {
                var saved = window.localStorage.getItem(storageKey);
                if (saved === 'collapsed') {
                    root.classList.add('is-collapsed');
                } else if (saved === 'expanded') {
                    root.classList.remove('is-collapsed');
                }
            } catch (e) {
                /* localStorage unavailable — ignore. */
            }
            if (toggle) {
                toggle.setAttribute('aria-expanded', isCollapsed() ? 'false' : 'true');
            }
        };

        var persistState = function () {
            if (!remember) {
                return;
            }
            try {
                window.localStorage.setItem(storageKey, isCollapsed() ? 'collapsed' : 'expanded');
            } catch (e) {
                /* ignore */
            }
        };

        /* ── Collapse toggle ───────────────────────────────── */
        if (toggle) {
            on(toggle, 'click', function (e) {
                e.preventDefault();
                root.classList.toggle('is-collapsed');
                toggle.setAttribute('aria-expanded', isCollapsed() ? 'false' : 'true');
                if (isCollapsed()) {
                    // Close every open group when shrinking.
                    parents.forEach(function (item) {
                        setGroup(item, false);
                    });
                }
                persistState();
            });
        }

        /* ── Parent group toggles ──────────────────────────── */
        parents.forEach(function (item) {
            var btn = item.querySelector('.captwiki-sidenav__link--parent');
            if (!btn) {
                return;
            }

            on(btn, 'click', function (e) {
                e.preventDefault();

                // If collapsed, expand the sidebar first so the group is usable.
                if (isCollapsed()) {
                    root.classList.remove('is-collapsed');
                    if (toggle) {
                        toggle.setAttribute('aria-expanded', 'true');
                    }
                    persistState();
                }

                var willOpen = !item.classList.contains('is-open');

                if (accordion && willOpen) {
                    parents.forEach(function (other) {
                        if (other !== item) {
                            setGroup(other, false);
                        }
                    });
                }

                setGroup(item, willOpen);
            });
        });

        restoreState();

        /* ── Teardown ──────────────────────────────────────── */
        root._cwkSideNavTeardown = function () {
            handlers.forEach(function (off) {
                off();
            });
            handlers = [];
            root._cwkSideNavTeardown = null;
        };
    };

    /* ── Register with Elementor frontend ───────────────────── */
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/captwiki-side-menu.default',
            CaptwikiSideNavHandler
        );
    });

})(jQuery);
