/* CRMfic - admin UI interactions */
(function () {
  'use strict';

  // ── Sidebar toggle ─────────────────────────────────────────────────────────
  const sidebar = document.getElementById('sidebar');
  const toggle = document.getElementById('sidebarToggle');
  const app = document.getElementById('app');

  const DESKTOP_BP = 1024; // matches max-lg mixin

  if (toggle && sidebar) {
    toggle.addEventListener('click', () => {
      if (window.innerWidth >= DESKTOP_BP) {
        // Desktop: collapse/expand (icon-only mode)
        app.classList.toggle('sidebar-collapsed');
      } else {
        // Mobile: slide in/out
        sidebar.classList.toggle('is-open');
      }
    });

    // Mobile: close sidebar when clicking outside
    document.addEventListener('click', (e) => {
      if (
        window.innerWidth < DESKTOP_BP &&
        sidebar.classList.contains('is-open') &&
        !sidebar.contains(e.target) &&
        !toggle.contains(e.target)
      ) {
        sidebar.classList.remove('is-open');
      }
    });

    // Reset state on resize to avoid mixed state
    window.addEventListener('resize', () => {
      if (window.innerWidth >= DESKTOP_BP) {
        sidebar.classList.remove('is-open');
      } else {
        app.classList.remove('sidebar-collapsed');
      }
    });
  }

  // ── Dropdown menus ────────────────────────────────────────────────────────
  // Usage: <button data-dropdown-toggle="myMenu">…</button>
  //        <div class="dropdown-menu" id="myMenu">…</div>
  document.addEventListener('click', (e) => {
    const btn = e.target.closest('[data-dropdown-toggle]');

    // close all open dropdowns first
    document.querySelectorAll('.dropdown-menu.is-open').forEach((menu) => {
      if (!btn || menu.id !== btn.dataset.dropdownToggle) {
        menu.classList.remove('is-open');
      }
    });

    if (btn) {
      e.stopPropagation();
      const menuId = btn.dataset.dropdownToggle;
      const menu = document.getElementById(menuId);
      if (menu) menu.classList.toggle('is-open');
    }
  });

  // ── Modals ────────────────────────────────────────────────────────────────
  // Usage: data-modal-open="modalId"  /  data-modal-close="modalId"
  function openModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
      modal.classList.add('is-open');
      document.body.style.overflow = 'hidden';
    }
  }

  function closeModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
      modal.classList.remove('is-open');
      document.body.style.overflow = '';
    }
  }

  document.addEventListener('click', (e) => {
    const opener = e.target.closest('[data-modal-open]');
    if (opener) { openModal(opener.dataset.modalOpen); return; }

    const closer = e.target.closest('[data-modal-close]');
    if (closer) { closeModal(closer.dataset.modalClose); return; }

    // click on backdrop closes modal
    if (e.target.classList.contains('modal-overlay')) {
      const id = e.target.id;
      if (id) closeModal(id);
    }
  });

  // Escape key closes topmost open modal
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      document.querySelectorAll('.modal-overlay.is-open').forEach((m) => closeModal(m.id));
    }
  });

  // ── Settings / generic tabs ───────────────────────────────────────────────
  // Usage: <button class="settings-tab" data-tab-target="panelId">…</button>
  //        <div class="settings-panel" id="panelId">…</div>  (hide with display:none initially)
  document.querySelectorAll('[data-tab-target]').forEach((tab) => {
    tab.addEventListener('click', () => {
      const targetId = tab.dataset.tabTarget;
      const group = tab.closest('[data-tab-group]') || tab.parentElement;

      // deactivate all sibling tabs
      group.querySelectorAll('[data-tab-target]').forEach((t) => t.classList.remove('is-active'));
      tab.classList.add('is-active');

      // find panels in a container marked with data-tab-panels or the same parent's next sibling
      const panelContainer =
        document.querySelector('[data-tab-panels]') ||
        tab.closest('.settings-tabs')?.nextElementSibling;

      if (panelContainer) {
        panelContainer.querySelectorAll('.settings-panel').forEach((p) => {
          p.style.display = p.id === targetId ? '' : 'none';
        });
      } else {
        // fallback: look up globally
        document.querySelectorAll('.settings-panel').forEach((p) => {
          p.style.display = p.id === targetId ? '' : 'none';
        });
      }
    });
  });

  // activate the first tab in each settings-tabs group on load
  document.querySelectorAll('.settings-tabs').forEach((group) => {
    const firstTab = group.querySelector('[data-tab-target]');
    if (firstTab) {
      // only auto-activate if none are already active
      if (!group.querySelector('[data-tab-target].is-active')) {
        firstTab.click();
      }
    }
  });

  // ── Chart tabs (dashboard / analytics pages) ─────────────────────────────
  document.querySelectorAll('.chart-tab').forEach((tab) => {
    tab.addEventListener('click', () => {
      const card = tab.closest('.chart-card');
      card.querySelectorAll('.chart-tab').forEach((t) => t.classList.remove('chart-tab--active'));
      tab.classList.add('chart-tab--active');
    });
  });

  // ── Animated progress bars ────────────────────────────────────────────────
  // Looks for [data-progress="<value 0-100>"] and animates width on load
  function animateProgressBars() {
    document.querySelectorAll('[data-progress]').forEach((bar) => {
      const val = parseInt(bar.dataset.progress, 10);
      bar.style.width = '0%';
      requestAnimationFrame(() => {
        bar.style.transition = 'width 600ms ease';
        bar.style.width = `${Math.min(Math.max(val, 0), 100)}%`;
      });
    });
  }

  // ── Checkbox "select all" ─────────────────────────────────────────────────
  document.querySelectorAll('thead input[type="checkbox"]').forEach((master) => {
    const table = master.closest('table');
    const children = () => table.querySelectorAll('tbody input[type="checkbox"]');

    master.addEventListener('change', () => {
      children().forEach((cb) => { cb.checked = master.checked; });
    });

    table.addEventListener('change', (e) => {
      if (e.target !== master && e.target.type === 'checkbox') {
        const all = [...children()];
        const checked = all.filter((cb) => cb.checked);
        master.indeterminate = checked.length > 0 && checked.length < all.length;
        master.checked = checked.length === all.length;
      }
    });
  });

  // ── Upload zone drag-and-drop ─────────────────────────────────────────────
  document.querySelectorAll('.upload-zone').forEach((zone) => {
    zone.addEventListener('dragover', (e) => {
      e.preventDefault();
      zone.classList.add('is-drag-over');
    });
    ['dragleave', 'dragend'].forEach((ev) => {
      zone.addEventListener(ev, () => zone.classList.remove('is-drag-over'));
    });
    zone.addEventListener('drop', (e) => {
      e.preventDefault();
      zone.classList.remove('is-drag-over');
      const files = e.dataTransfer?.files;
      if (files?.length) {
        // Surface filename in the zone for demo purposes
        const nameEl = zone.querySelector('.upload-zone__filename');
        if (nameEl) nameEl.textContent = files[0].name;
        zone.classList.add('has-file');
      }
    });
  });

  // ── Toast helper ─────────────────────────────────────────────────────────
  // Usage: window.showToast('Saved!', 'success')
  window.showToast = function (message, type = 'success') {
    const container = document.getElementById('toastContainer') || (() => {
      const el = document.createElement('div');
      el.id = 'toastContainer';
      el.style.cssText = 'position:fixed;bottom:24px;right:24px;z-index:9999;display:flex;flex-direction:column;gap:8px;';
      document.body.appendChild(el);
      return el;
    })();

    const toast = document.createElement('div');
    toast.className = `toast toast--${type}`;
    toast.textContent = message;
    container.appendChild(toast);

    setTimeout(() => {
      toast.style.opacity = '0';
      toast.style.transform = 'translateX(20px)';
      toast.style.transition = 'all 300ms ease';
      setTimeout(() => toast.remove(), 320);
    }, 3000);
  };

  // ── Subscribers Growth chart (dashboard) ─────────────────────────────────
  const growthCanvas = document.getElementById('growthChart');
  if (growthCanvas && typeof Chart !== 'undefined') {
    const labels = [
      '2026-05-27', '2026-05-30', '2026-06-02', '2026-06-05', '2026-06-08',
      '2026-06-11', '2026-06-14', '2026-06-17', '2026-06-20', '2026-06-23', '2026-06-26'
    ];
    new Chart(growthCanvas, {
      type: 'line',
      data: {
        labels,
        datasets: [
          {
            label: 'By Date',
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            fill: true,
            backgroundColor: 'rgba(124,58,237,.15)',
            borderColor: '#7c3aed',
            borderWidth: 2,
            pointRadius: 3,
            pointBackgroundColor: '#7c3aed',
            tension: 0.3,
          },
          {
            label: 'Cumulative',
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            fill: false,
            borderColor: '#38bdf8',
            borderWidth: 2,
            borderDash: [5, 4],
            pointRadius: 3,
            pointBackgroundColor: '#38bdf8',
            tension: 0.3,
          },
        ],
      },
      options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: {
          x: { grid: { color: '#f3f4f6' }, ticks: { font: { size: 11 }, color: '#9ca3af' } },
          y: { min: 0, max: 1, grid: { color: '#f3f4f6' }, ticks: { stepSize: 1, font: { size: 11 }, color: '#9ca3af' } },
        },
      },
    });
  }

  // ── Init ──────────────────────────────────────────────────────────────────
  animateProgressBars();
})();
