/* ============================================================
   PainTrack App — root shell & routing
   ============================================================ */

function Root() {
  const [session, setSession] = useState(null); // null | 'patient' | 'clinician'

  useEffect(() => {
    const h = (location.hash || "").replace("#", "");
    if (h === "patient" || h === "clinician") setSession(h);
    // paint probe: enable transform animations only where transitions advance
    const probe = document.createElement("div");
    probe.style.cssText = "position:fixed;left:-9999px;top:0;width:2px;height:2px;opacity:0;transition:opacity .05s linear;pointer-events:none;";
    document.body.appendChild(probe);
    void probe.offsetWidth;
    probe.style.opacity = "1";
    const t = setTimeout(() => {
      const v = parseFloat(getComputedStyle(probe).opacity) || 0;
      if (probe.parentNode) probe.parentNode.removeChild(probe);
      if (v > 0.05) document.documentElement.classList.add("anim-ok");
    }, 100);
    return () => clearTimeout(t);
  }, []);

  function login(role) { setSession(role); try { location.hash = role; } catch (e) {} }
  function logout() { setSession(null); try { location.hash = ""; } catch (e) {} }
  function switchTo(role) { setSession(role); try { location.hash = role; } catch (e) {} }

  if (!session) return <Login onLogin={login} />;

  return (
    <>
      {session === "patient"
        ? <div className="stage stage--patient"><PatientApp user={PATIENTS[0]} onLogout={logout} /></div>
        : <ClinicianApp onLogout={logout} />}
      <DemoSwitch role={session} onSwitch={switchTo} onLogout={logout} />
    </>
  );
}

function DemoSwitch({ role, onSwitch, onLogout }) {
  const [open, setOpen] = useState(false);
  return (
    <div className={"demo-switch" + (open ? " open" : "")}>
      {open && (
        <div className="demo-switch__menu">
          <p className="demo-switch__label">Demo · view as</p>
          <button className={role === "patient" ? "on" : ""} onClick={() => onSwitch("patient")}><Icon name="user" size={16} /> Patient app</button>
          <button className={role === "clinician" ? "on" : ""} onClick={() => onSwitch("clinician")}><Icon name="pulse" size={16} /> Clinician dashboard</button>
          <button onClick={onLogout}><Icon name="logout" size={16} /> Sign out</button>
        </div>
      )}
      <button className="demo-switch__fab" onClick={() => setOpen(o => !o)} aria-label="Demo controls">
        <Icon name={open ? "arrowR" : "sparkle"} size={18} />
        <span>{role === "patient" ? "Patient" : "Clinician"}</span>
      </button>
    </div>
  );
}

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