"use client";

import { useEffect, useState, useCallback } from "react";
import type Lenis from "lenis";

export interface NavSection {
  id: string;
  label: string;
}

export default function SideNav({ sections }: { sections: NavSection[] }) {
  const [active, setActive] = useState(sections[0]?.id ?? "");
  const [open, setOpen] = useState(false);

  // Track which section is in view
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) setActive(entry.target.id);
        });
      },
      { rootMargin: "-45% 0px -45% 0px", threshold: 0 }
    );

    sections.forEach(({ id }) => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });

    return () => observer.disconnect();
  }, [sections]);

  const scrollTo = useCallback((id: string) => {
    const el = document.getElementById(id);
    if (!el) return;
    const lenis = (window as unknown as { lenis?: Lenis }).lenis;
    if (lenis) {
      lenis.scrollTo(el, { offset: 0, duration: 1.2 });
    } else {
      el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    setOpen(false);
  }, []);

  return (
    <>
      {/* Mobile toggle */}
      <button
        aria-label="Toggle navigation"
        onClick={() => setOpen((o) => !o)}
        className="fixed right-4 top-4 z-50 rounded-full bg-black/70 p-3 backdrop-blur-md ring-1 ring-white/15 lg:hidden"
      >
        <span className="block h-0.5 w-5 bg-white" />
        <span className="mt-1 block h-0.5 w-5 bg-white" />
        <span className="mt-1 block h-0.5 w-5 bg-white" />
      </button>

      {/* Right-side navigation */}
      <nav
        aria-label="Section navigation"
        className={`fixed right-0 top-0 z-40 flex h-screen flex-col justify-center gap-1 pr-5 pl-6 transition-transform duration-300 lg:translate-x-0 ${
          open
            ? "translate-x-0 bg-black/80 backdrop-blur-xl"
            : "translate-x-full lg:bg-transparent"
        }`}
      >
        <ul className="flex flex-col gap-1">
          {sections.map(({ id, label }, i) => {
            const isActive = active === id;
            return (
              <li key={id} className="group flex items-center justify-end gap-3">
                <button
                  onClick={() => scrollTo(id)}
                  className="flex items-center gap-3 text-right"
                >
                  <span
                    className={`whitespace-nowrap text-[11px] font-semibold uppercase tracking-wider transition-all duration-200 ${
                      isActive
                        ? "text-primary opacity-100"
                        : "text-white/50 opacity-0 group-hover:opacity-100 lg:opacity-0 lg:group-hover:opacity-100"
                    } ${open ? "opacity-100" : ""}`}
                  >
                    <span className="mr-2 tabular-nums text-white/30">
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    {label}
                  </span>
                  <span className="relative flex h-3 w-3 items-center justify-center">
                    <span
                      className={`rounded-full transition-all duration-300 ${
                        isActive
                          ? "h-3 w-3 bg-primary shadow-[0_0_12px_2px_rgba(255,199,44,0.7)]"
                          : "h-2 w-2 bg-white/30 group-hover:bg-white/70"
                      }`}
                    />
                  </span>
                </button>
              </li>
            );
          })}
        </ul>
      </nav>
    </>
  );
}
