/* Pipeline — app shell: sidebar, routing, state store, toasts */
const { useState: useAS, useEffect: useAE } = React;

const NAV_OVERVIEW = [
  { key: "gallery", label: "Dashboard", icon: "gallery" },
  { key: "bible", label: "Breakdown", icon: "bible" },
  { key: "mywork", label: "My Work", icon: "mywork" },
  { key: "review", label: "Review", icon: "review" }
];
const NAV_ENTITIES = [
  { key: "shots", label: "Shots", icon: "shots", entity: "shots" },
  { key: "chars", label: "Characters", icon: "chars", entity: "chars" },
  { key: "env", label: "Locations", icon: "env", entity: "env" },
  { key: "assets", label: "Assets", icon: "assets", entity: "assets" }
];
const NAV_MANAGE = [
  { key: "library", label: "Library", icon: "library" },
  { key: "sync", label: "Sync", icon: "sync" },
  { key: "members", label: "Members", icon: "members" }
];

function clone(x) { return JSON.parse(JSON.stringify(x)); }

function CLApp() {
  const C = window.CL;
  const embed = new URLSearchParams(location.search).get("embed") === "1";
  const hash = (location.hash || "").replace("#", "") || "shots";

  const [view, setView] = useAS(hash);
  const [openShotLabel, setOpenShotLabel] = useAS(null);
  const [expanded, setExpanded] = useAS({ shots: true });
  const [shots, setShots] = useAS(clone(C.shots));
  const [submissions, setSubmissions] = useAS([
    { id: "s1", shot: "SH040", title: "Krishna at the threshold", by: "u_rp", take: "B", thumb: "v1", alternates: 2, note: "Preferred take — wider framing matches the offline. Two alternates attached." },
    { id: "s2", shot: "SH050", title: "Two-shot — across the fire", by: "u_jh", take: "A", thumb: "v2", alternates: 3, note: "Hero two-shot. Distortion check passed at the edges — no Unreal fallback needed." }
  ]);
  const [decisions, setDecisions] = useAS([]);
  const [syncPhase, setSyncPhase] = useAS("idle");
  const [toasts, setToasts] = useAS([]);

  useAE(() => {
    function onHash() {
      const k = (location.hash || "").replace("#", "");
      if (k.indexOf("shot/") === 0) { setOpenShotLabel(k.slice(5)); }
      else if (k) { setView(k); setOpenShotLabel(null); }
    }
    window.addEventListener("hashchange", onHash); return () => window.removeEventListener("hashchange", onHash);
  }, []);

  function toast(text, warn) {
    const id = Math.random();
    setToasts((t) => [...t, { id, text, warn }]);
    setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 2500);
  }
  function setShot(label, p) { setShots((arr) => arr.map((s) => s.label === label ? { ...s, ...p } : s)); }

  const actions = {
    go: (v) => { setView(v); setOpenShotLabel(null); history.replaceState(null, "", "#" + v); },
    openShot: (label) => { setOpenShotLabel(label); history.replaceState(null, "", "#shot/" + label); },
    backToShots: () => { setOpenShotLabel(null); setView("shots"); history.replaceState(null, "", "#shots"); },
    openEntity: (kind) => { const m = { char: "chars", env: "env", asset: "assets" }; setOpenShotLabel(null); setView(m[kind] || "chars"); },
    toast,
    assign: (label, who) => { setShot(label, { assignee: who }); toast(who ? "Assigned to " + window.memberById(who).name.split(" ")[0] : "Unassigned"); },
    approveSub: (sub) => {
      setShot(sub.shot, { status: "approved" });
      setSubmissions((s) => s.filter((x) => x.id !== sub.id));
      setDecisions((d) => [...d, { to: sub.by, kind: "approved", shot: sub.shot, text: "Locked. Take " + sub.take + " becomes the still reference for video generation." }]);
      toast("Approved " + sub.shot);
    },
    requestChanges: (sub, text) => {
      setShot(sub.shot, { status: "changes" });
      setSubmissions((s) => s.filter((x) => x.id !== sub.id));
      setDecisions((d) => [...d, { to: sub.by, kind: "change", shot: sub.shot, text: text || "Please revise per the locked palette and re-submit." }]);
      toast("Change note sent", true);
    },
    dismissSub: (id) => { setSubmissions((s) => s.filter((x) => x.id !== id)); toast("Submission dismissed", true); },
    runSync: () => { setSyncPhase("running"); setTimeout(() => { setSyncPhase("done"); toast("Sync complete — files structured & named"); }, 2000); }
  };

  const state = { ...C, view, openShotLabel, shots, submissions, decisions, syncPhase, current: C.current };

  function navItem(n) {
    const isEntity = !!n.entity;
    const on = view === n.key && !openShotLabel;
    const ct = n.entity === "shots" ? shots.length : n.entity === "chars" ? C.chars.length : n.entity === "env" ? C.envs.length : n.entity === "assets" ? C.assets.length : null;
    return (
      <div key={n.key}>
        <div className={"cl-navi" + (on ? " on" : "") + (isEntity && expanded[n.key] ? " exp" : "")}
          onClick={() => { if (isEntity) setExpanded((e) => ({ ...e, [n.key]: !e[n.key] })); actions.go(n.key); }}>
          {isEntity && <window.CIcon name="chev" size={12} className="chev" />}
          <span className="ic"><window.CIcon name={n.icon} size={16} /></span>
          {n.label}
          {n.key === "review" && submissions.length > 0 ? <span className="badge">{submissions.length}</span>
            : n.key === "mywork" ? <span className="badge">{shots.filter((s) => s.assignee === C.current && (s.status === "changes" || s.status === "notstarted" || s.status === "inprogress")).length}</span>
              : ct != null ? <span className="ct">{ct}</span> : null}
        </div>
        {isEntity && expanded[n.key] && n.entity === "shots" && (
          <div className="cl-subnav">
            {shots.slice(0, 8).map((s) => (
              <div key={s.label} className={"cl-subi" + (openShotLabel === s.label ? " on" : "")} onClick={() => actions.openShot(s.label)}>
                <span className="dot" /> {s.label}
              </div>
            ))}
            <div className="cl-subi" onClick={() => actions.go("shots")}><span className="more">+ {shots.length - 8} more</span></div>
          </div>
        )}
        {isEntity && expanded[n.key] && n.entity !== "shots" && (
          <div className="cl-subnav">
            {(n.entity === "chars" ? C.chars : n.entity === "env" ? C.envs : C.assets).map((e) => (
              <div key={e.id} className="cl-subi" onClick={() => actions.go(n.key)}><span className="dot" /> {e.name}</div>
            ))}
          </div>
        )}
      </div>
    );
  }

  let Body;
  if (openShotLabel) Body = <window.ShotDetail state={state} actions={actions} />;
  else if (view === "shots") Body = <window.ShotsView state={state} actions={actions} />;
  else if (view === "bible") Body = <window.BibleView state={state} actions={actions} />;
  else if (view === "mywork") Body = <window.MyWorkView state={state} actions={actions} />;
  else if (view === "review") Body = <window.ReviewView state={state} actions={actions} />;
  else if (view === "gallery") Body = <window.TeamView state={state} actions={actions} />;
  else if (view === "builder") Body = <window.BuilderView state={state} actions={actions} />;
  else if (view === "chars") Body = <window.EntityView kind="chars" state={state} actions={actions} />;
  else if (view === "env") Body = <window.EntityView kind="env" state={state} actions={actions} />;
  else if (view === "assets") Body = <window.EntityView kind="assets" state={state} actions={actions} />;
  else if (view === "rnd") Body = <window.LibraryView state={state} actions={actions} />;
  else if (view === "library") Body = <window.LibraryView state={state} actions={actions} />;
  else if (view === "sync") Body = <window.SyncView state={state} actions={actions} />;
  else if (view === "members") Body = <window.MembersView state={state} actions={actions} />;
  else Body = <window.ShotsView state={state} actions={actions} />;

  // builder is full-height (no cl-pad wrapper scroll), handle specially
  const isBuilder = view === "builder" && !openShotLabel;

  return (
    <div className="cl-app">
      <aside className="cl-side">
        <div className="cl-side-top">
          <div className="cl-allproj"><window.CIcon name="back" size={11} /> All projects</div>
          <div className="cl-projname">{C.project.name}</div>
          <div className="cl-projrole">{C.project.role} · {C.project.prefix}</div>
        </div>
        <nav className="cl-nav">
          <div className="cl-navgrp">Overview</div>
          {NAV_OVERVIEW.map(navItem)}
          <div className="cl-navgrp">Entities</div>
          {NAV_ENTITIES.map(navItem)}
          <div className="cl-navgrp">Manage</div>
          {NAV_MANAGE.map(navItem)}
        </nav>
      </aside>

      <div className="cl-main">
        {embed && (
          <div className="cl-bnr"><span className="k">Live prototype</span><span>Dummy data — click anything: open a shot, generate, approve, browse the Bible.</span><a href={location.pathname} target="_blank" rel="noopener">Open fullscreen ↗</a></div>
        )}
        {isBuilder ? <div className="cl-body" style={{ overflow: "hidden" }}>{Body}</div> : <div className="cl-body">{Body}</div>}
      </div>

      <div className="cl-toasts">
        {toasts.map((t) => <div key={t.id} className={"cl-toast" + (t.warn ? " warn" : "")}><span className="dot" /> {t.text}</div>)}
      </div>
    </div>
  );
}

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