/* global React, Btn, Eyebrow, Display, Field, Rule, Wordmark, AppHeader, FigureNum, qrcode */
const { useState: useStateSettings, useEffect: useEffectSettings, useRef: useRefSettings } = React;

function SettingsScreen({ theme, user, onClose, onLogout, onNav, onAdmin, onUserUpdate }) {
  return (
    <div>
      <AppHeader theme={theme} user={user} onLogout={onLogout} current="settings" onNav={onNav} onAdmin={onAdmin} />
      <main style={{ maxWidth: 720, margin: "0 auto", padding: "32px 40px 80px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 32 }}>
          <div>
            <Eyebrow theme={theme} style={{ color: theme.accent, marginBottom: 8 }}>── ACCOUNT</Eyebrow>
            <Display theme={theme} size={48}>Instellingen</Display>
          </div>
          <Btn theme={theme} variant="outline" size="sm" onClick={onClose}>← terug</Btn>
        </div>

        <section style={{ border: `1px solid ${theme.rule}`, padding: "24px 28px", marginBottom: 28 }}>
          <Eyebrow theme={theme} style={{ marginBottom: 16 }}>── PROFIEL</Eyebrow>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <div>
              <div style={{ fontFamily: theme.fonts.mono, fontSize: 10, color: theme.fgDim, letterSpacing: "0.1em", marginBottom: 4 }}>NAAM</div>
              <div style={{ fontFamily: theme.fonts.display, fontSize: 20 }}>{user.name}</div>
            </div>
            <div>
              <div style={{ fontFamily: theme.fonts.mono, fontSize: 10, color: theme.fgDim, letterSpacing: "0.1em", marginBottom: 4 }}>E-MAIL</div>
              <div style={{ fontFamily: theme.fonts.mono, fontSize: 14 }}>{user.email}</div>
            </div>
          </div>
        </section>

        <TierSection theme={theme} user={user} />

        <MfaSection theme={theme} user={user} onUserUpdate={onUserUpdate} />
      </main>
    </div>
  );
}

const TIER_META = {
  free:       { label: "Gratis",    color: null,      desc: "Tot 3 quizzes, max 10 spelers per sessie.", limits: { quizzes: 3, sessions: 10, questions: 60 } },
  party:      { label: "Party",     color: "#3b5bff", desc: "Onbeperkt quizzes, tot 25 spelers, quick-party mode.", limits: { quizzes: null, sessions: null, questions: null } },
  quizkrak:   { label: "Quizkrak",  color: "#ff3b6f", desc: "Alles van Party + CSV-export, media-vragen, team-modus.", limits: { quizzes: null, sessions: null, questions: null } },
  enterprise: { label: "Enterprise",color: "#0a0a0a", desc: "Op maat: SSO, eigen branding, onbeperkt alles.", limits: { quizzes: null, sessions: null, questions: null } },
};

function TierSection({ theme, user }) {
  const tier = user.tier || "free";
  const meta = TIER_META[tier] || TIER_META.free;
  const badgeColor = meta.color || theme.fgDim;
  const [usage, setUsage] = useStateSettings(null);

  useEffectSettings(() => {
    window.kwistApi.get("/api/auth/usage").then(setUsage).catch(() => {});
  }, []);

  const meters = [
    { label: "QUIZZES", used: usage?.quizzes ?? 0, limit: meta.limits.quizzes },
    { label: "VRAGEN", used: usage?.questions ?? 0, limit: meta.limits.questions },
    { label: "SESSIES", used: usage?.sessions ?? 0, limit: meta.limits.sessions },
  ];

  return (
    <section style={{ border: `1px solid ${theme.rule}`, padding: "24px 28px", marginBottom: 28 }}>
      <Eyebrow theme={theme} style={{ marginBottom: 16 }}>── LICENTIE</Eyebrow>
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 20 }}>
        <div style={{
          fontFamily: theme.fonts.display, fontWeight: 800, fontStyle: "italic",
          fontSize: 36, lineHeight: 1, letterSpacing: "-0.03em",
          textTransform: "lowercase", color: badgeColor,
        }}>{meta.label}</div>
        <span style={{
          fontFamily: theme.fonts.mono, fontSize: 10, letterSpacing: "0.12em",
          padding: "4px 12px",
          border: `1.5px solid ${badgeColor}`,
          background: badgeColor, color: "#fff",
          textTransform: "uppercase",
        }}>{tier === "free" ? "ACTIEF" : "ACTIEF ABONNEMENT"}</span>
      </div>
      <p style={{
        fontSize: 14, lineHeight: 1.55, color: theme.fgDim,
        margin: "0 0 20px",
      }}>{meta.desc}</p>

      {usage && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
          {meters.map((m) => {
            const pct = m.limit ? Math.min(100, Math.round((m.used / m.limit) * 100)) : null;
            const full = pct !== null && pct >= 100;
            return (
              <div key={m.label} style={{ padding: "16px", border: `1px solid ${theme.rule}`, background: theme.bg2 }}>
                <div style={{
                  fontFamily: theme.fonts.mono, fontSize: 10, letterSpacing: "0.12em",
                  color: theme.fgDim, marginBottom: 8,
                }}>{m.label}</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <span style={{
                    fontFamily: theme.fonts.display, fontWeight: 800, fontStyle: "italic",
                    fontSize: 32, lineHeight: 1, letterSpacing: "-0.03em",
                    color: full ? theme.accent : theme.fg,
                  }}>{m.used}</span>
                  {m.limit ? (
                    <span style={{ fontFamily: theme.fonts.mono, fontSize: 12, color: theme.fgDim }}>/ {m.limit}</span>
                  ) : (
                    <span style={{ fontFamily: theme.fonts.mono, fontSize: 10, color: theme.fgDim, letterSpacing: "0.1em" }}>ONBEPERKT</span>
                  )}
                </div>
                {m.limit && (
                  <div style={{
                    marginTop: 10, height: 6,
                    background: theme.rule, overflow: "hidden",
                  }}>
                    <div style={{
                      width: `${pct}%`, height: "100%",
                      background: full ? theme.accent : badgeColor || theme.fg,
                      transition: "width .3s",
                    }} />
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </section>
  );
}

function MfaSection({ theme, user, onUserUpdate }) {
  const [mfaEnabled, setMfaEnabled] = useStateSettings(!!user.mfaEnabled);
  const [setupData, setSetupData] = useStateSettings(null);
  const [verifyCode, setVerifyCode] = useStateSettings("");
  const [disablePassword, setDisablePassword] = useStateSettings("");
  const [disableCode, setDisableCode] = useStateSettings("");
  const [error, setError] = useStateSettings(null);
  const [success, setSuccess] = useStateSettings(null);
  const [busy, setBusy] = useStateSettings(false);
  const [showDisable, setShowDisable] = useStateSettings(false);
  const qrRef = useRefSettings(null);

  const startSetup = async () => {
    setError(null); setSuccess(null); setBusy(true);
    try {
      const res = await window.kwistApi.post("/api/auth/mfa/setup", {});
      if (res.error) { setError(res.error); return; }
      setSetupData(res);
    } catch (e) {
      setError(e.message);
    } finally {
      setBusy(false);
    }
  };

  useEffectSettings(() => {
    if (!setupData?.uri || !qrRef.current) return;
    try {
      const qr = qrcode(0, "M");
      qr.addData(setupData.uri);
      qr.make();
      qrRef.current.innerHTML = qr.createSvgTag({ cellSize: 4, margin: 4 });
    } catch { /* qrcode lib not loaded */ }
  }, [setupData]);

  const confirmMfa = async (e) => {
    e?.preventDefault();
    setError(null); setBusy(true);
    try {
      await window.kwistApi.post("/api/auth/mfa/confirm", { code: verifyCode });
      setMfaEnabled(true);
      setSetupData(null);
      setVerifyCode("");
      setSuccess("MFA is ingeschakeld.");
      onUserUpdate?.({ ...user, mfaEnabled: true });
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  const disableMfa = async (e) => {
    e?.preventDefault();
    setError(null); setBusy(true);
    try {
      await window.kwistApi.post("/api/auth/mfa/disable", { password: disablePassword, code: disableCode });
      setMfaEnabled(false);
      setShowDisable(false);
      setDisablePassword("");
      setDisableCode("");
      setSuccess("MFA is uitgeschakeld.");
      onUserUpdate?.({ ...user, mfaEnabled: false });
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <section style={{ border: `1px solid ${theme.rule}`, padding: "24px 28px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
        <Eyebrow theme={theme}>── TWEESTAPSVERIFICATIE (MFA)</Eyebrow>
        <span style={{
          fontFamily: theme.fonts.mono, fontSize: 11, letterSpacing: "0.1em",
          padding: "4px 12px",
          border: `1px solid ${mfaEnabled ? theme.accent : theme.rule}`,
          background: mfaEnabled ? theme.accent : "transparent",
          color: mfaEnabled ? "#fff" : theme.fgDim,
        }}>{mfaEnabled ? "INGESCHAKELD" : "UITGESCHAKELD"}</span>
      </div>

      <p style={{ fontSize: 14, lineHeight: 1.6, color: theme.fgDim, margin: "0 0 20px 0" }}>
        Bescherm je account met een extra verificatiestap via een authenticator-app (zoals Google Authenticator, Authy of 1Password).
      </p>

      {error && (
        <div style={{
          marginBottom: 16, padding: "8px 12px",
          border: `1px solid ${theme.accent}`, background: `${theme.accent}10`,
          color: theme.accent, fontFamily: theme.fonts.mono, fontSize: 12,
        }}>{error}</div>
      )}
      {success && (
        <div style={{
          marginBottom: 16, padding: "8px 12px",
          border: `1px solid ${theme.accent}`, background: `${theme.accent}10`,
          color: theme.accent, fontFamily: theme.fonts.mono, fontSize: 12,
        }}>{success}</div>
      )}

      {!mfaEnabled && !setupData && (
        <Btn theme={theme} onClick={startSetup} disabled={busy}>
          {busy ? "Bezig…" : "MFA inschakelen →"}
        </Btn>
      )}

      {setupData && (
        <div style={{ border: `1px dashed ${theme.rule}`, padding: "20px 24px" }}>
          <Eyebrow theme={theme} style={{ marginBottom: 12 }}>STAP 1 — SCAN DE QR-CODE</Eyebrow>
          <div ref={qrRef} style={{ background: "#fff", display: "inline-block", padding: 12, marginBottom: 16 }} />
          <div style={{ marginBottom: 16 }}>
            <Eyebrow theme={theme} style={{ marginBottom: 4 }}>OF VOER HANDMATIG IN:</Eyebrow>
            <code style={{
              fontFamily: theme.fonts.mono, fontSize: 13, letterSpacing: "0.15em",
              background: theme.bg2, padding: "6px 10px", display: "inline-block",
              wordBreak: "break-all", userSelect: "all",
            }}>{setupData.secret}</code>
          </div>
          <Rule theme={theme} dashed />
          <Eyebrow theme={theme} style={{ margin: "16px 0 12px" }}>STAP 2 — BEVESTIG MET EEN CODE</Eyebrow>
          <form onSubmit={confirmMfa} style={{ display: "flex", gap: 12, alignItems: "flex-end" }}>
            <div style={{ width: 180 }}>
              <Field theme={theme} label="Code uit app" value={verifyCode} onChange={setVerifyCode} placeholder="000 000" autoFocus />
            </div>
            <Btn theme={theme} type="submit" onClick={confirmMfa} disabled={busy || verifyCode.replace(/\s/g, "").length < 6}>
              {busy ? "Bezig…" : "Bevestigen"}
            </Btn>
            <Btn theme={theme} variant="ghost" onClick={() => { setSetupData(null); setVerifyCode(""); setError(null); }}>
              Annuleren
            </Btn>
          </form>
        </div>
      )}

      {mfaEnabled && !showDisable && (
        <Btn theme={theme} variant="outline" onClick={() => { setShowDisable(true); setError(null); setSuccess(null); }}>
          MFA uitschakelen
        </Btn>
      )}

      {showDisable && (
        <form onSubmit={disableMfa} style={{ border: `1px dashed ${theme.rule}`, padding: "20px 24px" }}>
          <Eyebrow theme={theme} style={{ marginBottom: 16 }}>── BEVESTIG UITSCHAKELING</Eyebrow>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
            <Field theme={theme} label="Wachtwoord" value={disablePassword} onChange={setDisablePassword} type="password" placeholder="••••••••" />
            <Field theme={theme} label="Code uit app" value={disableCode} onChange={setDisableCode} placeholder="000 000" />
          </div>
          <div style={{ display: "flex", gap: 12 }}>
            <Btn theme={theme} type="submit" onClick={disableMfa} disabled={busy}>
              {busy ? "Bezig…" : "Uitschakelen"}
            </Btn>
            <Btn theme={theme} variant="ghost" onClick={() => { setShowDisable(false); setError(null); }}>
              Annuleren
            </Btn>
          </div>
        </form>
      )}
    </section>
  );
}

window.SettingsScreen = SettingsScreen;
