// Microsoft login page — drives the device-code flow via the intake API and polls /whoami.
const { useState, useRef, useEffect } = React;

function LoginPage({ onSignIn }) {
  const [phase, setPhase] = useState("idle"); // idle | starting | waiting | error
  const [code, setCode] = useState(null);     // { userCode, verificationUri, message }
  const [error, setError] = useState(null);
  const timerRef = useRef(null); // the /whoami poll interval, so we can clear it on unmount

  // Clear the poll interval if this component unmounts before approval lands —
  // otherwise a leaked interval keeps firing cross-origin /whoami fetches forever.
  useEffect(() => () => { if (timerRef.current) clearInterval(timerRef.current); }, []);

  async function begin() {
    setPhase("starting"); setError(null);
    try {
      const c = await window.Api.startLogin();
      setCode(c); setPhase("waiting");
      // poll /whoami until the server-side session appears; swallow transient
      // errors (network blips) so the interval keeps retrying instead of spewing
      // unhandled rejections.
      const timer = setInterval(async () => {
        try {
          const { identity } = await window.Api.whoami();
          if (identity) { clearInterval(timer); timerRef.current = null; onSignIn(identity); }
        } catch { /* transient — retry on the next tick */ }
      }, 2500);
      timerRef.current = timer;
    } catch (e) {
      setError(String(e.message || e)); setPhase("error");
    }
  }

  return (
    <div className="min-h-[70vh] flex items-center justify-center">
      <div className="max-w-md w-full rounded-2xl border border-neutral-200 p-8 text-center shadow-sm">
        <h1 className="text-xl font-semibold mb-2">Fellow Assembly Line</h1>
        <p className="text-neutral-500 mb-6">Sign in with your Fellow Microsoft account to continue.</p>
        {phase === "idle" && (
          <button onClick={begin} className="px-5 py-2.5 rounded-lg bg-[#2F2F2F] text-white font-medium hover:bg-black">
            Sign in with Microsoft
          </button>
        )}
        {phase === "starting" && <p className="text-neutral-500">Starting…</p>}
        {phase === "waiting" && code && (
          <div className="text-left space-y-3">
            <p>1. Open <a className="text-blue-600 underline" href={code.verificationUri} target="_blank" rel="noreferrer">{code.verificationUri}</a></p>
            <p>2. Enter the code: <span className="font-mono text-lg font-semibold">{code.userCode}</span></p>
            <p>3. Approve with your fellow.dk account.</p>
            <p className="text-neutral-400 text-sm">Waiting for approval… this page updates automatically.</p>
          </div>
        )}
        {phase === "error" && <p className="text-red-600">Sign-in failed: {error}</p>}
      </div>
    </div>
  );
}

window.LoginPage = LoginPage;
