/* global React, ReactDOM, Rail, Topbar, ScreenIndex, ScreenIndexButton, WizardBar, NextStepButton, WIZARD_STEPS, WIZARD_INDEX, ScrOnboarding, ScrMemory, ScrResume, ScrSummary, ScrTailor, ScrTracker, ScrPrep, ScrBoard, ScrNetwork, ScrEvents, NET_COMPANIES, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakButton */
const { useState: useRoot } = React;

const SCROLL_KEY = "offerroom.route";
const DONE_KEY = "offerroom.completed";
const RAIL_KEY = "offerroom.rail";

// Tweaks for the "Where you stand" page (ScrSummary). The host persists changes
// by rewriting the object between the EDITMODE markers.
const SUMMARY_TWEAKS = /*EDITMODE-BEGIN*/{
  "tone": "warm",
  "stage": "experienced",
  "horizon": 5,
  "detail": 2,
  "plainLabels": false,
  "netTier": "premium",
  "netStrength": "strong",
  "netPersonas": true,
  "netSpotlight": false
}/*EDITMODE-END*/;

// The "Screen index" button is a kit-review affordance for the standalone kit.
// Hide it when the app is embedded (e.g. the marketing site's preview iframe).
const EMBEDDED = (() => { try { return window.self !== window.top; } catch { return true; } })();

const loadDone = () => {
  try { return JSON.parse(localStorage.getItem(DONE_KEY)) || []; } catch { return []; }
};

