/* ============================================================
   ADMIN.JS — Panel Admin Budi Jaya
   ============================================================ */
document.addEventListener('DOMContentLoaded', () => {

  /* ── Sidebar toggle ──────────────────────────────────────── */
  const sidebar  = document.getElementById('adminSidebar');
  const overlay  = document.getElementById('sidebarOverlay');
  const btnOpen  = document.getElementById('toggleSidebar');
  const btnClose = document.getElementById('closeSidebar');

  function openSidebar()  { sidebar?.classList.add('open');    overlay?.classList.add('show'); }
  function closeSidebar() { sidebar?.classList.remove('open'); overlay?.classList.remove('show'); }

  btnOpen?.addEventListener('click',  openSidebar);
  btnClose?.addEventListener('click', closeSidebar);
  overlay?.addEventListener('click',  closeSidebar);

  // Global toggleSidebar (dipanggil dari inline onclick lama)
  window.toggleSidebar = () => sidebar?.classList.contains('open') ? closeSidebar() : openSidebar();

  /* ── Auto-dismiss flash messages ──────────────────────────── */
  document.querySelectorAll('.alert-dismissible').forEach(el => {
    setTimeout(() => el.querySelector('.btn-close')?.click(), 5500);
  });

  /* ── Konfirmasi hapus universal [data-confirm] ─────────────── */
  document.querySelectorAll('[data-confirm]').forEach(btn => {
    btn.addEventListener('click', e => {
      if (!confirm(btn.dataset.confirm)) e.preventDefault();
    });
  });

  /* ── Preview gambar tunggal [data-preview="targetId"] ──────── */
  document.querySelectorAll('[data-preview]').forEach(input => {
    input.addEventListener('change', () => {
      const target = document.getElementById(input.dataset.preview);
      if (!target || !input.files?.[0]) return;
      const r = new FileReader();
      r.onload = e => { target.src = e.target.result; target.classList.remove('d-none'); };
      r.readAsDataURL(input.files[0]);
    });
  });

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

  /* ── Active nav-link: exact match untuk index.php ──────────── */
  const currentPath = window.location.pathname;
  document.querySelectorAll('.sidebar-link').forEach(link => {
    try {
      const linkPath = new URL(link.href).pathname;
      if (linkPath === currentPath) link.classList.add('active');
    } catch {}
  });

  /* ── Tambah baris spesifikasi (global, untuk produk form) ──── */
  window.tambahSpec = function() {
    const cont = document.getElementById('spesList'); if (!cont) return;
    const row  = document.createElement('div');
    row.className = 'adm-spec-row';
    row.innerHTML = `
      <input type="text" name="spec_key[]" class="form-control form-control-sm adm-spec-key" placeholder="Nama">
      <input type="text" name="spec_val[]" class="form-control form-control-sm adm-spec-val" placeholder="Nilai">
      <button type="button" class="adm-spec-del btn btn-sm btn-outline-danger"
              onclick="this.closest('.adm-spec-row').remove()">
        <i class="bi bi-dash"></i>
      </button>`;
    cont.appendChild(row);
    row.querySelector('.adm-spec-key')?.focus();
  };

  /* ── Keyboard accessibility: escape menutup sidebar di mobile ── */
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape') closeSidebar();
  });

  /* ── Loading state: semua tombol submit (kecuali toggle) ────── */
  document.querySelectorAll('form:not([data-no-loading]) button[type="submit"]').forEach(btn => {
    btn.closest('form')?.addEventListener('submit', () => {
      // Jangan loading untuk form kecil (hapus, toggle aktif, hapus foto)
      const isSmall = btn.classList.contains('btn-xs') || btn.closest('[data-no-loading]');
      if (!isSmall && !btn.disabled) {
        const orig = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Memproses…';
        // Restore jika navigasi kembali (bfcache)
        window.addEventListener('pageshow', () => {
          btn.disabled  = false;
          btn.innerHTML = orig;
        }, { once: true });
      }
    });
  });

});