// App shell — role switcher (PM / Research), live data, auto-refresh every 5 min.
// Header design mirrors snapshot_pm_2026-05-04.html (4 logos, gap-8, no separator,
// "Updated <time>" pill driven by data.dataFetchedAt).
const { useState: useStateApp, useEffect: useEffectApp, useCallback: useCallbackApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "defaultRole": "pm"
}/*EDITMODE-END*/;

const REFRESH_MS = 5 * 60 * 1000; // match backend CACHE_TTL

function App() {
  const [data, setData]         = useStateApp(window.RO_DATA);
  const [syncing, setSyncing]   = useStateApp(false);
  const [role, setRole]         = useStateApp(TWEAK_DEFAULTS.defaultRole);
  const [tweaks, setTweak]      = window.useTweaks(TWEAK_DEFAULTS);
  const PMView         = window.PMView;
  const ResearcherView = window.ResearcherView;

  // Fetch fresh data from the backend
  const fetchData = useCallbackApp(async () => {
    setSyncing(true);
    try {
      const r = await fetch(window.__API_BASE__ + "/api/data");
      if (!r.ok) throw new Error("API " + r.status);
      const d = await r.json();
      window.RO_DATA = d;
      setData(d);
    } catch (e) {
      console.warn("Auto-refresh failed:", e);
    } finally {
      setSyncing(false);
    }
  }, []);

  useEffectApp(() => {
    const id = setInterval(fetchData, REFRESH_MS);
    return () => clearInterval(id);
  }, [fetchData]);

  // ── Render the "Updated <time>" pill text from data.dataFetchedAt ─────────
  const pillText = (() => {
    if (syncing) return "Syncing\u2026";
    if (!data.dataFetchedAt) return "Last sync \u2014";
    const d = new Date(data.dataFetchedAt);
    const now = new Date();
    const sameDay = d.toDateString() === now.toDateString();
    const time = d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
    return sameDay
      ? `Updated ${time}`
      : `Updated ${d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} \u00b7 ${time}`;
  })();

  return (
    <div className="min-h-screen" style={{background: PAPER, color: INK}}>
      <header className="sticky top-0 z-30 border-b backdrop-blur" style={{borderColor: RULE, background: "oklch(0.985 0.005 80 / 0.88)"}}>
        <div className="max-w-[1300px] mx-auto px-10 pt-6 pb-5">
          <div className="flex items-end justify-between">
            <div className="flex items-center gap-8">
              <img src="assets/logo-ro.png" alt="Rogers-O'Brien Construction"
                   style={{height: 48, width: "auto", display: "block"}}/>
              <img src="assets/logo-tamu-cosc.png" alt="Texas A&M University · Construction Science"
                   style={{height: 64, width: "auto", display: "block"}}/>
              <img src="assets/logo-acig.png" alt="ACIG"
                   style={{height: 48, width: "auto", display: "block"}}/>
              <img src="assets/logo-procore.png" alt="Procore"
                   style={{height: 30, width: "auto", display: "block"}}/>
            </div>
            <div className="flex items-center gap-3 shrink-0">
              <div className="text-right text-[12px] leading-tight" style={{color: SUBINK}}>
                <div>Week <span style={{color: INK, fontWeight: 500}}>{data.summary.weeksElapsed}</span></div>
                <div className="font-mono tabular-nums mt-0.5 text-[11px]">
                  {new Date().toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                </div>
              </div>
              <div className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-full text-[11.5px] whitespace-nowrap" style={{background: "oklch(0.96 0.04 145)", color: "oklch(0.4 0.10 145)"}}
                   title={data.dataFetchedAt ? new Date(data.dataFetchedAt).toString() : ""}>
                <span className="size-1.5 rounded-full bg-emerald-600" style={{animation: syncing ? "pulse 1s ease-in-out infinite" : "none"}}/>
                {pillText}
              </div>
            </div>
          </div>
          <div className="mt-5 flex items-end justify-between">
            <div>
              <div className="text-[22px] tracking-[-0.02em] font-semibold leading-none">Team Health Study</div>
              <div className="text-[11px] tracking-[0.2em] uppercase mt-2" style={{color: SUBINK}}>Study cycle &middot; 2026 – 2027</div>
            </div>
            <div className="inline-flex p-0.5 rounded-full" style={{background: "oklch(0.94 0.005 80)"}}>
              <button onClick={()=>setRole("pm")}
                className={"px-5 py-2 text-[13px] tracking-tight rounded-full transition " + (role==="pm" ? "bg-white shadow-sm" : "")}
                style={{color: role==="pm" ? INK : SUBINK}}>
                Project Operations
              </button>
              <button onClick={()=>setRole("researcher")}
                className={"px-5 py-2 text-[13px] tracking-tight rounded-full transition " + (role==="researcher" ? "bg-white shadow-sm" : "")}
                style={{color: role==="researcher" ? INK : SUBINK}}>
                Research &middot; TAMU
              </button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-[1300px] mx-auto px-8 py-8">
        {role === "pm"         && <PMView data={data}/>}
        {role === "researcher" && <ResearcherView data={data} onSelectTeam={()=>{}}/>}
      </main>

      <window.TweaksPanel title="Tweaks">
        <window.TweakSection title="Default role">
          <window.TweakRadio label="On load" value={tweaks.defaultRole}
            options={[{value:"pm",label:"Project Operations"},{value:"researcher",label:"Research · TAMU"}]}
            onChange={(v)=>setTweak("defaultRole",v)}/>
        </window.TweakSection>
      </window.TweaksPanel>
    </div>
  );
}

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