/* Medina Fight Lab — account gate. Routes to coach console or athlete app, or onboarding. */
const { Button: AButton, Input: AInput } = window.MedinaFightLabDesignSystem_ed6365;

function Welcome({ onCoach, onAthlete }) {
  const { MFLIcons } = window;
  const [mode, setMode] = React.useState(null); // null | "athlete" | "coach"
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");

  // athlete
  const [code, setCode] = React.useState("");
  // coach
  const [needsSetup, setNeedsSetup] = React.useState(null);
  const [cname, setCname] = React.useState("Coach Medina");
  const [pass, setPass] = React.useState("");

  const openCoach = async () => {
    setMode("coach"); setError(""); setBusy(true);
    try { const s = await window.MFLApi.status(); setNeedsSetup(!s.setup); if (s.coachName) setCname(s.coachName); }
    catch (e) { setNeedsSetup(false); setError("Can't reach server. Check connection."); }
    setBusy(false);
  };

  const joinAthlete = async () => {
    setError(""); setBusy(true);
    try {
      const r = await window.MFLApi.join(code.trim().toUpperCase());
      window.MFLApi.setAthleteToken(r.token);
      onAthlete();
    } catch (e) { setError(e.message || "Couldn't join."); }
    setBusy(false);
  };

  const doCoach = async () => {
    setError(""); setBusy(true);
    try {
      const r = needsSetup
        ? await window.MFLApi.setup(cname.trim(), pass.trim())
        : await window.MFLApi.coachLogin(pass.trim());
      window.MFLApi.setCoachToken(r.token);
      onCoach();
    } catch (e) { setError(e.message || "Sign-in failed."); }
    setBusy(false);
  };

  return (
    <div className="wl">
      <div className="wl__brand">
        <img src="icons/icon-192.png" alt="Medina Fight Lab" />
        <div className="wl__word">Medina<br />Fight Lab</div>
        <div className="wl__tag">Science-based S&amp;C for combat athletes</div>
      </div>

      {!mode ? (
        <div className="wl__choose">
          <button className="wl__role" onClick={onAthleteStart()}>
            <span className="wl__role-ic">{MFLIcons.zap({ width: 22, height: 22 })}</span>
            <span className="wl__role-t">I'm an athlete</span>
            <span className="wl__role-s">Enter your join code</span>
          </button>
          <button className="wl__role wl__role--coach" onClick={openCoach}>
            <span className="wl__role-ic">{MFLIcons.settings({ width: 22, height: 22 })}</span>
            <span className="wl__role-t">I'm the coach</span>
            <span className="wl__role-s">Build &amp; assign sessions</span>
          </button>
        </div>
      ) : mode === "athlete" ? (
        <div className="wl__form">
          <AInput label="Join code" value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} placeholder="e.g. S5K6V3" maxLength={6} />
          {error ? <div className="wl__err">{error}</div> : null}
          <AButton variant="stamp" size="lg" fullWidth disabled={busy || code.trim().length < 4} onClick={joinAthlete}>
            {busy ? "Linking…" : "Enter the lab"}
          </AButton>
          <button className="wl__back" onClick={() => { setMode(null); setError(""); }}>← Back</button>
        </div>
      ) : (
        <div className="wl__form">
          {busy && needsSetup === null ? <div className="wl__muted">Connecting…</div> : (
            <React.Fragment>
              {needsSetup ? <AInput label="Your name" value={cname} onChange={(e) => setCname(e.target.value)} /> : null}
              <AInput label={needsSetup ? "Create a passphrase" : "Passphrase"} type="password" value={pass} onChange={(e) => setPass(e.target.value)} placeholder={needsSetup ? "min 4 characters" : ""} />
              {error ? <div className="wl__err">{error}</div> : null}
              <AButton variant="stamp" size="lg" fullWidth disabled={busy || pass.trim().length < 4} onClick={doCoach}>
                {busy ? "…" : needsSetup ? "Create coach account" : "Sign in"}
              </AButton>
              <button className="wl__back" onClick={() => { setMode(null); setError(""); setPass(""); }}>← Back</button>
            </React.Fragment>
          )}
        </div>
      )}
    </div>
  );

  function onAthleteStart() { return () => { setMode("athlete"); setError(""); }; }
}

function Root() {
  const initial = window.MFLApi.athleteToken() ? "athlete" : window.MFLApi.coachToken() ? "coach" : "welcome";
  const [view, setView] = React.useState(initial);

  const signOut = () => { window.MFLApi.signOut(); setView("welcome"); };

  if (view === "athlete") return <AthleteApp onSignOut={signOut} />;
  if (view === "coach") return <CoachConsole onSignOut={signOut} />;
  return (
    <div className="aa-app">
      <Welcome onCoach={() => setView("coach")} onAthlete={() => setView("athlete")} />
    </div>
  );
}

Object.assign(window, { Root, Welcome });
