/**
 * EMRS — Main UI Script
 * Features: sidebar, dark mode, topbar dropdowns, global search,
 *           table sort, inline search, animated counters, confirm-delete,
 *           form spinners, auto-dismiss alerts.
 */

document.addEventListener('DOMContentLoaded', function () {

    // ── Sidebar toggle ─────────────────────────────────────────
    const sidebar   = document.getElementById('erpSidebar');
    const overlay   = document.getElementById('erpOverlay');
    const toggleBtn = document.getElementById('sidebarToggle');

    function openSidebar()  {
        sidebar?.classList.add('show');
        overlay?.classList.add('show');
        document.body.style.overflow = 'hidden';
    }
    function closeSidebar() {
        sidebar?.classList.remove('show');
        overlay?.classList.remove('show');
        document.body.style.overflow = '';
    }
    function isMobile() { return window.innerWidth < 992; }

    toggleBtn?.addEventListener('click', () => {
        if (isMobile()) {
            sidebar?.classList.contains('show') ? closeSidebar() : openSidebar();
        } else {
            document.body.classList.toggle('sidebar-collapsed');
            try { localStorage.setItem('sidebar_collapsed', document.body.classList.contains('sidebar-collapsed')); }
            catch(e) {}
        }
    });
    overlay?.addEventListener('click', closeSidebar);
    sidebar?.querySelectorAll('.erp-nav-link').forEach(l => l.addEventListener('click', () => { if (isMobile()) closeSidebar(); }));

    // Restore desktop collapse state
    if (!isMobile()) {
        try { if (localStorage.getItem('sidebar_collapsed') === 'true') document.body.classList.add('sidebar-collapsed'); }
        catch(e) {}
    }

    // ── Dark Mode ──────────────────────────────────────────────
    const html        = document.documentElement;
    const dmToggle    = document.getElementById('darkModeToggle');
    const dmIcon      = document.getElementById('darkModeIcon');
    const mobileDmBtn = document.getElementById('mobileDarkToggle');
    const mobileDmIco = document.getElementById('mobileDarkIcon');
    const mobileDmLbl = document.getElementById('mobileDarkLabel');

    function applyTheme(dark) {
        html.setAttribute('data-theme', dark ? 'dark' : '');
        // Desktop icon
        if (dmIcon) dmIcon.className = dark ? 'bi bi-sun-fill' : 'bi bi-moon-stars-fill';
        // Mobile icon + label
        if (mobileDmIco) mobileDmIco.className = dark
            ? 'bi bi-sun-fill me-2 text-warning'
            : 'bi bi-moon-stars-fill me-2 text-primary';
        if (mobileDmLbl) mobileDmLbl.textContent = dark ? 'Light Mode' : 'Dark Mode';
        try { localStorage.setItem('emrs_theme', dark ? 'dark' : 'light'); } catch(e) {}
    }

    // Load saved preference
    (function initTheme() {
        try {
            const saved = localStorage.getItem('emrs_theme');
            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            applyTheme(saved ? saved === 'dark' : prefersDark);
        } catch(e) { applyTheme(false); }
    })();

    dmToggle?.addEventListener('click', () => {
        applyTheme(html.getAttribute('data-theme') !== 'dark');
    });
    mobileDmBtn?.addEventListener('click', () => {
        applyTheme(html.getAttribute('data-theme') !== 'dark');
    });

    // ── Topbar dropdown z-index fix ───────────────────────────
    document.querySelectorAll('.erp-topbar .dropdown').forEach(dd => {
        const btn  = dd.querySelector('[data-bs-toggle="dropdown"]');
        const menu = dd.querySelector('.dropdown-menu');
        if (!btn || !menu) return;

        document.body.appendChild(menu);
        menu.style.cssText = 'display:none;position:fixed;z-index:99999;';

        btn.addEventListener('click', e => {
            e.stopPropagation();
            const isOpen = menu.classList.contains('erp-dd-open');

            document.querySelectorAll('.erp-dd-open').forEach(m => {
                m.classList.remove('erp-dd-open'); m.style.display = 'none';
            });

            if (!isOpen) {
                const rect = btn.getBoundingClientRect();
                const isDark = html.getAttribute('data-theme') === 'dark';
                Object.assign(menu.style, {
                    display:      'block',
                    position:     'fixed',
                    zIndex:       '99999',
                    top:          '56px',
                    right:        (window.innerWidth - rect.right) + 'px',
                    left:         'auto',
                    minWidth:     '260px',
                    maxHeight:    (window.innerHeight - 70) + 'px',
                    overflowY:    'auto',
                    borderRadius: '12px',
                    boxShadow:    '0 8px 32px rgba(0,0,0,.22)',
                    border:       '1px solid ' + (isDark ? '#2d3748' : '#e2e8f0'),
                    background:   isDark ? '#1a1d2e' : '#fff'
                });
                menu.classList.add('erp-dd-open');
            }
        });
    });

    document.addEventListener('click', () => {
        document.querySelectorAll('.erp-dd-open').forEach(m => {
            m.classList.remove('erp-dd-open'); m.style.display = 'none';
        });
    });
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape') {
            document.querySelectorAll('.erp-dd-open').forEach(m => {
                m.classList.remove('erp-dd-open'); m.style.display = 'none';
            });
        }
    });

    // Mobile search trigger
    document.getElementById('mobileSearchBtn')?.addEventListener('click', () => {
        const modal = document.getElementById('globalSearchModal');
        if (modal && window.bootstrap) {
            bootstrap.Modal.getOrCreateInstance(modal).show();
            setTimeout(() => document.getElementById('globalSearchInput')?.focus(), 200);
        }
    });

    // ── Global Search (Ctrl+K) ────────────────────────────────
    (function initGlobalSearch() {
        const modal   = document.getElementById('globalSearchModal');
        const input   = document.getElementById('globalSearchInput');
        const results = document.getElementById('globalSearchResults');
        if (!modal || !input) return;

        const bsModal = new bootstrap.Modal(modal);

        document.addEventListener('keydown', e => {
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                bsModal.show();
                setTimeout(() => input.focus(), 200);
            }
        });
        document.getElementById('globalSearchBtn')?.addEventListener('click', () => {
            bsModal.show();
            setTimeout(() => input.focus(), 200);
        });
        modal.addEventListener('shown.bs.modal', () => input.focus());

        const searchLinks = [
            { label:'Consumers',   icon:'bi-person-badge-fill', url: BASE_URL + '/modules/admin/consumers.php?q=' },
            { label:'Solar Report',icon:'bi-sun-fill',          url: BASE_URL + '/modules/reports/index.php?type=solar&q=' },
            { label:'KCC Report',  icon:'bi-lightning-fill',    url: BASE_URL + '/modules/reports/index.php?type=kcc&q=' },
            { label:'Users',       icon:'bi-people-fill',       url: BASE_URL + '/modules/admin/users.php?q=' },
        ];

        let debounce;
        input.addEventListener('input', () => {
            clearTimeout(debounce);
            debounce = setTimeout(() => {
                const q = input.value.trim();
                if (!q) { results.innerHTML = ''; return; }
                results.innerHTML = searchLinks.map(l => `
                    <a href="${l.url}${encodeURIComponent(q)}"
                       class="global-search-result d-flex align-items-center gap-3 text-decoration-none">
                        <span style="width:34px;height:34px;border-radius:8px;background:#e8eaf6;
                                     display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                            <i class="bi ${l.icon}" style="color:#1a237e;"></i>
                        </span>
                        <div>
                            <div style="font-size:.88rem;font-weight:600;">Search "${escHtml(q)}" in ${l.label}</div>
                        </div>
                        <i class="bi bi-arrow-right ms-auto text-muted"></i>
                    </a>`).join('');
            }, 200);
        });

        // Keyboard nav in results
        results.addEventListener('click', () => bsModal.hide());
    })();

    // ── Table column sort ─────────────────────────────────────
    (function initTableSort() {
        document.querySelectorAll('table[data-sortable]').forEach(table => {
            table.querySelectorAll('thead th[data-sort]').forEach((th, colIdx) => {
                let asc = true;
                th.addEventListener('click', () => {
                    const tbody = table.querySelector('tbody');
                    const rows  = Array.from(tbody.querySelectorAll('tr'));
                    rows.sort((a, b) => {
                        const av = a.cells[colIdx]?.textContent.trim() ?? '';
                        const bv = b.cells[colIdx]?.textContent.trim() ?? '';
                        const an = parseFloat(av.replace(/[₹,%\s]/g, ''));
                        const bn = parseFloat(bv.replace(/[₹,%\s]/g, ''));
                        if (!isNaN(an) && !isNaN(bn)) return asc ? an - bn : bn - an;
                        return asc ? av.localeCompare(bv) : bv.localeCompare(av);
                    });
                    rows.forEach(r => tbody.appendChild(r));
                    // Update sort icons
                    table.querySelectorAll('thead th[data-sort]').forEach(h => h.classList.remove('sort-asc','sort-desc'));
                    th.classList.add(asc ? 'sort-asc' : 'sort-desc');
                    asc = !asc;
                });
            });
        });
    })();

    // ── Inline table search ───────────────────────────────────
    (function initInlineSearch() {
        document.querySelectorAll('[data-search-table]').forEach(input => {
            const tableId = input.getAttribute('data-search-table');
            const table   = document.getElementById(tableId);
            if (!table) return;
            input.addEventListener('input', () => {
                const q = input.value.toLowerCase();
                table.querySelectorAll('tbody tr').forEach(row => {
                    row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
                });
            });
        });
    })();

    // ── Animated number counters ──────────────────────────────
    (function initCounters() {
        const els = document.querySelectorAll('[data-count-to]');
        if (!els.length) return;

        const observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                if (!entry.isIntersecting) return;
                const el      = entry.target;
                const target  = parseFloat(el.getAttribute('data-count-to')) || 0;
                const prefix  = el.getAttribute('data-prefix') || '';
                const suffix  = el.getAttribute('data-suffix') || '';
                const dec     = parseInt(el.getAttribute('data-decimals') || '0');
                const dur     = 1200;
                const step    = 16;
                const inc     = target / (dur / step);
                let   current = 0;

                const timer = setInterval(() => {
                    current = Math.min(current + inc, target);
                    el.textContent = prefix + current.toFixed(dec) + suffix;
                    if (current >= target) clearInterval(timer);
                }, step);

                observer.unobserve(el);
            });
        }, { threshold: .3 });

        els.forEach(el => observer.observe(el));
    })();

    // ── Confirm delete ────────────────────────────────────────
    (function initConfirmDelete() {
        document.querySelectorAll('[data-confirm]').forEach(el => {
            el.addEventListener('click', e => {
                const msg = el.getAttribute('data-confirm') || 'Are you sure?';
                if (!confirm(msg)) e.preventDefault();
            });
        });
        // Also handle forms with onsubmit="return confirm(...)" already handled natively
    })();

    // ── Auto-dismiss alerts ───────────────────────────────────
    document.querySelectorAll('.alert-success, .alert-info').forEach(el => {
        if (el.closest('#alertContainer') || el.classList.contains('alert-dismissible')) {
            setTimeout(() => {
                el.style.transition = 'opacity .4s';
                el.style.opacity    = '0';
                setTimeout(() => el.remove(), 420);
            }, 4500);
        }
    });

    // ── Form loading spinners ─────────────────────────────────
    document.querySelectorAll('form:not(.no-spinner)').forEach(form => {
        form.addEventListener('submit', () => {
            const btn = form.querySelector('[type=submit]:not([data-no-spinner])');
            if (!btn || btn.disabled) return;
            btn.disabled = true;
            btn.dataset.origHtml = btn.innerHTML;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing…';
            // Safety re-enable
            setTimeout(() => {
                if (btn.disabled && btn.dataset.origHtml) {
                    btn.disabled = false;
                    btn.innerHTML = btn.dataset.origHtml;
                }
            }, 20000);
        });
    });

    // ── Bootstrap tooltips ────────────────────────────────────
    document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
        new bootstrap.Tooltip(el, { trigger: 'hover' });
    });

});

// ── Shared escape helper (used by app.js too) ─────────────────
function escHtml(str) {
    return String(str)
        .replace(/&/g,'&amp;').replace(/</g,'&lt;')
        .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
