"use client";

import { useEffect, useState } from "react";
import "./section-nav.css";

const sections = [
  { id: "i84ba", label: "Home" },
  { id: "ilwyn", label: "Solutions" },
  { id: "platform-modules", label: "Platform" },
  { id: "who-we-serve", label: "Who We Serve" },
  { id: "how-it-works", label: "How It Works" },
  { id: "security", label: "Security" },
  { id: "injpw", label: "Get Started" },
] as const;

// Mirrors --nav-offset in theme.css - how far a scroll target sits below the
// fixed navbar.
const NAV_OFFSET = 96;

export function SectionNav() {
  const [visible, setVisible] = useState(false);
  const [active, setActive] = useState(0);

  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 240);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    const targets = sections
      .map((s) => document.getElementById(s.id))
      .filter((el): el is HTMLElement => el !== null);
    if (targets.length === 0) return;

    // A thin band through the viewport's middle decides which section is
    // "active" - the first target crossing it wins, so the highlight tracks
    // whichever section is actually centered on screen while scrolling.
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) return;
          const idx = targets.indexOf(entry.target as HTMLElement);
          if (idx !== -1) setActive(idx);
        });
      },
      { rootMargin: "-45% 0px -45% 0px", threshold: 0 },
    );

    targets.forEach((el) => observer.observe(el));
    return () => observer.disconnect();
  }, []);

  const scrollToSection = (id: string) => (ev: React.MouseEvent) => {
    ev.preventDefault();
    const el = document.getElementById(id);
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - NAV_OFFSET;
    window.scrollTo({ top, behavior: "smooth" });
  };

  return (
    <nav className={`section-nav${visible ? " is-visible" : ""}`} aria-label="Page sections">
      <ul className="section-nav-list">
        {sections.map((s, i) => (
          <li className="section-nav-item" key={s.id}>
            <a
              href={`#${s.id}`}
              className={`section-nav-dot${active === i ? " is-active" : ""}`}
              aria-label={s.label}
              aria-current={active === i ? "true" : undefined}
              onClick={scrollToSection(s.id)}
            >
              <span className="section-nav-tooltip">{s.label}</span>
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}
