/* global React, ReactDOM */
const { useState, useEffect } = React;

const SECTIONS = [
  { id: "why",         label: "Why Klaviyo",        chapter: "nb" },
  { id: "stories",     label: "Customer stories",   chapter: "nb" },
  { id: "vision",      label: "Portfolio Vision",   chapter: "nb" },
  { id: "multibrand",  label: "Multi-brand",        chapter: "k" },
  { id: "industry",    label: "Industry view",      chapter: "k" },
  { id: "ai",          label: "AI Innovation",      chapter: "k" },
  { id: "fspov",       label: "Klaviyo's POV for FS", chapter: "k" },
  { id: "scv",         label: "SCV",                chapter: "k" },
  { id: "channels",    label: "Channels",           chapter: "k" },
  { id: "analytics",   label: "Analytics",          chapter: "k" },
  { id: "social",      label: "Social",             chapter: "k" },
  { id: "demo",        label: "Demo videos",        chapter: "k" },
  { id: "next",        label: "Next steps",         chapter: "k" },
];

function useActiveSection() {
  const [active, setActive] = useState("why");
  useEffect(() => {
    const onScroll = () => {
      const y = window.scrollY + window.innerHeight * 0.35;
      let current = SECTIONS[0].id;
      for (const s of SECTIONS) {
        const el = document.getElementById(s.id);
        if (!el) continue;
        if (el.offsetTop <= y) current = s.id;
      }
      setActive(current);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return active;
}

function ChapterNav({ active }) {
  const activeSec = SECTIONS.find(s => s.id === active) || SECTIONS[0];
  const isK = activeSec.chapter === "k";
  return (
    <nav className={"nav" + (isK ? " is-klaviyo" : "")}>
      {SECTIONS.map((s, i) => (
        <React.Fragment key={s.id}>
          {i === 2 && <span className="nav-sep" />}
          <a href={"#" + s.id} className={active === s.id ? "is-active" : ""}>
            {s.label}
          </a>
        </React.Fragment>
      ))}
    </nav>
  );
}

function App() {
  const isAdmin = typeof document !== "undefined" && document.body.classList.contains("is-admin");
  if (isAdmin && typeof AdminDashboard === "function") {
    return <AdminDashboard />;
  }
  const active = useActiveSection();
  return (
    <React.Fragment>
      <ChapterNav active={active} />
      <WhyKlaviyo />
      <CustomerStories />
      <PortfolioVision />
      <Hero />
      <MultiBrand />
      <IndustryView />
      <AIEfficiency />
      <FSPointOfView />
      <SingleCustomerView />
      <ChannelShowcase />
      <AnalyticsAndNext />
      <SocialMarketing />
      <DemoVideos />
      <NextSteps />
    </React.Fragment>
  );
}

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