/* global React, Btn, Field, Eyebrow, Display, Wordmark, Rule, FigureNum */
const { useState: useStateLogin } = React;

function LoginScreen({ theme, onLogin, initialMode = "login", portal = false }) {
  const registrationEnabled = theme.features?.["auth.registration"] !== false;
  const [mode, setMode] = useStateLogin(initialMode === "signup" && registrationEnabled ? "signup" : "login");
  const [email, setEmail] = useStateLogin("");
  const [password, setPassword] = useStateLogin("");
  const [name, setName] = useStateLogin("");
  const [error, setError] = useStateLogin(null);
  const [busy, setBusy] = useStateLogin(false);

  const [mfaStep, setMfaStep] = useStateLogin(false);
  const [mfaToken, setMfaToken] = useStateLogin(null);
  const [mfaCode, setMfaCode] = useStateLogin("");

  const submit = async (e) => {
    e?.preventDefault();
    if (busy) return;
    setError(null);
    setBusy(true);
    try {
      const api = window.kwistApi;
      const res = mode === "signup"
        ? await api.signup(email, password, name)
        : await api.login(email, password);

      if (res.mfaRequired) {
        setMfaToken(res.mfaToken);
        setMfaStep(true);
        return;
      }

      api.setToken(res.token);
      const u = res.user;
      onLogin({
        ...u,
        initials: (u.name || "").split(" ").map((s) => s[0]).slice(0, 2).join("").toUpperCase() || "??",
      });
    } catch (err) {
      setError(err.message || "Er ging iets mis.");
    } finally {
      setBusy(false);
    }
  };

  const submitMfa = async (e) => {
    e?.preventDefault();
    if (busy) return;
    setError(null);
    setBusy(true);
    try {
      const api = window.kwistApi;
      const res = await api.post("/api/auth/mfa/verify-login", { mfaToken, code: mfaCode });
      api.setToken(res.token);
      const u = res.user;
      onLogin({
        ...u,
        initials: (u.name || "").split(" ").map((s) => s[0]).slice(0, 2).join("").toUpperCase() || "??",
      });
    } catch (err) {
      setError(err.message || "Ongeldige code.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      minHeight: "100vh",
      display: "grid",
      gridTemplateColumns: "1fr 1fr",
      background: theme.bg,
    }}>
      {/* LEFT — editorial cover */}
      <div style={{
        background: theme.bg2,
        color: theme.fg,
        padding: "48px 56px",
        display: "flex",
        flexDirection: "column",
        justifyContent: "space-between",
        position: "relative",
        borderRight: `1px solid ${theme.rule}`,
      }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Wordmark size={260} />
          <Eyebrow theme={theme}>{portal ? "ENTERPRISE PORTAL" : (theme.siteText?.headerRight || "QUIZ PLATFORM")}</Eyebrow>
        </div>

        <div>
          <Eyebrow theme={theme} style={{ marginBottom: 24, color: theme.accent }}>
            ── <span style={{ textTransform: "none", letterSpacing: 0, fontFamily: theme.fonts.display, fontSize: 14 }}>{portal ? "Inloggen voor organisaties — leertrajecten, rapporten, certificaten" : (theme.siteText?.loginTagline || "Een platform voor iedereen die iets te vragen heeft")}</span>
          </Eyebrow>
          <Display theme={theme} size={92} style={{ maxWidth: 580 }}>
            {portal ? (
              <>Jouw<br/><span style={{ color: theme.accent }}>portal</span><br/>voor leren.</>
            ) : (
              <>De vraag,<br/><span style={{ color: theme.accent }}>opnieuw</span><br/>uitgevonden.</>
            )}
          </Display>
          <div style={{
            marginTop: 28,
            maxWidth: 460,
            fontSize: 16,
            lineHeight: 1.55,
            color: theme.fg,
            opacity: 0.85,
          }}>
            Maak in enkele klikken een quiz voor de vrijdagmiddagborrel, een teambuilding of een serieuze kennistoets. AI helpt waar het kan, jij beslist wat blijft. Spelers joinen op hun telefoon, jij volgt alles live op het grote scherm.
          </div>
        </div>

        <div>
          <Rule theme={theme} />
          <div style={{
            display: "flex",
            justifyContent: "space-between",
            paddingTop: 12,
            fontFamily: theme.fonts.mono,
            fontSize: 10,
            color: theme.fgDim,
            letterSpacing: "0.1em",
          }}>
            <span>{theme.siteText?.loginFooterLeft || "EST. MMXXIV — ANTWERPEN"}</span>
            <span>{theme.siteText?.loginFooterCenter || "— PAGINA 01 —"}</span>
            <span>{theme.siteText?.loginFooterRight || "VOORWOORD"}</span>
          </div>
        </div>
      </div>

      {/* RIGHT — form */}
      <div style={{
        padding: "48px 56px",
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        position: "relative",
      }}>
        {registrationEnabled && !mfaStep && (
          <div style={{
            position: "absolute", top: 32, right: 56,
            display: "flex", gap: 12, alignItems: "center",
          }}>
            <Eyebrow theme={theme}>{mode === "login" ? "Nieuw hier?" : "Al een account?"}</Eyebrow>
            <button onClick={() => { setMode(mode === "login" ? "signup" : "login"); setError(null); }} style={{
              background: "transparent",
              border: "none",
              fontFamily: theme.fonts.display,
              fontSize: 16,
              color: theme.accent,
              cursor: "pointer",
              textDecoration: "underline",
              textUnderlineOffset: 4,
            }}>{mode === "login" ? "Maak een account →" : "← Inloggen"}</button>
          </div>
        )}

        <div style={{ maxWidth: 420, width: "100%", margin: "0 auto" }}>
          {mfaStep ? (
            <>
              <Eyebrow theme={theme} style={{ color: theme.accent, marginBottom: 14 }}>
                ── Tweestapsverificatie
              </Eyebrow>
              <Display theme={theme} size={52} style={{ marginBottom: 12 }}>
                Voer je<br/><span style={{ color: theme.accent }}>code</span> in.
              </Display>
              <p style={{ fontSize: 15, lineHeight: 1.6, color: theme.fgDim, margin: "8px 0 36px 0", maxWidth: 360 }}>
                Open je authenticator-app en voer de 6-cijferige code in.
              </p>
              <form onSubmit={submitMfa} style={{ display: "flex", flexDirection: "column", gap: 22 }}>
                <Field theme={theme} label="Verificatiecode" value={mfaCode} onChange={setMfaCode}
                  placeholder="000 000" autoFocus />
                {error && (
                  <div style={{
                    padding: "8px 12px",
                    border: `1px solid ${theme.accent}`,
                    background: `${theme.accent}10`,
                    color: theme.accent,
                    fontFamily: theme.fonts.mono, fontSize: 12, letterSpacing: "0.05em",
                  }}>{error}</div>
                )}
                <Btn theme={theme} size="lg" type="submit" onClick={submitMfa} disabled={busy}
                  style={{ width: "100%", justifyContent: "center", opacity: busy ? 0.6 : 1 }}>
                  {busy ? "Bezig…" : "Verifiëren →"}
                </Btn>
                <button onClick={() => { setMfaStep(false); setMfaToken(null); setMfaCode(""); setError(null); }} style={{
                  background: "transparent", border: "none", color: theme.fgDim,
                  fontFamily: theme.fonts.display, fontSize: 14, cursor: "pointer",
                  textAlign: "center", textDecoration: "underline", textUnderlineOffset: 4,
                }}>← Terug naar inloggen</button>
              </form>
            </>
          ) : (
            <>
              <Eyebrow theme={theme} style={{ color: theme.accent, marginBottom: 14 }}>
                ── {mode === "login" ? "Inloggen" : "Aanmelden"}
              </Eyebrow>
              <Display theme={theme} size={64} style={{ marginBottom: 12 }}>
                {mode === "login" ? <>Welkom <span style={{ fontStyle: "normal", fontFamily: theme.fonts.body, fontWeight: 500, fontSize: 56 }}>terug.</span></> : <>Hoi.<br/>Wie ben jij?</>}
              </Display>
              <p style={{ fontSize: 15, lineHeight: 1.6, color: theme.fgDim, margin: "8px 0 36px 0", maxWidth: 360 }}>
                {mode === "login"
                  ? "Log in om je quizzes te bekijken, spelen of nieuwe te maken."
                  : "Maak een gratis account aan en begin direct met quizzen."}
              </p>

              <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 22 }}>
                {mode === "signup" && (
                  <Field theme={theme} label="Volledige naam" value={name} onChange={setName} placeholder="Bijv. Sanne van Dijk" />
                )}
                <Field theme={theme} label="E-mailadres" value={email} onChange={setEmail} placeholder="naam@domein.be" autoFocus />
                <Field theme={theme} label="Wachtwoord" value={password} onChange={setPassword} type="password" placeholder="••••••••"
                  hint={mode === "signup" ? "Minimaal 8 tekens." : undefined} />

                <div style={{ marginTop: 8 }}>
                  {error && (
                    <div style={{
                      marginBottom: 12,
                      padding: "8px 12px",
                      border: `1px solid ${theme.accent}`,
                      background: `${theme.accent}10`,
                      color: theme.accent,
                      fontFamily: theme.fonts.mono, fontSize: 12, letterSpacing: "0.05em",
                    }}>{error}</div>
                  )}
                  <Btn theme={theme} size="lg" type="submit" onClick={submit} disabled={busy} style={{ width: "100%", justifyContent: "center", opacity: busy ? 0.6 : 1 }}>
                    {busy ? "Bezig…" : (mode === "login" ? "Inloggen" : "Account maken")}
                    <span style={{ fontFamily: theme.fonts.display, marginLeft: 4 }}>→</span>
                  </Btn>
                </div>
              </form>

              <div style={{
                marginTop: 40,
                paddingTop: 16,
                borderTop: `1px dashed ${theme.rule}`,
                fontFamily: theme.fonts.mono,
                fontSize: 10,
                letterSpacing: "0.1em",
                color: theme.fgDim,
                textAlign: "center",
                textTransform: "uppercase",
              }}>
                {theme.siteText?.loginTerms || "Door verder te gaan accepteer je onze voorwaarden"}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
