/* ===========================================================================
   app-shell.jsx — owns view (Create/Library), wizard step, persisted store,
   top nav, toast. Mounts the app.
   (useState/useEffect already declared by components.jsx — reuse globals.)
   =========================================================================== */

const SHELL_NEXT_STATUS = { todo: "filming", filming: "filmed", filmed: "todo" };

function load(key, fallback) {
  try { const v = localStorage.getItem(key); return v ? JSON.parse(v) : fallback; }
  catch (e) { return fallback; }
}

const SEED_SHOT = [
  { id: "no-mess-no-mixing-mushroom", status: "filming", ts: 2 },
  { id: "grab-and-go-lifestyle", status: "todo", ts: 1 },
];
const SEED_ANGLES = [
  { id: "taste-test-demo", title: "On-camera taste test",
    note: "Show the gummy being eaten — “tastes like strawberry, not dirt.” Fills the sensory gap nobody in the category covers.",
    status: "approved", ts: 1 },
];

function App() {
  const [view, setView] = useState("dashboard");
  const [analysisId, setAnalysisId] = useState("gruns");
  const [analysisTab, setAnalysisTab] = useState("ads");
  const [step, setStep] = useState(0);
  const [maxStep, setMaxStep] = useState(0);
  const [tab, setTab] = useState("shot");
  const [shot, setShot] = useState(() => load("sm_shot", SEED_SHOT));
  const [angles, setAngles] = useState(() => load("sm_angles", SEED_ANGLES));
  const [toast, setToast] = useState(null);

  useEffect(() => { localStorage.setItem("sm_shot", JSON.stringify(shot)); }, [shot]);
  useEffect(() => { localStorage.setItem("sm_angles", JSON.stringify(angles)); }, [angles]);
  useEffect(() => { if (!toast) return; const id = setTimeout(() => setToast(null), 4200); return () => clearTimeout(id); }, [toast]);

  const showToast = (msg, action) => setToast({ msg, action });
  const goLibrary = (which) => { setView("library"); if (which) setTab(which); window.scrollTo(0, 0); };
  const goCreate = () => { setView("create"); window.scrollTo(0, 0); };
  const goDashboard = () => { setView("dashboard"); window.scrollTo(0, 0); };
  const openAnalysis = (id, openTab) => {
    setAnalysisId(id);
    if (openTab) setAnalysisTab(openTab);
    setView("analysis");
    window.scrollTo(0, 0);
  };

  const addShot = (id) => setShot((s) => s.some((x) => x.id === id) ? s : [{ id, status: "todo", ts: Date.now() }, ...s]);
  const cycleShot = (id) => setShot((s) => s.map((x) => x.id === id ? { ...x, status: SHELL_NEXT_STATUS[x.status] || "todo" } : x));
  const removeShot = (id) => setShot((s) => s.filter((x) => x.id !== id));
  const saveAngle = (a) => setAngles((g) => g.some((x) => x.id === a.id) ? g : [{ ...a, status: "approved", ts: Date.now() }, ...g]);
  const removeAngle = (id) => setAngles((g) => g.filter((x) => x.id !== id));

  const store = { shot, angles, analysisId, analysisTab, setAnalysisTab, addShot, cycleShot, removeShot, saveAngle, removeAngle, toast: showToast, goLibrary, goCreate, goDashboard, openAnalysis, setTab, setView };

  // Dashboard component was authored with a `go(payload)` API. Bridge it to store actions.
  const primaryComp = (window.STUDIO && window.STUDIO.primary_competitor_id) || "gruns";
  const go = (payload) => {
    if (!payload) return;
    const { name, id, tab: targetTab } = payload;
    if (name === "competitor" && id) { openAnalysis(id, targetTab); return; }
    if (name === "ads") { openAnalysis(primaryComp, "ads"); return; }
    if (name === "scripts") { openAnalysis(primaryComp, "scripts"); return; }
    if (name === "hooks") { openAnalysis(primaryComp, "hooks"); return; }
    if (name === "best") { openAnalysis(primaryComp, "best"); return; }
    if (name === "gaps" || name === "patterns") { openAnalysis(primaryComp, "patterns"); return; }
    if (name === "competitors") { goDashboard(); return; }
    if (name === "library") { goLibrary(); return; }
    if (name === "create") { goCreate(); return; }
  };

  const next = () => { const n = Math.min(step + 1, 4); setStep(n); setMaxStep((m) => Math.max(m, n)); window.scrollTo(0, 0); };
  const back = () => { setStep((s) => Math.max(0, s - 1)); window.scrollTo(0, 0); };
  const goStep = (n) => { if (n <= maxStep) { setStep(n); window.scrollTo(0, 0); } };

  return (
    <div className="app2">
      <div className="topnav">
        <div className="tn-brand" onClick={() => goDashboard()} title="SuperMush — Dashboard" style={{ cursor: "pointer" }}>
          <span style={{ fontFamily: '"Bagel Fat One", system-ui, sans-serif', fontSize: 28, color: "var(--ink)", letterSpacing: "0.01em", lineHeight: 1 }}>SuperMush</span>
        </div>
        <div className="tn-mid">
          {view === "create" && (
            <div className="wiz-prog">
              <span className="wiz-prog-label">{String(step + 1).padStart(2, "0")} / 05 · {WIZ_STEP_LABELS[step]}</span>
              <div className="wiz-segs">
                {WIZ_STEP_LABELS.map((_, i) => <div key={i} className={`wiz-seg ${i <= step ? "on" : ""}`} onClick={() => goStep(i)} title={WIZ_STEP_LABELS[i]}/>)}
              </div>
            </div>
          )}
        </div>
        <div className="tn-nav">
          <button className={`tn-link ${view === "dashboard" || view === "analysis" ? "on" : ""}`} onClick={goDashboard}><Icon name="dashboard" size={15}/> Dashboard</button>
          <button className={`tn-link ${view === "videos" ? "on" : ""}`} onClick={() => { setView("videos"); window.scrollTo(0, 0); }}><Icon name="video" size={15}/> Videos</button>
          <button className={`tn-link ${view === "library" ? "on" : ""}`} onClick={() => goLibrary()}>
            <Icon name="grid" size={15}/> Library{shot.length > 0 && <span className="tn-count">{shot.length}</span>}
          </button>
          <button className={`tn-link ${view === "brand" ? "on" : ""}`} onClick={() => { setView("brand"); window.scrollTo(0, 0); }}><Icon name="sparkle" size={15}/> Brand Kit</button>
        </div>
      </div>

      {view === "dashboard" && <Dashboard store={store} go={go}/>}
      {view === "analysis" && <AnalysisPage store={store} go={go}/>}
      {view === "videos" && <VideosPage store={store}/>}
      {view === "brand" && <BrandKitPage store={store}/>}
      {view === "create" && <Wizard step={step} next={next} back={back} store={store}/>}
      {view === "library" && <Library store={store} tab={tab} setTab={setTab}/>}

      {toast && (
        <div className="toast">
          <span className="tt-msg"><Icon name="check" size={16} stroke={2.6}/> {toast.msg}</span>
          {toast.action && <button className="tt-action" onClick={() => { toast.action.fn(); setToast(null); }}>{toast.action.label}</button>}
        </div>
      )}

    </div>
  );
}

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