document.addEventListener('DOMContentLoaded', function(){
    const k = 'gopools_theme';
    const h = document.documentElement;
    const b = document.querySelector('[data-theme-toggle]');
    
    let currentTheme = window.dbTheme;
    if (!currentTheme || currentTheme === 'system') {
        currentTheme = localStorage.getItem(k) || window.defaultThemeMode || 'dark';
    }
    h.setAttribute('data-theme', currentTheme);
    localStorage.setItem(k, currentTheme);

    if(b){
        b.addEventListener('click', function(e){
            e.preventDefault();
            const n = h.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
            h.setAttribute('data-theme', n);
            localStorage.setItem(k, n);
            fetch('/gopools/public/api/theme_sync.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({theme: n})
            }).catch(() => {});
        });
    }

    // Notifications
    const markAllBtn = document.getElementById('mark-all-read-btn');
    if (markAllBtn) {
        markAllBtn.addEventListener('click', function(e){
            e.preventDefault();
            e.stopPropagation();
            fetch('/gopools/public/api/notifications_read.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({mark_all: true})
            }).then(() => {
                document.querySelectorAll('a.unread').forEach(el => {
                    el.classList.remove('unread');
                    el.style.background = '';
                    const span = el.querySelector('span');
                    if(span) span.style.fontWeight = '400';
                });
                const badge = document.querySelector('.btn-bell span');
                if(badge) badge.remove();
                markAllBtn.remove();
            });
        });
    }

    // Global Search
    const searchInput = document.getElementById('global-search-input');
    const searchResults = document.getElementById('global-search-results');
    let searchTimeout;

    if (searchInput && searchResults) {
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const q = this.value.trim();
            if (q.length < 2) {
                searchResults.style.display = 'none';
                return;
            }
            searchTimeout = setTimeout(() => {
                fetch('/gopools/public/api/global_search.php?q=' + encodeURIComponent(q))
                .then(r => r.json())
                .then(data => {
                    if (data.length === 0) {
                        searchResults.innerHTML = '<div style="padding:10px;color:var(--gp-muted);text-align:center;">No results found</div>';
                    } else {
                        searchResults.innerHTML = data.map(item => `
                            <a href="${item.url}" style="display:flex; flex-direction:column; padding:10px 12px; border-bottom:1px solid var(--gp-card-border); text-decoration:none; color:var(--gp-text);">
                                <span style="font-size:0.7rem; color:var(--gp-primary); text-transform:uppercase; font-weight:700;">${item.type}</span>
                                <span style="font-size:0.9rem;">${item.label}</span>
                            </a>
                        `).join('');
                    }
                    searchResults.style.display = 'block';
                });
            }, 300);
        });

        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !searchResults.contains(e.target)) {
                searchResults.style.display = 'none';
            }
        });

        // Keyboard shortcut: / to focus global search
        document.addEventListener('keydown', function(e) {
            if (e.key === '/' && !['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName)) {
                e.preventDefault();
                searchInput.focus();
            }
        });
    }

    // ─── Reusable Table Search ─────────────────────────────────
    // Usage: add `data-table-search` to any input, and `data-table-searchable` to the target table.
    // Or call gpTableSearch(inputEl, tableEl) programmatically.
    window.gpTableSearch = function(inputEl, tableEl) {
        if (!inputEl || !tableEl) return;
        const tbody = tableEl.querySelector('tbody');
        if (!tbody) return;

        const countEl = inputEl.parentElement?.querySelector('[data-search-count]');

        inputEl.addEventListener('input', function() {
            const q = this.value.toLowerCase().trim();
            const rows = tbody.querySelectorAll('tr');
            let visible = 0;

            rows.forEach(function(row) {
                const text = row.textContent.toLowerCase();
                const match = !q || text.indexOf(q) !== -1;
                row.style.display = match ? '' : 'none';
                if (match) visible++;
            });

            if (countEl) {
                countEl.textContent = q ? visible + ' of ' + rows.length : rows.length + ' total';
            }
        });
    };

    // Auto-init: find all [data-table-search] inputs
    document.querySelectorAll('[data-table-search]').forEach(function(input) {
        const targetId = input.getAttribute('data-table-search');
        const table = targetId ? document.getElementById(targetId) : input.closest('.card')?.querySelector('table');
        if (table) window.gpTableSearch(input, table);
    });
});