function ProductApp() {
  const [route, setRoute] = useRoot(() => { const r = localStorage.getItem(SCROLL_KEY) || "onboarding"; return r === "reach" ? "network" : r; });
  const [completed, setCompleted] = useRoot(loadDone);
  const [indexOpen, setIndexOpen] = useRoot(false);
  const [railCollapsed, setRailCollapsed] = useRoot(false); // always start expanded
  const toggleRail = () => setRailCollapsed(c => { const n = !c; localStorage.setItem(RAIL_KEY, n ? "1" : "0"); return n; });
  const [netTarget, setNetTarget] = useRoot(null);
  const [tw, setTweak] = useTweaks(SUMMARY_TWEAKS);
  const scrollRef = React.useRef(null);

  // The tweaks only affect the "Where you stand" page, so jump there on any
  // change to keep what you're tuning in view (without touching wizard state).
  const viewSummary = () => {
    setRoute("summary");
    localStorage.setItem(SCROLL_KEY, "summary");
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  };
  const onTweak = (k, v) => { setTweak(k, v); if (route !== "summary") viewSummary(); };

  const persistDone = (next) => { setCompleted(next); localStorage.setItem(DONE_KEY, JSON.stringify(next)); };

  // Mark every wizard step before `targetKey` complete, so the bar fills as you move forward.
  const fillBehind = (targetKey) => {
    if (!(targetKey in WIZARD_INDEX)) return completed;
    const idx = WIZARD_INDEX[targetKey];
    const earlier = WIZARD_STEPS.slice(0, idx).map(s => s.key);
    const merged = Array.from(new Set([...completed, ...earlier]));
    if (merged.length !== completed.length) persistDone(merged);
    return merged;
  };

  const navigate = (r) => {
    fillBehind(r);
    setRoute(r);
    localStorage.setItem(SCROLL_KEY, r);
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  };
  const go = (r) => { setNetTarget(null); navigate(r); };
  // Deep-link into the unified network map from a way-in badge / tracker Paths action.
  const onWayIn = (co) => { setNetTarget({ companyId: (co || "").toLowerCase() }); navigate("network"); };

  // Next-step button: complete the current wizard step, then advance.
  const advance = (from, to) => {
    if (from in WIZARD_INDEX && !completed.includes(from)) {
      persistDone(Array.from(new Set([...completed, from])));
    }
    go(to);
  };

  const setupDone = WIZARD_STEPS.every(s => completed.includes(s.key));
  const showNext = !setupDone && NEXT_OF[route];
  const isNet = route === "network";
  const isEvents = route === "events";

  return (
    <div style={{ display: "flex", height: "100vh", width: "100vw", overflow: "hidden", background: "var(--paper)" }}>
      <Rail route={route} go={go} collapsed={railCollapsed} onToggle={toggleRail}/>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        <Topbar route={route}/>
        {!setupDone && <WizardBar route={route} completed={completed} go={go}/>}
        <main ref={scrollRef} key={route} className="cad-fade" style={{ flex: 1, overflow: "auto", padding: "26px 28px", paddingBottom: showNext ? 104 : 40, minHeight: 0, position: "relative" }}>
          {route === "onboarding" && <ScrOnboarding onDone={() => advance("onboarding", "memory")}/>}
          {route === "memory" && <ScrMemory onDone={() => advance("memory", "resume")}/>}
          {route === "resume" && <ScrResume/>}
          {route === "summary" && <ScrSummary tw={tw} onExplore={() => go("board")}/>}
          {route === "board" && <ScrBoard onTailor={() => go("tailor")} onWayIn={onWayIn}/>}
          {route === "tailor" && <ScrTailor/>}
          {route === "network" && <ScrNetwork target={netTarget} tier={tw.netTier} strength={tw.netStrength} spotlight={tw.netSpotlight}/>}
          {route === "events" && <ScrEvents tier={tw.netTier} onWayIn={onWayIn}/>}
          {route === "tracker" && <ScrTracker onPrep={() => go("prep")} onPaths={onWayIn}/>}
          {route === "prep" && <ScrPrep onBack={() => go("tracker")}/>}
        </main>
      </div>
      {showNext && <NextStepButton route={route} completed={completed} go={go} onAdvance={advance}/>}
      {!EMBEDDED && <ScreenIndexButton onOpen={() => setIndexOpen(true)} collapsed={railCollapsed}/>}
      {!EMBEDDED && indexOpen && <ScreenIndex onClose={() => setIndexOpen(false)} go={go}/>}

      <TweaksPanel title={isEvents ? "Events" : isNet ? "Get introduced" : "Where you stand"}>
        {isEvents ? (
          <>
            <TweakSection label="Plan"/>
            <TweakRadio label="Tier" value={tw.netTier}
              options={[{ value: "premium", label: "Premium" }, { value: "free", label: "Free" }]}
              onChange={(v) => setTweak("netTier", v)}/>
            <div style={{ fontSize: 11, lineHeight: 1.45, color: "rgba(41,38,27,.6)", paddingTop: 2 }}>Free tier keeps company events but locks the profile-matched feed behind an upsell. Shares the plan tweak with the network map.</div>
          </>
        ) : isNet ? (
          <>
            <TweakSection label="Plan"/>
            <TweakRadio label="Tier" value={tw.netTier}
              options={[{ value: "premium", label: "Premium" }, { value: "free", label: "Free" }]}
              onChange={(v) => setTweak("netTier", v)}/>
            <TweakSection label="Network"/>
            <TweakRadio label="Density" value={tw.netStrength}
              options={[{ value: "strong", label: "Full map" }, { value: "weak", label: "Sparse" }]}
              onChange={(v) => setTweak("netStrength", v)}/>
            <TweakToggle label="Spotlight top connector" value={tw.netSpotlight}
              onChange={(v) => setTweak("netSpotlight", v)}/>
            <div style={{ fontSize: 11, lineHeight: 1.45, color: "rgba(41,38,27,.6)", paddingTop: 2 }}>Tier locks the map and super-connector rail (free tier). Density swaps in the sparse-map nudge. Spotlight pre-highlights the #1 connector's fan.</div>
          </>
        ) : (
          <>
            {route !== "summary" && (
              <div style={{ display: "flex", flexDirection: "column", gap: 8, padding: "9px 10px", marginBottom: 2, borderRadius: 8, background: "rgba(140,21,21,0.05)", border: "1px solid rgba(140,21,21,0.12)" }}>
                <span style={{ fontSize: 11, lineHeight: 1.45, color: "rgba(41,38,27,.72)" }}>These controls tune the “Where you stand” page.</span>
                <TweakButton label="Open that page" onClick={viewSummary}/>
              </div>
            )}
            <TweakSection label="Profile"/>
            <TweakRadio label="Career stage" value={tw.stage}
              options={[{ value: "experienced", label: "Experienced" }, { value: "newgrad", label: "New grad" }]}
              onChange={(v) => onTweak("stage", v)}/>
            <TweakSection label="The read"/>
            <TweakRadio label="Tone" value={tw.tone}
              options={[{ value: "warm", label: "Warm" }, { value: "direct", label: "Direct" }]}
              onChange={(v) => onTweak("tone", v)}/>
            <TweakRadio label="Detail" value={tw.detail}
              options={[{ value: 1, label: "Light" }, { value: 2, label: "Medium" }, { value: 3, label: "Full" }]}
              onChange={(v) => onTweak("detail", v)}/>
            <TweakToggle label="Plain language" value={tw.plainLabels}
              onChange={(v) => onTweak("plainLabels", v)}/>
            <TweakSection label="Career chart"/>
            <TweakRadio label="Horizon" value={tw.horizon}
              options={[{ value: 3, label: "3 yrs" }, { value: 5, label: "5 yrs" }]}
              onChange={(v) => onTweak("horizon", v)}/>
          </>
        )}
      </TweaksPanel>
    </div>
  );
}

// Self-mount only as the standalone web-app page — never when this file is
// loaded as part of the design-system bundle on a consumer's page.
const __waRoot = document.getElementById("root");
if (__waRoot && window.__OFFERROOM_KIT__ === "webapp") {
  ReactDOM.createRoot(__waRoot).render(<ProductApp/>);
}
