/* ============================================
   PREMIUM SAAS ADMIN DASHBOARD - JAVASCRIPT
   ============================================ */

document.addEventListener('DOMContentLoaded', () => {

  // ---- DOM References ----
  const sidebar = document.getElementById('sidebar');
  const sidebarOverlay = document.getElementById('sidebarOverlay');
  const sidebarToggle = document.getElementById('sidebarToggle');
  const profileToggle = document.getElementById('profileToggle');
  const profileMenu = document.getElementById('profileMenu');
  const tableSearchInput = document.getElementById('tableSearch');

  // ---- Sidebar Toggle (Mobile) ----
  function openSidebar() {
    sidebar.classList.add('active');
    sidebarOverlay.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  function closeSidebar() {
    sidebar.classList.remove('active');
    sidebarOverlay.classList.remove('active');
    document.body.style.overflow = '';
  }

  if (sidebarToggle) {
    sidebarToggle.addEventListener('click', () => {
      if (sidebar.classList.contains('active')) {
        closeSidebar();
      } else {
        openSidebar();
      }
    });
  }

  if (sidebarOverlay) {
    sidebarOverlay.addEventListener('click', closeSidebar);
  }




  // ---- Sidebar Submenu Toggle ----
const submenuToggles = document.querySelectorAll('[data-submenu]');

submenuToggles.forEach(toggle => {
  toggle.addEventListener('click', (e) => {
    e.preventDefault();

    const targetId = toggle.getAttribute('data-submenu');
    const submenu = document.getElementById(targetId);
    const arrow = toggle.querySelector('.menu-arrow');

    // Only open submenu, never close others
    submenu.classList.add('open');

    if (arrow) {
      arrow.classList.add('rotated');
    }
  });
});

// Open all submenus on page load
document.querySelectorAll('.submenu').forEach(submenu => {
  submenu.classList.add('open');
});

document.querySelectorAll('.menu-arrow').forEach(arrow => {
  arrow.classList.add('rotated');
});


// ---- Sidebar Overlay ----
if (sidebarOverlay) {
  sidebarOverlay.addEventListener('click', closeSidebar);
}


  // ---- Sidebar Menu Active State ----
  const menuLinks = document.querySelectorAll('.sidebar-menu .menu-link:not([data-submenu])');

  menuLinks.forEach(link => {
    link.addEventListener('click', () => {
      // Remove active from all
      document.querySelectorAll('.sidebar-menu .menu-link').forEach(l => l.classList.remove('active'));
      link.classList.add('active');

      // Close sidebar on mobile
      if (window.innerWidth < 992) {
        closeSidebar();
      }
    });
  });


// ---- Open Parent Submenu of Active Page ----
const activeMenu = document.querySelector('.submenu .menu-link.active');

if (activeMenu) {
    const parentSubmenu = activeMenu.closest('.submenu');

    if (parentSubmenu) {
        parentSubmenu.classList.add('open');

        const parentToggle = document.querySelector(
            `[data-submenu="${parentSubmenu.id}"]`
        );

        if (parentToggle) {
            const arrow = parentToggle.querySelector('.menu-arrow');
            if (arrow) {
                arrow.classList.add('rotated');
            }
        }
    }
}



  // ---- Profile Dropdown ----
  if (profileToggle) {
    profileToggle.addEventListener('click', (e) => {
      e.stopPropagation();
      profileToggle.classList.toggle('show');
      profileMenu.classList.toggle('show');
    });
  }

  // Close profile dropdown when clicking outside
  document.addEventListener('click', (e) => {
    if (profileToggle && !profileToggle.contains(e.target) && !profileMenu.contains(e.target)) {
      profileToggle.classList.remove('show');
      profileMenu.classList.remove('show');
    }
  });

  // ---- Table Search ----
  if (tableSearchInput) {
    tableSearchInput.addEventListener('input', (e) => {
      const query = e.target.value.toLowerCase().trim();
      const rows = document.querySelectorAll('.data-table tbody tr');

      rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(query) ? '' : 'none';
      });
    });
  }

  // ---- Pagination ----
  const pageBtns = document.querySelectorAll('.page-btn[data-page]');

  pageBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      pageBtns.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
    });
  });

  // ---- Form Submit ----
  const dashForm = document.getElementById('dashForm');

  if (dashForm) {
    dashForm.addEventListener('submit', (e) => {
      e.preventDefault();

      const submitBtn = dashForm.querySelector('.btn-gradient');
      const originalText = submitBtn.innerHTML;

      // Simulated submission
      submitBtn.innerHTML = '<i class="bi bi-arrow-repeat spin"></i> Submitting...';
      submitBtn.disabled = true;

      setTimeout(() => {
        submitBtn.innerHTML = '<i class="bi bi-check-circle"></i> Submitted!';
        submitBtn.style.background = 'linear-gradient(135deg, #22c55e, #16a34a)';

        setTimeout(() => {
          submitBtn.innerHTML = originalText;
          submitBtn.style.background = '';
          submitBtn.disabled = false;
          dashForm.reset();

          // Reset floating labels
          dashForm.querySelectorAll('.form-input').forEach(input => {
            input.dispatchEvent(new Event('blur'));
          });
        }, 2000);
      }, 1500);
    });
  }

  // ---- Animate Stat Numbers ----
  function animateCounter(element, target, duration = 1500) {
    const start = 0;
    const startTime = performance.now();
    const isDecimal = target % 1 !== 0;
    const prefix = element.dataset.prefix || '';
    const suffix = element.dataset.suffix || '';

    function update(currentTime) {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 4); // easeOutQuart
      const current = start + (target - start) * eased;

      if (isDecimal) {
        element.textContent = prefix + current.toFixed(1) + suffix;
      } else {
        element.textContent = prefix + Math.floor(current).toLocaleString() + suffix;
      }

      if (progress < 1) {
        requestAnimationFrame(update);
      }
    }

    requestAnimationFrame(update);
  }

  // Intersection Observer for counter animation
  const statValues = document.querySelectorAll('.stat-value[data-count]');

  const counterObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const el = entry.target;
        const target = parseFloat(el.dataset.count);
        animateCounter(el, target);
        counterObserver.unobserve(el);
      }
    });
  }, { threshold: 0.3 });

  statValues.forEach(el => counterObserver.observe(el));

  // ---- Responsive Window Resize ----
  let resizeTimer;
  window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
      if (window.innerWidth >= 992) {
        closeSidebar();
      }
    }, 150);
  });

  // ---- Add spin animation for submit button ----
  const style = document.createElement('style');
  style.textContent = `
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    .spin {
      display: inline-block;
      animation: spin 1s linear infinite;
    }
  `;
  document.head.appendChild(style);

});
