/**
 * GreenAdmin - Admin Panel JavaScript
 * Supports: 3-level sidebar, desktop collapse, theme toggle, dropdowns, FAQ, DataTable
 */
(function () {
  'use strict';

  // Sidebar Manager (mobile + desktop collapse + 3-level submenu)
  const SidebarManager = {
    storageKey: 'ga-sidebar-collapsed',

    init() {
      this.sidebar = document.querySelector('.ga-sidebar');
      this.overlay = document.querySelector('.ga-overlay');
      this.hamburger = document.querySelector('.ga-hamburger');
      this.isMobile = () => window.innerWidth <= 1024;

      // Restore desktop collapsed state
      if (!this.isMobile() && localStorage.getItem(this.storageKey) === '1') {
        document.body.classList.add('sidebar-collapsed');
      }

      if (this.hamburger) {
        this.hamburger.addEventListener('click', () => {
          if (this.isMobile()) {
            this.mobileToggle();
          } else {
            this.desktopToggle();
          }
        });
      }

      if (this.overlay) {
        this.overlay.addEventListener('click', () => this.mobileClose());
      }

      // Keep mobile and desktop sidebar states from leaking into each other on resize
      let wasMobile = this.isMobile();
      window.addEventListener('resize', () => {
        const nowMobile = this.isMobile();
        if (nowMobile === wasMobile) return;
        wasMobile = nowMobile;
        if (nowMobile) {
          document.body.classList.remove('sidebar-collapsed');
        } else {
          this.mobileClose();
          if (localStorage.getItem(this.storageKey) === '1') {
            document.body.classList.add('sidebar-collapsed');
          }
        }
      });

      // Level 2 submenu toggles
      document.querySelectorAll('.ga-nav-toggle').forEach(item => {
        item.addEventListener('click', (e) => {
          e.preventDefault();
          const submenu = item.nextElementSibling;
          if (submenu && submenu.classList.contains('ga-submenu')) {
            item.classList.toggle('expanded');
            submenu.classList.toggle('open');
          }
        });
      });

      // Level 3 submenu toggles
      document.querySelectorAll('.ga-nav-toggle-l3').forEach(item => {
        item.addEventListener('click', (e) => {
          e.preventDefault();
          const submenu = item.nextElementSibling;
          if (submenu && submenu.classList.contains('ga-submenu-l3')) {
            item.classList.toggle('expanded');
            submenu.classList.toggle('open');
          }
        });
      });

      // Auto-expand active submenu on load + mark parent as has-active
      document.querySelectorAll('.ga-submenu .ga-nav-item.active, .ga-submenu-l3 .ga-nav-item.active').forEach(activeItem => {
        const l3 = activeItem.closest('.ga-submenu-l3');
        if (l3) {
          l3.classList.add('open');
          const l3Toggle = l3.previousElementSibling;
          if (l3Toggle) l3Toggle.classList.add('expanded');
        }
        const l2 = activeItem.closest('.ga-submenu');
        if (l2) {
          l2.classList.add('open');
          const l2Toggle = l2.previousElementSibling;
          if (l2Toggle) {
            l2Toggle.classList.add('expanded');
            l2Toggle.classList.add('has-active');
          }
        }
      });
    },

    mobileToggle() {
      if (this.sidebar) {
        this.sidebar.classList.toggle('open');
        if (this.overlay) this.overlay.classList.toggle('show');
      }
    },

    mobileClose() {
      if (this.sidebar) {
        this.sidebar.classList.remove('open');
        if (this.overlay) this.overlay.classList.remove('show');
      }
    },

    desktopToggle() {
      document.body.classList.toggle('sidebar-collapsed');
      const collapsed = document.body.classList.contains('sidebar-collapsed');
      localStorage.setItem(this.storageKey, collapsed ? '1' : '0');
    }
  };

  // Theme Manager (mode + color + density + radius + customizer panel)
  const ThemeManager = {
    modeKey: 'ga-theme-mode',
    colorKey: 'ga-theme-color',
    densityKey: 'ga-density',
    radiusKey: 'ga-radius',

    modes: [
      { id: 'light', label: 'Light', hint: 'Bright' },
      { id: 'dark', label: 'Dark', hint: 'Dim' },
      { id: 'mix', label: 'Mix', hint: 'Classic' },
      { id: 'midnight', label: 'Midnight', hint: 'OLED' },
      { id: 'system', label: 'System', hint: 'Auto' }
    ],

    // Ordered around the colour wheel so the grid reads as a spectrum
    colors: [
      'lime', 'green', 'emerald', 'teal', 'cyan', 'sky',
      'blue', 'indigo', 'purple', 'fuchsia', 'pink', 'rose',
      'red', 'orange', 'amber', 'yellow', 'slate', 'stone'
    ],

    densities: [
      { id: 'compact', label: 'Compact' },
      { id: 'comfortable', label: 'Comfortable' }
    ],

    radii: [
      { id: 'sharp', label: 'Sharp' },
      { id: 'normal', label: 'Normal' },
      { id: 'round', label: 'Round' }
    ],

    defaultMode: 'mix',
    defaultColor: 'green',
    defaultDensity: 'compact',
    defaultRadius: 'normal',

    init() {
      this.btn = document.getElementById('themeToggle');
      this.root = document.documentElement;

      // Migrate the pre-1.0 single-key format
      const legacyTheme = localStorage.getItem('ga-theme');
      if (legacyTheme && !localStorage.getItem(this.modeKey)) {
        const mapped = (legacyTheme === 'dark') ? 'dark' : (legacyTheme === 'light') ? 'mix' : legacyTheme;
        localStorage.setItem(this.modeKey, mapped);
        localStorage.removeItem('ga-theme');
      }

      this.applyMode(this.read(this.modeKey, this.modes.map(m => m.id), this.defaultMode), false);
      this.applyColor(this.read(this.colorKey, this.colors, this.defaultColor), false);
      this.applyDensity(this.read(this.densityKey, this.densities.map(d => d.id), this.defaultDensity), false);
      this.applyRadius(this.read(this.radiusKey, this.radii.map(r => r.id), this.defaultRadius), false);

      this.updateIcon();
      if (this.btn) this.btn.addEventListener('click', () => this.openPanel());

      this.watchSystem();
      this.injectPanel();
    },

    read(key, allowed, fallback) {
      const value = localStorage.getItem(key);
      return allowed.indexOf(value) > -1 ? value : fallback;
    },

    // 'system' is a preference, not a palette: resolve it to light or dark
    resolve(mode) {
      if (mode !== 'system') return mode;
      return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    },

    watchSystem() {
      if (!window.matchMedia) return;
      const query = window.matchMedia('(prefers-color-scheme: dark)');
      const onChange = () => {
        if (this.getModePref() === 'system') this.applyMode('system', true);
      };
      if (query.addEventListener) query.addEventListener('change', onChange);
      else if (query.addListener) query.addListener(onChange);
    },

    animateOnce(animate) {
      if (!animate) return;
      this.root.classList.add('ga-theme-transitioning');
      clearTimeout(this._animateTimer);
      this._animateTimer = setTimeout(() => this.root.classList.remove('ga-theme-transitioning'), 400);
    },

    applyMode(mode, animate) {
      this.animateOnce(animate);
      this.root.setAttribute('data-theme', this.resolve(mode));
      this.root.setAttribute('data-theme-pref', mode);
      localStorage.setItem(this.modeKey, mode);
      this.updateIcon();
      this.updatePanel();
    },

    applyColor(color, animate) {
      this.animateOnce(animate);
      this.root.setAttribute('data-color', color);
      localStorage.setItem(this.colorKey, color);
      this.updatePanel();
    },

    applyDensity(density, animate) {
      this.animateOnce(animate);
      this.root.setAttribute('data-density', density);
      localStorage.setItem(this.densityKey, density);
      this.updatePanel();
    },

    applyRadius(radius, animate) {
      this.animateOnce(animate);
      this.root.setAttribute('data-radius', radius);
      localStorage.setItem(this.radiusKey, radius);
      this.updatePanel();
    },

    getModePref() { return this.root.getAttribute('data-theme-pref') || this.defaultMode; },
    getMode() { return this.root.getAttribute('data-theme') || this.defaultMode; },
    getColor() { return this.root.getAttribute('data-color') || this.defaultColor; },
    getDensity() { return this.root.getAttribute('data-density') || this.defaultDensity; },
    getRadius() { return this.root.getAttribute('data-radius') || this.defaultRadius; },

    reset() {
      this.applyMode(this.defaultMode, true);
      this.applyColor(this.defaultColor, true);
      this.applyDensity(this.defaultDensity, true);
      this.applyRadius(this.defaultRadius, true);
    },

    updateIcon() {
      if (!this.btn) return;
      const icons = {
        light: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>',
        dark: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>',
        mix: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a10 10 0 0 1 0 20V2z" fill="currentColor" opacity="0.2"/><path d="M12 2v20"/></svg>',
        midnight: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/><circle cx="17" cy="6" r="1" fill="currentColor"/><circle cx="20" cy="10" r="0.7" fill="currentColor"/></svg>',
        system: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>'
      };
      const pref = this.getModePref();
      this.btn.innerHTML = icons[pref] || icons[this.getMode()] || icons.mix;
      this.btn.setAttribute('title', 'Theme settings');
    },

    openPanel() {
      const panel = document.querySelector('.ga-theme-panel');
      const overlay = document.querySelector('.ga-theme-overlay');
      if (panel) {
        panel.classList.add('open');
        panel.setAttribute('aria-hidden', 'false');
        const first = panel.querySelector('.ga-theme-panel-close');
        if (first) setTimeout(() => first.focus(), 60);
      }
      if (overlay) overlay.classList.add('open');
    },

    closePanel() {
      const panel = document.querySelector('.ga-theme-panel');
      const overlay = document.querySelector('.ga-theme-overlay');
      if (panel && panel.classList.contains('open')) {
        panel.classList.remove('open');
        panel.setAttribute('aria-hidden', 'true');
        if (this.btn) this.btn.focus();
      }
      if (overlay) overlay.classList.remove('open');
    },

    updatePanel() {
      const modePref = this.getModePref();
      const color = this.getColor();
      const density = this.getDensity();
      const radius = this.getRadius();

      const sync = (selector, attr, value) => {
        document.querySelectorAll(selector).forEach(el => {
          el.setAttribute('aria-checked', String(el.dataset[attr] === value));
        });
      };

      sync('.ga-mode-card', 'mode', modePref);
      sync('.ga-color-swatch', 'color', color);
      sync('.ga-seg-btn[data-density]', 'density', density);
      sync('.ga-seg-btn[data-radius]', 'radius', radius);

      const setValue = (name, text) => {
        const el = document.querySelector(`[data-section-value="${name}"]`);
        if (el) el.textContent = text;
      };
      setValue('color', color);
      setValue('density', density);
      setValue('radius', radius);

      const info = document.querySelector('.ga-theme-current-text');
      if (info) {
        const mode = this.modes.find(m => m.id === modePref);
        const label = mode ? mode.label : 'Mix';
        const resolved = modePref === 'system' ? ` (${this.getMode()})` : '';
        info.innerHTML = `<strong>${label}</strong>${resolved} &middot; <strong>${color}</strong> &middot; ${density}, ${radius} corners`;
      }
    },

    injectPanel() {
      if (document.querySelector('.ga-theme-panel')) return;

      const icon = {
        sun: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>',
        drop: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>',
        rows: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="5" rx="1"/><rect x="3" y="14" width="18" height="5" rx="1"/></svg>',
        corner: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 20V10a6 6 0 0 1 6-6h10"/></svg>'
      };

      const modeCards = this.modes.map(mode => `
        <button type="button" class="ga-mode-card" role="radio" aria-checked="false" data-mode="${mode.id}" title="${mode.label} mode">
          <span class="ga-mode-preview">
            <span class="ga-mode-preview-sidebar"></span>
            <span class="ga-mode-preview-content">
              <span class="ga-mode-preview-header"></span>
              <span class="ga-mode-preview-body"></span>
            </span>
          </span>
          <span class="ga-mode-label">${mode.label}</span>
          <span class="ga-mode-hint">${mode.hint}</span>
        </button>`).join('');

      const swatches = this.colors.map(color => `
        <button type="button" class="ga-color-swatch" role="radio" aria-checked="false"
                data-color="${color}" title="${color}" aria-label="${color} colour palette"></button>`).join('');

      const segment = (name, items) => items.map(item => `
        <button type="button" class="ga-seg-btn" role="radio" aria-checked="false" data-${name}="${item.id}">${item.label}</button>`).join('');

      const html = `
        <div class="ga-theme-overlay"></div>
        <aside class="ga-theme-panel" role="dialog" aria-modal="true" aria-label="Theme customizer" aria-hidden="true">
          <div class="ga-theme-panel-header">
            <div class="ga-theme-panel-title">
              <span class="ga-theme-panel-title-icon">${icon.drop}</span>
              <span>Theme Customizer<span class="ga-theme-panel-subtitle">${this.modes.length} modes &middot; ${this.colors.length} palettes</span></span>
            </div>
            <button type="button" class="ga-theme-panel-close" aria-label="Close theme customizer">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
            </button>
          </div>

          <div class="ga-theme-panel-body">
            <div class="ga-theme-current">
              <span class="ga-theme-current-dot"></span>
              <span class="ga-theme-current-text"></span>
            </div>

            <div class="ga-theme-section">
              <div class="ga-theme-section-label">${icon.sun}Appearance Mode</div>
              <div class="ga-mode-grid" role="radiogroup" aria-label="Appearance mode">${modeCards}</div>
            </div>

            <div class="ga-theme-section">
              <div class="ga-theme-section-label">${icon.drop}Color Palette<span class="ga-theme-section-value" data-section-value="color"></span></div>
              <div class="ga-color-grid" role="radiogroup" aria-label="Color palette">${swatches}</div>
            </div>

            <div class="ga-theme-section">
              <div class="ga-theme-section-label">${icon.rows}Density<span class="ga-theme-section-value" data-section-value="density"></span></div>
              <div class="ga-seg" role="radiogroup" aria-label="Interface density">${segment('density', this.densities)}</div>
            </div>

            <div class="ga-theme-section">
              <div class="ga-theme-section-label">${icon.corner}Corner Radius<span class="ga-theme-section-value" data-section-value="radius"></span></div>
              <div class="ga-seg" role="radiogroup" aria-label="Corner radius">${segment('radius', this.radii)}</div>
            </div>
          </div>

          <div class="ga-theme-panel-footer">
            <button type="button" class="ga-theme-reset-btn">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>
              Reset to Default
            </button>
          </div>
        </aside>`;

      const container = document.createElement('div');
      container.id = 'ga-theme-system';
      container.innerHTML = html;
      document.body.appendChild(container);

      const on = (selector, handler) => {
        container.querySelectorAll(selector).forEach(el => el.addEventListener('click', () => handler(el)));
      };

      const overlay = container.querySelector('.ga-theme-overlay');
      const closeBtn = container.querySelector('.ga-theme-panel-close');
      const resetBtn = container.querySelector('.ga-theme-reset-btn');
      if (overlay) overlay.addEventListener('click', () => this.closePanel());
      if (closeBtn) closeBtn.addEventListener('click', () => this.closePanel());
      if (resetBtn) resetBtn.addEventListener('click', () => this.reset());

      on('.ga-mode-card', el => this.applyMode(el.dataset.mode, true));
      on('.ga-color-swatch', el => this.applyColor(el.dataset.color, true));
      on('.ga-seg-btn[data-density]', el => this.applyDensity(el.dataset.density, true));
      on('.ga-seg-btn[data-radius]', el => this.applyRadius(el.dataset.radius, true));

      // Arrow-key navigation within each radio group
      container.querySelectorAll('[role="radiogroup"]').forEach(group => {
        group.addEventListener('keydown', (e) => {
          if (['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp'].indexOf(e.key) === -1) return;
          const options = [...group.querySelectorAll('[role="radio"]')];
          const current = options.indexOf(document.activeElement);
          if (current === -1) return;
          e.preventDefault();
          const step = (e.key === 'ArrowRight' || e.key === 'ArrowDown') ? 1 : -1;
          const next = options[(current + step + options.length) % options.length];
          next.focus();
          next.click();
        });
      });

      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') this.closePanel();
      });

      this.updatePanel();
    }
  };

  // Dropdown
  const DropdownManager = {
    init() {
      document.addEventListener('click', (e) => {
        const trigger = e.target.closest('[data-dropdown]');
        if (trigger) {
          e.stopPropagation();
          const menu = trigger.nextElementSibling;
          if (menu) {
            document.querySelectorAll('.ga-dropdown-menu.show').forEach(m => {
              if (m !== menu) m.classList.remove('show');
            });
            menu.classList.toggle('show');
          }
          return;
        }
        document.querySelectorAll('.ga-dropdown-menu.show').forEach(m => m.classList.remove('show'));
      });
    }
  };

  // Header Menu Search (live suggestions)
  const HeaderSearchManager = {
    init() {
      this.container = document.querySelector('.ga-header-search');
      this.input = this.container ? this.container.querySelector('input') : null;
      if (!this.container || !this.input) return;

      this.results = document.createElement('div');
      this.results.className = 'ga-header-search-results';
      this.results.setAttribute('role', 'listbox');
      this.container.appendChild(this.results);

      this.sidebar = document.querySelector('.ga-sidebar');
      this.items = [];
      this.matches = [];
      this.activeIndex = -1;

      this.refreshItems();
      this.observeMenuChanges();

      this.input.setAttribute('autocomplete', 'off');
      this.input.setAttribute('placeholder', 'Search menu...');

      this.input.addEventListener('input', () => this.onInput());
      this.input.addEventListener('focus', () => this.onInput());
      this.input.addEventListener('keydown', (e) => this.onKeyDown(e));

      document.addEventListener('click', (e) => {
        if (!this.container.contains(e.target)) {
          this.hide();
        }
      });
    },

    collectItems() {
      const items = [];
      const seen = new Set();

      const addItem = (item) => {
        if (!item.label || !item.href) return;
        const key = `${item.label.toLowerCase()}|${item.href.toLowerCase()}`;
        if (seen.has(key)) return;
        seen.add(key);

        const keywords = Array.isArray(item.keywords) ? item.keywords.join(' ') : '';
        const hrefText = item.href.replace(/[-_/.]+/g, ' ');
        items.push({
          label: item.label,
          href: item.href,
          section: item.section || 'Menu',
          searchText: `${item.label} ${item.section || ''} ${keywords} ${item.href} ${hrefText}`.toLowerCase()
        });
      };

      const links = this.sidebar ? this.sidebar.querySelectorAll('a.ga-nav-item[href]') : [];

      links.forEach((link) => {
        const label = this.getLabel(link);
        const href = (link.getAttribute('href') || '').trim();
        if (!href || href === '#' || href.startsWith('javascript:')) return;
        const section = this.getSection(link);
        addItem({ label, href, section });
      });

      return items;
    },

    refreshItems() {
      this.items = this.collectItems();
    },

    observeMenuChanges() {
      if (!this.sidebar || typeof MutationObserver === 'undefined') return;

      this.observer = new MutationObserver(() => {
        this.refreshItems();
        if (this.input.value.trim()) {
          this.onInput();
        }
      });

      this.observer.observe(this.sidebar, {
        childList: true,
        subtree: true,
        characterData: true,
        attributes: true,
        attributeFilter: ['href', 'class']
      });
    },

    getLabel(link) {
      const span = link.querySelector('span');
      if (span && span.textContent.trim()) return span.textContent.trim();
      return link.textContent.trim();
    },

    getSection(link) {
      const group = link.closest('.ga-nav-group');
      const groupLabel = group ? (group.querySelector('.ga-nav-label')?.textContent || '').trim() : '';
      const trail = [];

      if (groupLabel) trail.push(groupLabel);

      const l2 = link.closest('.ga-submenu');
      if (l2) {
        const l2Toggle = l2.previousElementSibling;
        const l2Label = this.getToggleLabel(l2Toggle);
        if (l2Label) trail.push(l2Label);
      }

      const l3 = link.closest('.ga-submenu-l3');
      if (l3) {
        const l3Toggle = l3.previousElementSibling;
        const l3Label = this.getToggleLabel(l3Toggle);
        if (l3Label) trail.push(l3Label);
      }

      return trail.join(' / ') || 'Menu';
    },

    getToggleLabel(toggle) {
      if (!toggle) return '';
      const span = toggle.querySelector('span');
      return span ? span.textContent.trim() : toggle.textContent.trim();
    },

    onInput() {
      const query = this.input.value.toLowerCase().trim();
      if (!query) {
        this.hide();
        return;
      }

      this.refreshItems();
      this.matches = this.items
        .filter((item) => item.searchText.includes(query))
        .sort((a, b) => this.rank(a, query) - this.rank(b, query) || a.label.localeCompare(b.label))
        .slice(0, 8);

      this.activeIndex = -1;
      this.render();
    },

    rank(item, query) {
      const label = item.label.toLowerCase();
      const section = item.section.toLowerCase();
      if (label.startsWith(query)) return 0;
      if (label.includes(query)) return 1;
      if (section.includes(query)) return 2;
      return 3;
    },

    onKeyDown(e) {
      if (!this.matches.length) return;

      if (e.key === 'ArrowDown') {
        e.preventDefault();
        this.activeIndex = (this.activeIndex + 1) % this.matches.length;
        this.render();
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        this.activeIndex = this.activeIndex <= 0 ? this.matches.length - 1 : this.activeIndex - 1;
        this.render();
      } else if (e.key === 'Enter') {
        const selected = this.matches[this.activeIndex] || this.matches[0];
        if (selected) {
          e.preventDefault();
          window.location.href = selected.href;
        }
      } else if (e.key === 'Escape') {
        this.hide();
      }
    },

    render() {
      if (!this.matches.length) {
        this.hide();
        return;
      }

      this.results.innerHTML = this.matches.map((item, index) => `
        <button type="button" class="ga-header-search-item ${index === this.activeIndex ? 'active' : ''}" data-index="${index}">
          <span class="ga-header-search-title">${item.label}</span>
          <span class="ga-header-search-meta">${item.section}</span>
        </button>
      `).join('');

      this.results.querySelectorAll('.ga-header-search-item').forEach((btn) => {
        btn.addEventListener('mousedown', (e) => e.preventDefault());
        btn.addEventListener('click', () => {
          const index = parseInt(btn.dataset.index, 10);
          const selected = this.matches[index];
          if (selected) window.location.href = selected.href;
        });
      });

      this.results.classList.add('show');
    },

    hide() {
      this.results.classList.remove('show');
      this.activeIndex = -1;
    }
  };

  // FAQ Accordion
  const FAQManager = {
    init() {
      document.querySelectorAll('.ga-faq-question').forEach(q => {
        q.addEventListener('click', () => {
          const item = q.parentElement;
          const wasOpen = item.classList.contains('open');
          // Close all
          document.querySelectorAll('.ga-faq-item.open').forEach(i => i.classList.remove('open'));
          if (!wasOpen) item.classList.add('open');
        });
      });
    }
  };

  // Alert dismissals
  const AlertManager = {
    init() {
      document.querySelectorAll('.ga-alert-close').forEach(btn => {
        btn.addEventListener('click', () => {
          const alert = btn.closest('.ga-alert');
          if (alert) {
            alert.style.opacity = '0';
            alert.style.transform = 'translateX(20px)';
            setTimeout(() => alert.remove(), 200);
          }
        });
      });
    }
  };

  // DataTable Engine
  window.GaDataTable = class {
    constructor(tableId, options = {}) {
      this.table = document.getElementById(tableId);
      if (!this.table) return;

      this.wrapper = this.table.closest('.ga-card');
      this.tbody = this.table.querySelector('tbody');
      this.allRows = Array.from(this.tbody.querySelectorAll('tr'));
      this.filteredRows = [...this.allRows];
      this.perPage = options.perPage || 10;
      this.currentPage = 1;
      this.sortCol = -1;
      this.sortDir = 'asc';

      this.initControls();
      this.initSorting();
      this.render();
    }

    initControls() {
      const controls = this.wrapper.querySelector('.ga-dt-controls');
      if (!controls) return;

      this.searchInput = controls.querySelector('.ga-dt-search input');
      this.perPageSelect = controls.querySelector('.ga-dt-per-page select');

      if (this.searchInput) {
        this.searchInput.addEventListener('input', () => {
          this.currentPage = 1;
          this.applyFilter();
          this.render();
        });
      }

      if (this.perPageSelect) {
        this.perPageSelect.addEventListener('change', () => {
          this.perPage = parseInt(this.perPageSelect.value);
          this.currentPage = 1;
          this.render();
        });
      }
    }

    initSorting() {
      this.table.querySelectorAll('thead th.sortable').forEach(th => {
        // Use the real cell index so tables that mix sortable and static columns sort correctly
        const i = th.cellIndex;
        th.addEventListener('click', () => {
          if (this.sortCol === i) {
            this.sortDir = this.sortDir === 'asc' ? 'desc' : 'asc';
          } else {
            this.sortCol = i;
            this.sortDir = 'asc';
          }
          this.table.querySelectorAll('thead th.sortable').forEach(h => h.classList.remove('asc', 'desc'));
          th.classList.add(this.sortDir);
          this.applySort();
          this.render();
        });
      });
    }

    applyFilter() {
      const q = (this.searchInput ? this.searchInput.value : '').toLowerCase().trim();
      this.filteredRows = this.allRows.filter(row => {
        return q === '' || row.textContent.toLowerCase().includes(q);
      });
      if (this.sortCol >= 0) this.applySort();
    }

    applySort() {
      const col = this.sortCol;
      const dir = this.sortDir === 'asc' ? 1 : -1;
      this.filteredRows.sort((a, b) => {
        const aVal = (a.cells[col]?.textContent || '').trim();
        const bVal = (b.cells[col]?.textContent || '').trim();
        const aNum = parseFloat(aVal.replace(/[^0-9.-]/g, ''));
        const bNum = parseFloat(bVal.replace(/[^0-9.-]/g, ''));
        if (!isNaN(aNum) && !isNaN(bNum)) return (aNum - bNum) * dir;
        return aVal.localeCompare(bVal) * dir;
      });
    }

    render() {
      const total = this.filteredRows.length;
      const totalPages = Math.max(1, Math.ceil(total / this.perPage));
      if (this.currentPage > totalPages) this.currentPage = totalPages;

      const start = (this.currentPage - 1) * this.perPage;
      const end = start + this.perPage;
      const pageRows = this.filteredRows.slice(start, end);

      // Render rows
      this.tbody.innerHTML = '';
      if (pageRows.length === 0) {
        const tr = document.createElement('tr');
        const td = document.createElement('td');
        td.colSpan = this.table.querySelectorAll('thead th').length;
        td.className = 'text-center ga-text-muted';
        td.style.padding = '32px';
        td.textContent = 'No data found';
        tr.appendChild(td);
        this.tbody.appendChild(tr);
      } else {
        pageRows.forEach(row => this.tbody.appendChild(row));
      }

      // Render pagination
      const footer = this.wrapper.querySelector('.ga-dt-footer');
      if (footer) {
        const info = footer.querySelector('.ga-dt-info');
        const pag = footer.querySelector('.ga-dt-pagination');

        if (info) {
          info.textContent = total === 0
            ? 'No entries'
            : `Showing ${start + 1} to ${Math.min(end, total)} of ${total} entries`;
        }

        if (pag) {
          let html = `<button ${this.currentPage <= 1 ? 'disabled' : ''} data-page="${this.currentPage - 1}">&laquo; Prev</button>`;
          for (let i = 1; i <= totalPages; i++) {
            if (totalPages > 7) {
              if (i === 1 || i === totalPages || (i >= this.currentPage - 1 && i <= this.currentPage + 1)) {
                html += `<button class="${i === this.currentPage ? 'active' : ''}" data-page="${i}">${i}</button>`;
              } else if (i === this.currentPage - 2 || i === this.currentPage + 2) {
                html += `<button disabled>...</button>`;
              }
            } else {
              html += `<button class="${i === this.currentPage ? 'active' : ''}" data-page="${i}">${i}</button>`;
            }
          }
          html += `<button ${this.currentPage >= totalPages ? 'disabled' : ''} data-page="${this.currentPage + 1}">Next &raquo;</button>`;
          pag.innerHTML = html;

          pag.querySelectorAll('button[data-page]').forEach(btn => {
            btn.addEventListener('click', () => {
              const p = parseInt(btn.dataset.page);
              if (p >= 1 && p <= totalPages) {
                this.currentPage = p;
                this.render();
              }
            });
          });
        }
      }
    }
  };

  // Tab Manager
  const TabManager = {
    init() {
      document.querySelectorAll('.ga-tabs').forEach(tabBar => {
        tabBar.querySelectorAll('.ga-tab').forEach(tab => {
          tab.addEventListener('click', () => {
            const target = tab.dataset.tab;
            if (!target) return;
            tabBar.querySelectorAll('.ga-tab').forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            const container = tabBar.parentElement;
            container.querySelectorAll('.ga-tab-content').forEach(c => c.classList.remove('active'));
            const panel = container.querySelector(`[data-tab-content="${target}"]`);
            if (panel) panel.classList.add('active');
          });
        });
      });
    }
  };

  // Toast notification helper
  window.GaToast = function(title, message, type) {
    let container = document.querySelector('.ga-toast-container');
    if (!container) {
      container = document.createElement('div');
      container.className = 'ga-toast-container';
      document.body.appendChild(container);
    }
    const colors = { success: '#10b981', danger: '#ef4444', warning: '#f59e0b', info: '#3b82f6' };
    const toast = document.createElement('div');
    toast.className = 'ga-toast';
    toast.innerHTML = `
      <svg class="ga-toast-icon" viewBox="0 0 24 24" fill="none" stroke="${colors[type]||colors.info}" stroke-width="2">
        ${type === 'success' ? '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>' :
          type === 'danger' ? '<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>' :
          type === 'warning' ? '<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>' :
          '<circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>'}
      </svg>
      <div class="ga-toast-body">
        <div class="ga-toast-title">${title}</div>
        <div class="ga-toast-message">${message}</div>
      </div>
      <button onclick="this.parentElement.remove()" style="background:none;border:none;cursor:pointer;color:var(--ga-text-muted);padding:0;font-size:1.2rem;">&times;</button>`;
    container.appendChild(toast);
    setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.3s'; setTimeout(() => toast.remove(), 300); }, 5000);
  };

  // Init
  document.addEventListener('DOMContentLoaded', () => {
    SidebarManager.init();
    ThemeManager.init();
    DropdownManager.init();
    HeaderSearchManager.init();
    FAQManager.init();
    AlertManager.init();
    TabManager.init();
  });
})();
