/**
 * Reports & Accounting module hub — sidebar search, mobile nav, date presets, export feedback
 */
(function () {
    'use strict';

    const hub = document.querySelector('[data-module-hub]');
    if (!hub) return;

    /* Mobile sidebar */
    const toggleBtn = hub.querySelector('[data-hub-toggle]');
    const sidebarCol = hub.querySelector('[data-hub-sidebar]');
    const backdrop = hub.querySelector('[data-hub-backdrop]');

    function closeSidebar() {
        sidebarCol?.classList.remove('is-open');
        backdrop?.classList.remove('is-open');
        document.body.style.overflow = '';
    }

    function openSidebar() {
        sidebarCol?.classList.add('is-open');
        backdrop?.classList.add('is-open');
        document.body.style.overflow = 'hidden';
    }

    toggleBtn?.addEventListener('click', function () {
        if (sidebarCol?.classList.contains('is-open')) {
            closeSidebar();
        } else {
            openSidebar();
        }
    });

    backdrop?.addEventListener('click', closeSidebar);

    hub.querySelectorAll('.hub-sidebar__menu .nav-link').forEach(function (link) {
        link.addEventListener('click', function () {
            if (window.innerWidth < 992) closeSidebar();
        });
    });

    /* Sidebar search */
    const searchInput = hub.querySelector('[data-hub-search]');
    if (searchInput) {
        searchInput.addEventListener('input', function () {
            const q = this.value.trim().toLowerCase();
            hub.querySelectorAll('[data-hub-menu-item]').forEach(function (item) {
                const text = (item.textContent || '').toLowerCase();
                item.classList.toggle('is-hidden', q.length > 0 && !text.includes(q));
            });
            hub.querySelectorAll('[data-hub-menu-group]').forEach(function (group) {
                const visible = group.querySelectorAll('[data-hub-menu-item]:not(.is-hidden)').length;
                group.style.display = visible === 0 && q.length > 0 ? 'none' : '';
            });
        });
    }

    /* Date presets */
    hub.querySelectorAll('[data-date-preset]').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            const form = hub.querySelector('[data-hub-filter-form]');
            if (!form) return;

            const fromInput = form.querySelector('[name="date_from"]');
            const toInput = form.querySelector('[name="date_to"]');
            if (!fromInput || !toInput) return;

            const preset = this.getAttribute('data-date-preset');
            const today = new Date();
            let from = new Date(today);
            let to = new Date(today);

            if (preset === 'this_month') {
                from = new Date(today.getFullYear(), today.getMonth(), 1);
            } else if (preset === 'last_month') {
                from = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                to = new Date(today.getFullYear(), today.getMonth(), 0);
            } else if (preset === 'last_30') {
                from.setDate(from.getDate() - 29);
            } else if (preset === 'this_fy') {
                const y = today.getMonth() >= 3 ? today.getFullYear() : today.getFullYear() - 1;
                from = new Date(y, 3, 1);
            }

            fromInput.value = formatDateInput(from);
            toInput.value = formatDateInput(to);

            hub.querySelectorAll('[data-date-preset]').forEach(function (b) {
                b.classList.remove('active');
            });
            this.classList.add('active');

            if (form.dataset.autoSubmit !== 'false') {
                form.submit();
            }
        });
    });

    function formatDateInput(d) {
        const y = d.getFullYear();
        const m = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return y + '-' + m + '-' + day;
    }

    /* Export buttons loading state */
    hub.querySelectorAll('[data-hub-export]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            const self = this;
            if (self.classList.contains('is-loading')) return;
            self.classList.add('is-loading');
            const icon = self.querySelector('i');
            if (icon) {
                icon.className = 'ri-loader-4-line ri-spin';
            }
            setTimeout(function () {
                self.classList.remove('is-loading');
                if (icon && self.dataset.exportIcon) {
                    icon.className = self.dataset.exportIcon;
                }
            }, 8000);
        });
    });

    /* Month selects auto-submit */
    hub.querySelectorAll('[data-month-auto-submit]').forEach(function (sel) {
        sel.addEventListener('change', function () {
            const form = this.closest('form');
            if (form) form.submit();
        });
    });
})();
