// TABS is a function so section refs resolve at render time, not script-parse time —
// avoids races where App.jsx evaluates before later Babel <script> tags finish.
const buildTabs = () => [
  { id: "summary", label: "Summary", render: window.SectionExecutiveSummary },
  { id: "coverage", label: "Coverage", render: window.SectionRFPCoverage },
  { id: "studio", label: "Studio", render: window.SectionStudio },
  { id: "scope", label: "Scope", render: window.SectionScopeOfWork },
  { id: "architecture", label: "Architecture", render: window.SectionArchitecture },
  { id: "prototype", label: "Prototype", render: window.SectionPrototype },
  { id: "design", label: "Design", render: window.SectionDesignSystem, group: "more" },
  { id: "features", label: "Features", render: window.SectionNewFeatures, group: "more" },
  { id: "timeline", label: "Timeline", render: window.SectionTimeline },
  { id: "resources", label: "Resources", render: window.SectionResources, group: "more" },
  { id: "tech", label: "Tech", render: window.SectionTechStack, group: "more" },
  { id: "assumptions", label: "Assumptions", render: window.SectionAssumptions, group: "more" },
  { id: "commercials", label: "Commercials", render: window.SectionCommercials },
];

function BrandMark() {
  return (
    <div className="flex items-center gap-3 shrink-0">
      <svg width="32" height="32" viewBox="0 0 40 40" fill="none" className="shrink-0">
        <rect x="1" y="1" width="38" height="38" rx="10" fill="#002855" />
        <path
          d="M12 10h8a6 6 0 016 6 5 5 0 01-2.5 4.3A5.5 5.5 0 0128 25a6 6 0 01-6 6h-10V10z"
          fill="#C8A95B"
        />
        <circle cx="30" cy="12" r="3" fill="#C8A95B" />
      </svg>
      <div className="leading-tight whitespace-nowrap">
        <div className="font-serif text-[14px] font-bold text-bits-ink">
          BITS Unified Platform
        </div>
        <div className="text-[10px] text-bits-steel uppercase tracking-[0.14em]">
          Proposal · v1
        </div>
      </div>
    </div>
  );
}

