// App shell: composes sections, side nav, tweaks panel.

const { useState: useState3, useEffect: useEffect3 } = React;

// ---- Tweaks (persisted defaults) ----
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHue": 50,
  "typeScale": 1.0,
  "grainOverlay": false,
  "metaphorLabel": "flow"
}/*EDITMODE-END*/;

function SlideNav({ sections }) {
  const [active, setActive] = useState3(sections[0]?.id);
  useEffect3(() => {
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setActive(e.target.id);
        });
      },
      { rootMargin: "-40% 0px -55% 0px" }
    );
    sections.forEach((s) => {
      const el = document.getElementById(s.id);
      if (el) io.observe(el);
    });
    return () => io.disconnect();
  }, [sections]);

  return (
    <nav className="slide-nav" aria-label="Sections">
      {sections.map((s, i) => (
        <a
          key={s.id}
          href={`#${s.id}`}
          className={`slide-nav-item ${active === s.id ? "active" : ""}`}
          title={s.label}
        >
          <span className="slide-nav-label">{s.label}</span>
          <span className="slide-nav-marker">
            <span className="slide-nav-num">{String(i + 1).padStart(2, "0")}</span>
          </span>
        </a>
      ))}
    </nav>
  );
}

function TweaksPanel({ open, tweaks, setTweaks }) {
  if (!open) return null;
  const update = (k, v) => {
    const next = { ...tweaks, [k]: v };
    setTweaks(next);
    try {
      window.parent.postMessage(
        { type: "__edit_mode_set_keys", edits: { [k]: v } },
        "*"
      );
    } catch (e) {}
  };
  return (
    <div className="tweaks-panel">
      <div className="tweaks-title">Tweaks</div>

      <div className="tweak-row">
        <label>Type scale</label>
        <input
          type="range"
          min="0.9"
          max="1.15"
          step="0.01"
          value={tweaks.typeScale}
          onChange={(e) => update("typeScale", Number(e.target.value))}
        />
        <span className="tweak-val">{tweaks.typeScale.toFixed(2)}×</span>
      </div>

      <div className="tweaks-hint">
        Metaphor switch lives inside §03 (flow · circuit · stack).
      </div>
    </div>
  );
}

// All sections registered once. `audiences` controls visibility; ORDER controls
// per-audience render order. Adding a section: add it here, add its id to one or
// both ORDER arrays.
const SECTIONS = [
  { id: "top",          label: "Overview",     Component: () => <HeroSection />,             audiences: ["team", "client"] },
  { id: "outcomes",     label: "Outcomes",     Component: () => <OutcomesSection />,         audiences: ["client"] },
  { id: "perspectives", label: "Perspectives", Component: () => <PerspectivesSection />,     audiences: ["client"] },
  { id: "examples",     label: "Examples",     Component: () => <ExamplesSection />,         audiences: ["client"] },
  { id: "safety",       label: "Safety",       Component: () => <SafetySection />,           audiences: ["client"] },
  { id: "indicators",   label: "Indicators",   Component: () => <IndicatorsSection />,       audiences: ["client"] },
  { id: "dora",         label: "DORA",         Component: () => <DoraSection />,             audiences: ["team", "client"] },
  { id: "adoption",     label: "Adoption",     Component: () => <AdoptionStagesSection />,   audiences: ["team", "client"] },
  { id: "why",          label: "Why a method", Component: () => <WhyMethodSection />,        audiences: ["team", "client"] },
  { id: "convictions",  label: "Convictions",  Component: () => <ConvictionsSection />,      audiences: ["team", "client"] },
  { id: "method",       label: "5 steps",      Component: () => <MethodSection />,           audiences: ["team", "client"] },
  { id: "diagnose",     label: "Diagnose",     Component: () => <DiagnosticSection />,       audiences: ["team"] },
  { id: "explore",      label: "AI by stage",  Component: () => <ExploreSection />,          audiences: ["team", "client"] },
];

const ORDER = {
  team:   ["top", "dora", "adoption", "why", "convictions", "method", "diagnose", "explore"],
  // Mirror team narrative (pillars → foundations → journey → why → convictions → practice → safety → AI by stage),
  // then close with client-specific payoff sections (outcomes → perspectives → indicators).
  client: ["top", "dora", "adoption", "why", "convictions", "method", "safety", "explore", "examples", "outcomes", "perspectives", "indicators"],
};

function AppInner() {
  const [tweaks, setTweaks] = useState3(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = useState3(false);
  const { audience } = useAudience();

  // Edit mode protocol
  useEffect3(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setTweaksOpen(true);
      if (d.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    try {
      window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    } catch (e) {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  // Apply tweaks as CSS vars
  useEffect3(() => {
    const root = document.documentElement;
    root.style.setProperty("--type-scale", tweaks.typeScale);
  }, [tweaks]);

  const visible = (ORDER[audience] || ORDER.team)
    .map((id) => SECTIONS.find((s) => s.id === id))
    .filter((s) => s && s.audiences.includes(audience));

  const navSections = visible.map(({ id, label }) => ({ id, label }));

  return (
    <div className="app" data-audience={audience}>
      <AudienceToggle />
      <SlideNav key={audience} sections={navSections} />
      <TweaksPanel open={tweaksOpen} tweaks={tweaks} setTweaks={setTweaks} />

      {visible.map(({ id, Component }, i) => (
        <div key={id} id={id} data-screen-label={`${String(i + 1).padStart(2, "0")} ${id}`}>
          <Component />
        </div>
      ))}
      <CloserSection />
    </div>
  );
}

function App() {
  return (
    <AudienceProvider>
      <AppInner />
    </AudienceProvider>
  );
}

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