// Root mount — tab nav between the live Assembly Line and the About page.

const { useState: useStateRoot, useEffect: useEffectRoot } = React;

const Root = () => {
  const [page, setPage] = useStateRoot("line"); // "line" | "about"
  const [signedInUser, setSignedInUser] = useStateRoot(null);
  const [authRequired, setAuthRequired] = useStateRoot(true);
  const [authLoading, setAuthLoading] = useStateRoot(true);
  const [demoRunner, setDemoRunner] = useStateRoot(false);
  const [demoRunning, setDemoRunning] = useStateRoot(false);
  const [settingsOpen, setSettingsOpen] = useStateRoot(false);
  // DEMO MOCK LOGIN (window.AL_MOCK_LOGIN): replace the Microsoft login with a
  // client-only mock for the presentation. When on, we ignore the server whoami
  // and gate purely on a localStorage session written by <window.MockLogin>.
  const MOCK_LOGIN = typeof window !== "undefined" && window.AL_MOCK_LOGIN === true;
  useEffectRoot(() => {
    if (MOCK_LOGIN) {
      const id = typeof window.readMockAuth === "function" ? window.readMockAuth() : null;
      setSignedInUser(id);
      setAuthRequired(true); // always require the mock sign-in until the localStorage session exists
      setAuthLoading(false);
      return;
    }
    window.Api.whoami()
      .then(({ identity, authRequired }) => { setSignedInUser(identity); setAuthRequired(authRequired); })
      .finally(() => setAuthLoading(false));
  }, []);

  // After the mock login, land on the concept page — the post-login "index".
  // Its "Go to demo" buttons link to /demo (this SPA's line view). Only redirect
  // at the root path; /demo must keep showing the line directly.
  const atConceptRoot = typeof window !== "undefined" &&
    (window.location.pathname === "/" || window.location.pathname === "/index.html");
  const redirectingToConcept = MOCK_LOGIN && !!signedInUser && atConceptRoot;
  useEffectRoot(() => {
    if (MOCK_LOGIN && signedInUser && atConceptRoot) {
      window.location.replace("/sales/brief-to-done.html");
    }
  }, [signedInUser]);

  // Read-only (snapshot) mode is decided inside AssemblyLineLive, a sibling
  // tree. It broadcasts via window.AL_READONLY + an 'al-readonly-mode' event;
  // we mirror it here so the header "Inject Task" button can hide in the
  // read-only viewer. Seed from the flag in case the event already fired.
  const [readOnly, setReadOnly] = useStateRoot(() =>
    typeof window !== "undefined" && window.AL_READONLY === true);
  useEffectRoot(() => {
    const onMode = (e) => setReadOnly(e.detail?.readOnly === true);
    window.addEventListener("al-readonly-mode", onMode);
    // Defensive: catches the narrow render→effect gap where the event could
    // fire after the lazy initializer ran but before the listener attached.
    if (window.AL_READONLY === true) setReadOnly(true);
    return () => window.removeEventListener("al-readonly-mode", onMode);
  }, []);

  // Demo runner: poll capability + running state; Run/Reset drive run-demo.ts.
  useEffectRoot(() => {
    let stop = false;
    const tick = () => fetch("/demo/info").then((r) => r.json())
      .then((d) => { if (!stop) { setDemoRunner(!!d.runner); setDemoRunning(!!d.running); } })
      .catch(() => {});
    tick();
    const iv = setInterval(tick, 4000);
    return () => { stop = true; clearInterval(iv); };
  }, []);
  const runDemo = () => { setDemoRunning(true); fetch("/demo/run", { method: "POST" }).then((r) => r.json()).then((d) => setDemoRunning(!!d.running)).catch(() => {}); };
  const resetDemo = () => { setDemoRunning(false); fetch("/demo/reset", { method: "POST" }).catch(() => {}); };

  const TabBtn = ({ id, children }) => {
    const active = page === id;
    return (
      <button
        onClick={() => setPage(id)}
        className={`relative px-4 py-2 text-sm font-bold rounded-lg transition-colors ${
          active
            ? "bg-neutral-900 text-white shadow-sm"
            : "text-neutral-600 hover:text-neutral-900 hover:bg-neutral-100"
        }`}
      >
        {children}
      </button>
    );
  };

  return (
    <div className="min-h-screen bg-neutral-50 font-sans text-neutral-900">
      {/* Top brand bar */}
      <header className="bg-white border-b border-neutral-200 px-8 py-5 flex items-center justify-between sticky top-0 z-50">
        <div className="flex items-center gap-3">
          <div className="bg-neutral-900 p-2 rounded-lg text-white shadow-inner">
            {/* Fellow box on a conveyor belt */}
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
              <rect x="6.5" y="3" width="11" height="12" rx="1.4" />
              <g transform="translate(9.2 4.6) scale(0.04)" fill="currentColor" stroke="none">
                <path d="M138.12 0V55.41L0 122.09V66.68L138.12 0Z" />
                <path d="M138.12 80.3604V135.8L58.36 174.28V231.41L0 203.25V147.07L138.12 80.3604Z" />
              </g>
              <line x1="2" y1="18.5" x2="22" y2="18.5" />
              <circle cx="6" cy="21" r="1.4" />
              <circle cx="12" cy="21" r="1.4" />
              <circle cx="18" cy="21" r="1.4" />
            </svg>
          </div>
          <div>
            <h1 className="text-xl font-bold tracking-tight leading-none text-neutral-800">Fellow Assembly Line</h1>
            <p className="text-sm font-medium text-neutral-500 mt-1">Task routing &amp; refinement protocol</p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          {signedInUser && <span className="text-sm text-neutral-500">Signed in as {signedInUser.username}</span>}
          {signedInUser && !MOCK_LOGIN && (
            <button
              onClick={() => setSettingsOpen(true)}
              className="flex items-center gap-1.5 text-sm text-neutral-500 hover:text-neutral-900 hover:bg-neutral-100 px-3 py-2 rounded-lg transition-colors"
              title="Notification settings"
            >
              ⚙️ Settings
            </button>
          )}
          {page === "line" && !readOnly && (
            <button
              onClick={() => window.dispatchEvent(new CustomEvent("assembly-line:inject-task"))}
              className="flex items-center gap-2 bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg font-semibold text-sm transition-colors shadow-md shadow-indigo-600/20 active:scale-95"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
                <line x1="12" y1="5" x2="12" y2="19" />
                <line x1="5" y1="12" x2="19" y2="12" />
              </svg>
              Inject Task
            </button>
          )}
          {demoRunner && page === "line" && (
            <div className="flex items-center gap-2">
              <button
                onClick={runDemo}
                disabled={demoRunning}
                className={`flex items-center gap-2 px-4 py-2 rounded-lg font-semibold text-sm transition-colors shadow-md active:scale-95 ${demoRunning ? "bg-emerald-100 text-emerald-700 cursor-default shadow-none" : "bg-emerald-600 hover:bg-emerald-700 text-white shadow-emerald-600/20"}`}
                title="Start the demo — tasks cascade down the line"
              >
                {demoRunning
                  ? (<><span className="relative flex w-2 h-2"><span className="absolute inline-flex h-full w-full rounded-full bg-emerald-500 opacity-75 animate-ping" /><span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500" /></span> Running…</>)
                  : (<><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden><path d="M8 5v14l11-7z" /></svg> Run demo</>)}
              </button>
              <button
                onClick={resetDemo}
                className="flex items-center gap-2 bg-white border border-neutral-300 hover:bg-neutral-100 text-neutral-700 px-3 py-2 rounded-lg font-semibold text-sm transition-colors active:scale-95"
                title="Reset — all tasks back to the start"
              >
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden><path d="M3 12a9 9 0 1 0 3-6.7L3 8" /><path d="M3 3v5h5" /></svg>
                Reset
              </button>
            </div>
          )}
          <nav className="flex items-center gap-1 bg-neutral-50 border border-neutral-200 rounded-xl p-1">
            <TabBtn id="line">Assembly Line</TabBtn>
            <TabBtn id="about">About</TabBtn>
          </nav>
        </div>
      </header>

      {authLoading && <div className="p-10 text-center text-neutral-400">Loading…</div>}
      {!authLoading && authRequired && !signedInUser && (
        MOCK_LOGIN
          ? <window.MockLogin onSignIn={setSignedInUser} />
          : <window.LoginPage onSignIn={setSignedInUser} />
      )}
      {redirectingToConcept && <div className="p-10 text-center text-neutral-400">Loading…</div>}
      {!authLoading && !redirectingToConcept && (!authRequired || signedInUser) && page === "line" && <AssemblyLineApp />}
      {!authLoading && !redirectingToConcept && (!authRequired || signedInUser) && page === "about" && <AboutPage onGoToLine={() => setPage("line")} />}
      {settingsOpen && <window.SettingsPanel onClose={() => setSettingsOpen(false)} />}
    </div>
  );
};

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