/* studio-app.jsx — top-level shell, auth gate, view router. */

(function () {
  const { loadState, saveState } = window.STUDIO_DATA;
  const { Icon } = window.STUDIO_ICONS;

  /* Demo build: there is no backend. Every call is answered in-browser by
     demo-mock.js, so nothing on this page ever touches the network. */
  function apiFetch(url, options = {}) {
    return window.STUDIO_DEMO.apiFetch(url, options);
  }

  function App() {
    const [state, setState] = React.useState(loadState);
    /* Demo build: no accounts. The workspace is open from the first frame and
       history lives in this browser. */
    const teacher = window.STUDIO_DEMO.teacher;
    const setTeacher = () => {};
    const serverReady = false;
    const [syncStatus] = React.useState(window.STUDIO_DEMO.SYNC_STATUS);
    const [view, setView] = React.useState("gallery");       // "gallery" | "decodable" | ...
    const [toast, setToast] = React.useState(null);
    const [tweaks, setTweaks] = React.useState(() => window.STUDIO_TWEAK_DEFAULTS);

    /* Listen for dev-panel tweak changes via postMessage (shared protocol) */
    React.useEffect(() => {
      function onMsg(e) {
        const d = e.data;
        if (d && d.type === "__edit_mode_set_keys" && d.edits) {
          setTweaks((prev) => ({ ...prev, ...d.edits }));
        }
      }
      window.addEventListener("message", onMsg);
      return () => window.removeEventListener("message", onMsg);
    }, []);

    /* Apply theme/motion to body */
    React.useEffect(() => {
      document.body.setAttribute("data-theme", tweaks.theme);
      document.body.setAttribute("data-motion", tweaks.motion < 3 ? "low" : "normal");
    }, [tweaks.theme, tweaks.motion]);

    /* Persist to this browser only. */
    React.useEffect(() => { saveState(state); }, [state]);

    function showToast(text) {
      setToast({ text, id: Date.now() });
      clearTimeout(window.__studioToastTimer);
      window.__studioToastTimer = setTimeout(() => setToast(null), 2200);
    }

    function setJobs(updater) {
      setState((prev) => {
        const next = typeof updater === "function" ? updater(prev.jobs) : updater;
        return { ...prev, jobs: Array.isArray(next) ? next : prev.jobs };
      });
    }

    /* ----- APP ----- */

    return (
      <>
        {tweaks.showScene && <window.StudioScene motion={tweaks.motion} showScene={tweaks.showScene} theme={tweaks.theme}/>}
        <div className="app">
          <div className="topbar">
            <div className="brand">
              <div className="brand-mark">{Icon.brand()}</div>
              <div>
                <h1>Passage Studio</h1>
                <div className="subline">
                  <span className="pin"/>
                  Decodable passages, built to a scope and sequence
                </div>
              </div>
            </div>

            <div className="toolbar">
              {view !== "gallery" && (
                <button className="tool-btn tb-back" onClick={() => setView("gallery")}>
                  {Icon.back()}Back to tools
                </button>
              )}
              <button className="tool-btn account-chip" disabled>
                {teacher.name}
              </button>
            </div>
          </div>

          <div className="sync-line">{syncStatus}</div>

          {view === "gallery" && (
            <window.StudioGallery onPick={(toolId) => setView(toolId)}/>
          )}
          {view === "decodable" && (
            <window.StudioDecodable
              apiFetch={apiFetch}
              teacher={teacher}
              tweaks={tweaks}
              showToast={showToast}
              jobs={state.jobs}
              setJobs={setJobs}
            />
          )}
        </div>

        {toast && (
          <div className="toast show">
            {Icon.sparkle()}
            <span>{toast.text}</span>
          </div>
        )}

        <window.StudioTweaks/>
      </>
    );
  }

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