/**
 * SIAKAD - Main JavaScript
 */

(function () {
  'use strict';

  // ============================================================
  // Sidebar Toggle
  // ============================================================
  const sidebar = document.getElementById('sidebar');
  const overlay = document.getElementById('sidebarOverlay');
  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 = '';
  }

  toggleBtn?.addEventListener('click', () => {
    sidebar?.classList.contains('show') ? closeSidebar() : openSidebar();
  });

  overlay?.addEventListener('click', closeSidebar);

  // Close sidebar on resize to desktop
  window.addEventListener('resize', () => {
    if (window.innerWidth >= 992) closeSidebar();
  });

  // ============================================================
  // Submenu Toggle
  // ============================================================
  document.querySelectorAll('.has-submenu > .nav-link').forEach(link => {
    link.addEventListener('click', function (e) {
      e.preventDefault();
      const parent = this.closest('.has-submenu');
      const submenu = parent.querySelector('.submenu');
      const isOpen = parent.classList.contains('open');

      // Close all other submenus
      document.querySelectorAll('.has-submenu.open').forEach(item => {
        if (item !== parent) {
          item.classList.remove('open');
          item.querySelector('.submenu')?.classList.remove('show');
        }
      });

      parent.classList.toggle('open', !isOpen);
      submenu?.classList.toggle('show', !isOpen);
    });
  });

  // Auto-open submenu if active child exists
  document.querySelectorAll('.submenu .nav-link.active').forEach(link => {
    const parent = link.closest('.has-submenu');
    if (parent) {
      parent.classList.add('open');
      parent.querySelector('.submenu')?.classList.add('show');
    }
  });

  // ============================================================
  // Auto-dismiss alerts
  // ============================================================
  document.querySelectorAll('.alert-auto-dismiss').forEach(alert => {
    setTimeout(() => {
      const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
      bsAlert?.close();
    }, 4000);
  });

  // ============================================================
  // Confirm Delete
  // ============================================================
  document.querySelectorAll('[data-confirm]').forEach(el => {
    el.addEventListener('click', function (e) {
      const msg = this.dataset.confirm || 'Apakah Anda yakin ingin menghapus data ini?';
      if (!confirm(msg)) e.preventDefault();
    });
  });

  // ============================================================
  // DataTable-like: Search in table
  // ============================================================
  const tableSearch = document.getElementById('tableSearch');
  if (tableSearch) {
    tableSearch.addEventListener('input', function () {
      const query = this.value.toLowerCase();
      const rows = document.querySelectorAll('#dataTable tbody tr');
      rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(query) ? '' : 'none';
      });
    });
  }

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

  // ============================================================
  // Preview image upload
  // ============================================================
  document.querySelectorAll('.img-upload-input').forEach(input => {
    input.addEventListener('change', function () {
      const preview = document.getElementById(this.dataset.preview);
      if (preview && this.files[0]) {
        const reader = new FileReader();
        reader.onload = e => { preview.src = e.target.result; };
        reader.readAsDataURL(this.files[0]);
      }
    });
  });

  // ============================================================
  // Select All Checkbox
  // ============================================================
  const selectAll = document.getElementById('selectAll');
  if (selectAll) {
    selectAll.addEventListener('change', function () {
      document.querySelectorAll('.row-check').forEach(cb => {
        cb.checked = this.checked;
      });
    });
  }

  // ============================================================
  // Counter animation for stat cards
  // ============================================================
  function animateCounter(el) {
    const target = parseInt(el.dataset.target || el.textContent, 10);
    if (isNaN(target)) return;
    let current = 0;
    const step = Math.ceil(target / 40);
    const timer = setInterval(() => {
      current = Math.min(current + step, target);
      el.textContent = current.toLocaleString('id-ID');
      if (current >= target) clearInterval(timer);
    }, 30);
  }

  document.querySelectorAll('.stat-value[data-target]').forEach(animateCounter);

  // ============================================================
  // Form validation
  // ============================================================
  document.querySelectorAll('form.needs-validation').forEach(form => {
    form.addEventListener('submit', function (e) {
      if (!form.checkValidity()) {
        e.preventDefault();
        e.stopPropagation();
      }
      form.classList.add('was-validated');
    });
  });

  // ============================================================
  // Print page
  // ============================================================
  document.querySelectorAll('[data-print]').forEach(btn => {
    btn.addEventListener('click', () => window.print());
  });

})();
