"use client";

import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";

const sections = [
  { id: "introduction", label: "Introduction", labelZh: "简介" },
  { id: "committees", label: "Committees", labelZh: "委员会" },
  { id: "regional-centres", label: "Regional Centres", labelZh: "区域中心" },
  { id: "contact-us", label: "Contact Us", labelZh: "联系我们" },
];

export default function AboutNav() {
  const [active, setActive] = useState("introduction");

  useEffect(() => {
    const observers: IntersectionObserver[] = [];
    sections.forEach(({ id }) => {
      const el = document.getElementById(id);
      if (!el) return;
      const obs = new IntersectionObserver(
        ([entry]) => { if (entry.isIntersecting) setActive(id); },
        { rootMargin: "-30% 0px -60% 0px" }
      );
      obs.observe(el);
      observers.push(obs);
    });
    return () => observers.forEach((o) => o.disconnect());
  }, []);

  const scrollTo = (id: string) => {
    const el = document.getElementById(id);
    if (!el) return;
    const top = el.getBoundingClientRect().top + window.scrollY - 130;
    window.scrollTo({ top, behavior: "smooth" });
    setActive(id);
  };

  return (
    <div
      className="sticky top-[64px] z-40 bg-white border-b"
      style={{ borderColor: "rgba(45,95,166,0.12)" }}
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex gap-0 overflow-x-auto scrollbar-hide">
          {sections.map((s) => (
            <button
              key={s.id}
              onClick={() => scrollTo(s.id)}
              className={cn(
                "flex-shrink-0 flex flex-col items-center px-6 py-3.5 text-sm font-medium border-b-2 transition-all duration-200 cursor-pointer",
                active === s.id
                  ? "border-[#2D5FA6] text-[#2D5FA6]"
                  : "border-transparent text-charcoal/60 hover:text-charcoal hover:border-gray-200"
              )}
            >
              <span>{s.label}</span>
              <span className="text-[10px] mt-0.5 opacity-60">{s.labelZh}</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