function MoreMenu({ active, setActive, moreTabs }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (!ref.current?.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);
  const activeInMore = moreTabs.some((t) => t.id === active);
  return (
    <div className="relative" ref={ref}>
      <button
        onClick={() => setOpen((v) => !v)}
        className={`relative px-3 py-2 rounded-md text-[12.5px] font-semibold transition-colors inline-flex items-center gap-1.5 ${
          activeInMore ? "text-bits-deep" : "text-bits-steel hover:text-bits-ink"
        }`}
      >
        More
        <svg
          width="11"
          height="11"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2.2"
          strokeLinecap="round"
          className={`transition-transform ${open ? "rotate-180" : ""}`}
        >
          <polyline points="6 9 12 15 18 9" />
        </svg>
        {activeInMore && (
          <span className="absolute left-2 right-6 bottom-0.5 h-0.5 bg-bits-gold rounded-full tab-indicator" />
        )}
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-2 w-52 rounded-xl border border-bits-line bg-white shadow-glass p-1 fade-in z-50">
          {moreTabs.map((t) => {
            const isActive = active === t.id;
            return (
              <button
                key={t.id}
                onClick={() => {
                  setActive(t.id);
                  setOpen(false);
                }}
                className={`w-full text-left px-3 py-2 rounded-md text-[12.5px] font-semibold transition-colors ${
                  isActive
                    ? "bg-bits-cream text-bits-deep"
                    : "text-bits-ink hover:bg-bits-mist/60"
                }`}
              >
                {t.label}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function Header({ active, setActive, tabs }) {
  const primaryTabs = tabs.filter((t) => t.group !== "more");
  const moreTabs = tabs.filter((t) => t.group === "more");
  return (
    <header className="sticky top-0 z-40 glass">
      <div className="max-w-7xl mx-auto px-6 md:px-10 flex items-center gap-4 h-16">
        <BrandMark />
        <nav className="hidden lg:flex items-center gap-1 ml-auto">
          {primaryTabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setActive(t.id)}
              className={`relative px-3 py-2 rounded-md text-[12.5px] font-semibold transition-colors ${
                active === t.id
                  ? "text-bits-deep"
                  : "text-bits-steel hover:text-bits-ink"
              }`}
            >
              {t.label}
              {active === t.id && (
                <span className="absolute left-2 right-2 bottom-0.5 h-0.5 bg-bits-gold rounded-full tab-indicator" />
              )}
            </button>
          ))}
          <MoreMenu active={active} setActive={setActive} moreTabs={moreTabs} />
        </nav>
      </div>

      <div className="lg:hidden overflow-x-auto border-t border-bits-line/60 scroll-x">
        <div className="flex gap-1 px-4 py-2 min-w-max">
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setActive(t.id)}
              className={`px-3 py-1.5 rounded-full text-[12px] font-semibold whitespace-nowrap ${
                active === t.id
                  ? "bg-bits-deep text-white"
                  : "bg-white text-bits-ink border border-bits-line"
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>
      </div>
    </header>
  );
}

function Hero() {
  return (
    <section className="relative overflow-hidden">
      <div className="absolute inset-0 pointer-events-none">
        <div className="absolute -top-20 right-0 w-[40vw] h-[40vw] rounded-full bg-bits-gold/10 blur-3xl" />
        <div className="absolute bottom-0 -left-20 w-[35vw] h-[35vw] rounded-full bg-bits-deep/10 blur-3xl" />
      </div>
      <div className="relative max-w-7xl mx-auto px-6 md:px-10 pt-16 pb-10">
        <div className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.2em] text-bits-goldDeep mb-5">
          <span className="w-8 h-px bg-bits-gold" />
          Proposal to BITSAA · April 2026
        </div>
        <h1 className="font-serif text-[28px] md:text-[40px] leading-[1.1] tracking-tight text-bits-ink max-w-4xl">
          A unified, AI-native app for every BITSian.
        </h1>
        <p className="mt-5 text-[14px] md:text-[15.5px] text-bits-steel max-w-2xl leading-relaxed">
          Alumni, students, faculty, parents, staff, and admins on one surface
          — voice- or form-driven, never menu-driven. Replaces AlmaConnect,
          institutional portals, DarwinBox, and half a dozen spreadsheets.
          Backed by a finished PRD and a 65-screen interactive prototype.
        </p>
        <div className="mt-7 flex flex-wrap gap-3">
          <a
            href="#summary"
            onClick={(e) => {
              e.preventDefault();
              document.getElementById("summary")?.scrollIntoView({ behavior: "smooth" });
            }}
            className="inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-bits-deep text-white text-[13.5px] font-semibold hover:bg-bits-navy transition-colors"
          >
            Read the proposal
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              strokeLinecap="round"
            >
              <path d="M12 5v14M5 12l7 7 7-7" />
            </svg>
          </a>
          <a
            href="/prototype/"
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-white text-bits-ink text-[13.5px] font-semibold border border-bits-line hover:border-bits-deep/40 transition-colors"
          >
            Open the prototype
          </a>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="mt-10 border-t border-bits-line bg-white/60">
      <div className="max-w-7xl mx-auto px-6 md:px-10 py-6 text-center text-[13px] text-bits-steel">
        A proposal from VoiceQube · 2026
      </div>
    </footer>
  );
}

function App() {
  const [active, setActive] = React.useState("summary");
  const tabs = React.useMemo(() => buildTabs().filter((t) => t.render), []);

  // Sync scroll → active tab
  React.useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setActive(e.target.id);
          }
        });
      },
      { rootMargin: "-40% 0px -55% 0px", threshold: 0 }
    );
    tabs.forEach((t) => {
      const el = document.getElementById(t.id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, [tabs]);

  const handleSetActive = (id) => {
    setActive(id);
    const el = document.getElementById(id);
    el?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <div className="relative">
      <Header active={active} setActive={handleSetActive} tabs={tabs} />
      <Hero />
      {tabs.map(({ render: R }, i) => (
        <React.Fragment key={i}>
          <R />
        </React.Fragment>
      ))}
      <Footer />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
