/**
 * SHARED NAVBAR & PANEL MENU — JS/GSAP Logic
 * Source: dashboard.php (sumber utama)
 * Include file ini di semua halaman sebelum </body>
 *
 * Dependencies: GSAP, ScrollTrigger, Lenis
 */

document.addEventListener("DOMContentLoaded", () => {
  if (window.navbarInitialized) return;
  window.navbarInitialized = true;

  // Hapus class anti-FOUC agar GSAP bisa membaca ukuran asli & posisi elegan halaman
  document.documentElement.classList.remove('js-loading');

  // ========== ALERT ANIMATIONS (Entrance, Auto-Dismiss, Manual Close) ==========
  const alerts = document.querySelectorAll(".alert");
  if (alerts.length > 0) {
    // 1. Entrance Animation: Mulus membuka ruang
    alerts.forEach((alert) => {
      alert.style.overflow = "hidden"; // Hindari teks meluber saat height 0
      gsap.from(alert, {
        opacity: 0,
        y: -15,
        height: 0,
        paddingTop: 0,
        paddingBottom: 0,
        marginTop: 0,
        marginBottom: 0,
        duration: 0.6,
        ease: "power3.out"
      });
    });

    // Fungsi untuk animasi exit yang memuluskan elemen di bawahnya (card/tabel naik perlahan)
    const closeAlertSmoothly = (alertElem) => {
      gsap.killTweensOf(alertElem);
      gsap.to(alertElem, {
        opacity: 0,
        y: -15,
        height: 0,
        paddingTop: 0,
        paddingBottom: 0,
        marginTop: 0,
        marginBottom: 0,
        borderWidth: 0,
        duration: 0.5,
        ease: "power3.inOut",
        onComplete: () => {
          alertElem.remove();
          // Refresh ScrollTrigger agar animasi objek di bawahnya menyesuaikan tata letak baru
          if (typeof ScrollTrigger !== 'undefined') ScrollTrigger.refresh();
        }
      });
    };

    // 2. Auto-dismiss setelah 5 detik
    setTimeout(() => {
      alerts.forEach((alert) => {
        if (document.body.contains(alert)) {
          closeAlertSmoothly(alert);
        }
      });
    }, 5000);

    // 3. Timpa fungsi tombol 'X' bawaan dari PHP dengan animasi mulus
    const closeBtns = document.querySelectorAll(".close-alert");
    closeBtns.forEach((btn) => {
      btn.removeAttribute("onclick");
      btn.addEventListener("click", function () {
        const alertBox = this.closest(".alert");
        if (alertBox) {
          closeAlertSmoothly(alertBox);
        }
      });
    });
  }

  // ========== ANIMASI MASUK NAVBAR ==========
  const navItems = document.querySelectorAll(
    ".header h1, .header h2, .nav-menu a, .user-menu",
  );
  gsap.fromTo(
    navItems,
    { y: -30, opacity: 0 },
    { y: 0, opacity: 1, duration: 0.5, stagger: 0.05, ease: "power3.out" },
  );

  // ========== MAGNETIC EFFECT ==========
  const magnetics = document.querySelectorAll(".magnetic-btn");

  magnetics.forEach((btn) => {
    let rect = null;
    const btnFill = btn.querySelector(".btn-fill");

    btn.addEventListener("mouseenter", function () {
      rect = btn.getBoundingClientRect();
      if (btnFill) {
        gsap.killTweensOf(btnFill);
        gsap.set(btnFill, { top: "100%", borderRadius: "50%" });
        gsap.to(btnFill, {
          top: "-10px",
          borderRadius: "50%",
          duration: 0.4,
          ease: "power3.out",
        });

        if (btn.classList.contains("floating-menu-btn")) {
          gsap.killTweensOf(btn, "boxShadow,backgroundColor");
          gsap.to(btn, {
            boxShadow: "0 10px 20px rgba(197, 165, 90, 0.4)",
            duration: 0.4,
            ease: "power3.out",
          });
          gsap.to(btn, {
            backgroundColor: "var(--gold)",
            duration: 0.1,
            delay: 0.3,
          });
        }
      }
    });

    btn.addEventListener("mousemove", function (e) {
      if (!rect) rect = btn.getBoundingClientRect();

      const centerX = rect.left + window.scrollX + rect.width / 2;
      const centerY = rect.top + window.scrollY + rect.height / 2;

      const x = e.pageX - centerX;
      const y = e.pageY - centerY;

      let targets = [btn];
      let innerContent = btn.querySelector(".hamburger-inner, .btn-text-inner");

      if (btn.closest(".nav-menu")) {
        const navDot = document.querySelector(".nav-hover-dot");
        if (navDot) targets.push(navDot);
      }

      let multiplierX = 0.45;
      let multiplierY = 0.45;

      if (
        btn.tagName.toLowerCase() === "h1" ||
        btn.tagName.toLowerCase() === "h2" ||
        btn.classList.contains("user-name")
      ) {
        multiplierX = 0.1499;
        multiplierY = 0.585;
      }

      gsap.to(targets, {
        x: x * multiplierX,
        y: y * multiplierY,
        duration: 1.5,
        ease: "power4.out",
      });

      if (innerContent) {
        let innerMultiplier = 0.25;

        gsap.to(innerContent, {
          x: x * innerMultiplier,
          y: y * innerMultiplier,
          duration: 1.5,
          ease: "power4.out",
        });
      }
    });

    btn.addEventListener("mouseleave", function () {
      rect = null;

      if (btnFill) {
        gsap.killTweensOf(btnFill);
        gsap.to(btnFill, {
          top: "-150px",
          borderRadius: "50%",
          duration: 0.4,
          ease: "power3.out",
        });

        if (btn.classList.contains("floating-menu-btn")) {
          gsap.killTweensOf(btn, "boxShadow,backgroundColor");
          gsap.set(btn, { backgroundColor: "var(--primary)" });
          gsap.to(btn, {
            boxShadow: "0 10px 20px rgba(139, 26, 26, 0.3)",
            duration: 0.4,
            ease: "power3.out",
          });
        }
      }

      let targets = [btn];
      let innerContent = btn.querySelector(".hamburger-inner, .btn-text-inner");

      if (btn.closest(".nav-menu")) {
        const navDot = document.querySelector(".nav-hover-dot");
        if (navDot) targets.push(navDot);
      }

      gsap.to(targets, {
        x: 0,
        y: 0,
        duration: 1.5,
        ease: "elastic.out(1, 0.3)",
      });

      if (innerContent) {
        gsap.to(innerContent, {
          x: 0,
          y: 0,
          duration: 1.5,
          ease: "elastic.out(1, 0.3)",
        });
      }
    });
  });

  // ========== LOGO SLIDING EFFECT ==========
  const headerLogo = document.querySelector(".header h2.magnetic-btn");
  if (headerLogo) {
    const wrapper = headerLogo.querySelector(".brand-text-wrapper");
    const innerText = headerLogo.querySelector(".brand-text-inner");
    const prefixText = headerLogo.querySelector(".brand-text-prefix");
    const centerText = headerLogo.querySelector(".brand-text-center");
    const suffixText = headerLogo.querySelector(".brand-text-suffix");

    const updateLogoWidths = () => {
      if (wrapper && prefixText && centerText) {
        const originalWidth =
          prefixText.getBoundingClientRect().width +
          centerText.getBoundingClientRect().width;
        wrapper.style.width = originalWidth + "px";
      }
    };

    updateLogoWidths();
    window.addEventListener("load", updateLogoWidths);

    headerLogo.addEventListener("mouseenter", () => {
      if (prefixText && innerText && suffixText && centerText && wrapper) {
        const shiftDist = prefixText.getBoundingClientRect().width;
        const hoverTargetWidth =
          centerText.getBoundingClientRect().width +
          suffixText.getBoundingClientRect().width;

        gsap.to(wrapper, {
          width: hoverTargetWidth,
          duration: 0.65,
          ease: "power3.inOut",
        });
        gsap.to(innerText, {
          x: -shiftDist,
          duration: 0.65,
          ease: "power3.inOut",
        });
      }
    });

    headerLogo.addEventListener("mouseleave", () => {
      if (innerText && wrapper && prefixText && centerText) {
        const originalWidth =
          prefixText.getBoundingClientRect().width +
          centerText.getBoundingClientRect().width;

        gsap.to(wrapper, {
          width: originalWidth,
          duration: 0.65,
          ease: "power3.inOut",
        });
        gsap.to(innerText, { x: 0, duration: 0.65, ease: "power3.inOut" });
      }
    });
  }

  // ========== USER NAME SLIDING EFFECT ==========
  const userMenuBtn = document.querySelector(".user-info .user-name");
  if (userMenuBtn) {
    const wrapper = userMenuBtn.querySelector(".user-text-wrapper");
    const innerText = userMenuBtn.querySelector(".user-text-inner");
    const centerText = userMenuBtn.querySelector(".user-text-center");
    const suffixText = userMenuBtn.querySelector(".user-text-suffix");

    const updateUserWidths = () => {
      if (wrapper && centerText && suffixText) {
        const centerWidth = centerText.getBoundingClientRect().width;
        const suffixWidth = suffixText.getBoundingClientRect().width;

        wrapper.style.width = centerWidth + "px";
        wrapper.style.minWidth = centerWidth + "px";

        wrapper.dataset.centerWidth = centerWidth;
        wrapper.dataset.suffixWidth = suffixWidth;
      }
    };

    updateUserWidths();
    setTimeout(updateUserWidths, 100);
    window.addEventListener("load", updateUserWidths);

    userMenuBtn.addEventListener("mouseenter", () => {
      if (innerText && suffixText && centerText && wrapper) {
        const centerWidth = parseFloat(wrapper.dataset.centerWidth) || centerText.getBoundingClientRect().width;
        const suffixWidth = parseFloat(wrapper.dataset.suffixWidth) || suffixText.getBoundingClientRect().width;

        gsap.to(wrapper, {
          width: suffixWidth,
          minWidth: suffixWidth,
          duration: 0.70,
          ease: "power3.inOut"
        });

        gsap.to(innerText, {
          x: -centerWidth,
          duration: 0.70,
          ease: "power3.inOut",
        });
      }
    });

    userMenuBtn.addEventListener("mouseleave", () => {
      if (innerText && wrapper && centerText) {
        const centerWidth = parseFloat(wrapper.dataset.centerWidth) || centerText.getBoundingClientRect().width;

        gsap.to(wrapper, {
          width: centerWidth,
          minWidth: centerWidth,
          duration: 0.70,
          ease: "power3.inOut"
        });

        gsap.to(innerText, { x: 0, duration: 0.70, ease: "power3.inOut" });
      }
    });
  }


  // ========== LENIS SMOOTH SCROLL ==========
  window.lenis = new Lenis({
    lerp: 0.08,
    duration: 1.2,
    smoothWheel: true,
    wheelMultiplier: 0.8,
  });

  // ========== SMART LENIS PREVENT LOGIC ==========
  // Hanya matikan Lenis pada elemen apabila ia benar-benar bisa di-scroll (datanya luber)
  // Menghindari tabel yang jumlah datanya sedikit menahan scroll mouse wheel user.
  const smartScrollContainers = document.querySelectorAll('[data-lenis-prevent]');
  smartScrollContainers.forEach(container => {
    const checkScroll = () => {
      if (container.scrollHeight > container.clientHeight + 2) {
        container.setAttribute('data-lenis-prevent', 'true');
      } else {
        container.removeAttribute('data-lenis-prevent');
      }
    };

    // Periksa pada saat dimuat
    checkScroll();

    // Periksa ulang setiap kali mouse masuk ke area (jaga-jaga ada perubahan data browser zoom/edit)
    container.addEventListener('mouseenter', checkScroll);
    container.addEventListener('touchstart', checkScroll, { passive: true });
  });


  window.addEventListener("keydown", (e) => {
    const activeTag = document.activeElement.tagName.toLowerCase();
    if (activeTag === "input" || activeTag === "textarea") return;

    const keys = [
      "ArrowUp",
      "ArrowDown",
      "PageUp",
      "PageDown",
      "Home",
      "End",
      " ",
    ];
    if (keys.includes(e.key)) {
      e.preventDefault();

      const isModalOpen = document.body.style.overflow === 'hidden' && window.modalLenis;
      const activeLenis = isModalOpen ? window.modalLenis : window.lenis;

      let targetScroll = activeLenis.targetScroll !== undefined ? activeLenis.targetScroll : (activeLenis.scroll || 0);
      if (!isModalOpen && !targetScroll) {
        targetScroll = window.scrollY;
      }
      const viewportHeight = isModalOpen ? activeLenis.dimensions.height : window.innerHeight;

      switch (e.key) {
        case "ArrowUp":
          targetScroll -= 150;
          break;
        case "ArrowDown":
          targetScroll += 150;
          break;
        case "PageUp":
          targetScroll -= viewportHeight * 0.8;
          break;
        case "PageDown":
        case " ":
          targetScroll += viewportHeight * 0.8;
          break;
        case "Home":
          targetScroll = 0;
          break;
        case "End":
          targetScroll = isModalOpen ? activeLenis.dimensions.scrollHeight : document.body.scrollHeight;
          break;
      }

      activeLenis.scrollTo(targetScroll, {
        duration: 1.2,
        ease: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
      });
    }
  });

  // Animation is now natively handled via CSS on .nav-active class.

  // ========== LENIS RAF LOOP ==========
  function raf(time) {
    window.lenis.raf(time);
    if (window.modalLenis) {
      window.modalLenis.raf(time);
    }
    requestAnimationFrame(raf);
  }
  requestAnimationFrame(raf);

  // Pause Lenis logic migrated to master click listener
});

window.initModalLenis = function (modalId) {
  setTimeout(() => {
    const modal = document.getElementById(modalId);
    if (!modal) return;
    const modalBody = modal.querySelector(".modal-body");
    if (!modalBody) return;

    let contentWrapper = modalBody.querySelector(".lenis-modal-inner");
    if (!contentWrapper) {
      contentWrapper = document.createElement("div");
      contentWrapper.className = "lenis-modal-inner";
      while (modalBody.firstChild) {
        contentWrapper.appendChild(modalBody.firstChild);
      }
      modalBody.appendChild(contentWrapper);
    }

    if (window.modalLenis) {
      window.modalLenis.destroy();
    }

    window.modalLenis = new Lenis({
      wrapper: modalBody,
      content: contentWrapper,
      lerp: 0.08,
      duration: 1.2,
      smoothWheel: true,
      wheelMultiplier: 0.8,
    });
  }, 10);
};
