"use client";

import { useEffect } from "react";
import Lenis from "lenis";

/**
 * Smooth scroll Lenis — memberi rasa "melayang" khas situs Framer.
 * Sekaligus menangani klik anchor (#section) agar scroll halus ke target.
 */
export default function SmoothScroll({
  children,
}: {
  children: React.ReactNode;
}) {
  useEffect(() => {
    const lenis = new Lenis({
      lerp: 0.1,
      smoothWheel: true,
    });

    let rafId: number;
    const loop = (time: number) => {
      lenis.raf(time);
      rafId = requestAnimationFrame(loop);
    };
    rafId = requestAnimationFrame(loop);

    // Anchor #hash → scrollTo via Lenis
    const onClick = (e: MouseEvent) => {
      const anchor = (e.target as HTMLElement).closest<HTMLAnchorElement>(
        'a[href^="#"]'
      );
      if (!anchor) return;

      const hash = anchor.getAttribute("href") ?? "";

      // href="#" (logo, brand, ikon sosial) → cukup gulir halus ke atas.
      // Penting: querySelector("") melempar SyntaxError, jadi harus di-guard.
      if (hash.length < 2) {
        e.preventDefault();
        lenis.scrollTo(0);
        return;
      }

      const target = document.querySelector(hash);
      if (!target) return;
      e.preventDefault();
      lenis.scrollTo(target as HTMLElement, { offset: -80 });
    };
    document.addEventListener("click", onClick);

    return () => {
      cancelAnimationFrame(rafId);
      document.removeEventListener("click", onClick);
      lenis.destroy();
    };
  }, []);

  return <>{children}</>;
}
