import { useEffect, useRef } from "react";
import { useViewMode } from "../context/ViewModeContext";

interface Props {
  activeSection: string;
  sections: { id: string; label: string }[];
  scrollProgress: number;
}

export function TopNav({ activeSection, sections, scrollProgress }: Props) {
  const { mode, setMode } = useViewMode();
  const navRef = useRef<HTMLElement>(null);

  const scrollTo = (id: string) => {
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth" });
  };

  // Auto-scroll nav to keep the active pill visible
  useEffect(() => {
    const nav = navRef.current;
    if (!nav) return;
    const activeBtn = nav.querySelector("[data-active='true']") as HTMLElement | null;
    if (activeBtn) {
      activeBtn.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
    }
  }, [activeSection]);

  return (
    <header className="fixed top-0 left-0 right-0 z-50 h-12 bg-white/95 backdrop-blur-sm border-b border-slate-200">
      <div className="max-w-[1200px] mx-auto h-full flex items-center px-6 gap-5">
        <span className="font-semibold text-[13px] text-slate-900 tracking-tight shrink-0">AI Usage Analytics</span>

        <nav ref={navRef} className="flex-1 flex items-center gap-0.5 overflow-x-auto scrollbar-none">
          {sections.map((s) => {
            const isActive = activeSection === s.id;
            return (
              <button
                key={s.id}
                data-active={isActive}
                onClick={() => scrollTo(s.id)}
                className={`relative px-2.5 py-1 rounded text-[11px] font-medium whitespace-nowrap transition-all duration-200 ${
                  isActive
                    ? "text-slate-900"
                    : "text-slate-400 hover:text-slate-700"
                }`}
              >
                {s.label}
                {isActive && (
                  <span className="absolute bottom-0 left-1 right-1 h-[2px] bg-slate-900 rounded-full" />
                )}
              </button>
            );
          })}
        </nav>

        <div className="flex bg-slate-100 rounded p-0.5 gap-0.5 shrink-0">
          {(["vp", "dev"] as const).map((m) => (
            <button
              key={m}
              onClick={() => setMode(m)}
              className={`px-2.5 py-1 text-[11px] font-medium rounded transition-all duration-200 ${
                mode === m
                  ? "bg-white text-slate-900 shadow-sm"
                  : "text-slate-400 hover:text-slate-600"
              }`}
            >
              {m === "vp" ? "Executive" : "Developer"}
            </button>
          ))}
        </div>
      </div>

      <div className="absolute bottom-0 left-0 h-[1px] bg-slate-300 transition-all duration-150" style={{ width: `${scrollProgress}%` }} />
    </header>
  );
}
