(function(){
const { useState } = React;

function LoginScreen({ onLogin }) {
  const [mode, setMode] = useState("login"); // "login" | "register"
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [password2, setPassword2] = useState("");
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState(null);

  function switchMode(m) {
    setMode(m); setErr(null); setPassword(""); setPassword2(""); setEmail("");
  }

  async function handleSubmit(e) {
    e.preventDefault();
    if (!username.trim() || !password) { setErr(window.t("auth.fillAllFields")); return; }
    if (mode === "register") {
      if (password !== password2) { setErr(window.t("auth.passwordMismatch")); return; }
      if (password.length < 4) { setErr(window.t("auth.passwordMinLength")); return; }
    }
    setLoading(true); setErr(null);
    try {
      const endpoint = mode === "login" ? "/api/login" : "/api/register";
      const r = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username: username.trim().toLowerCase(), password,
          ...(mode === "register" && email.trim() ? { email: email.trim() } : {}) })
      });
      const data = await r.json();
      if (!r.ok) {
        setErr(data.error || (mode === "login" ? window.t("auth.loginFailed") : window.t("auth.registerFailed")));
        return;
      }
      onLogin(data.token, data.username);
    } catch {
      setErr(window.t("auth.connectionError"));
    } finally {
      setLoading(false);
    }
  }

  const inputStyle = {
    width: "100%", boxSizing: "border-box", fontSize: 14,
    padding: "10px 12px", borderRadius: 8,
    border: "1px solid var(--col-border)",
    background: "var(--col-bg)", color: "var(--col-text)",
    fontFamily: "var(--sans)", outline: "none"
  };
  const labelStyle = {
    display: "block", fontSize: 10, color: "var(--col-text-sec)",
    letterSpacing: "0.08em", textTransform: "uppercase", marginBottom: 6,
    fontFamily: "var(--mono)"
  };

  return (
    <div style={{
      minHeight: "100vh", background: "var(--col-bg)",
      display: "flex", flexDirection: "column",
      alignItems: "center", justifyContent: "center", padding: "24px"
    }}>
      {/* Logo */}
      <div style={{ marginBottom: 36, textAlign: "center" }}>
        <div style={{
          width: 52, height: 52, borderRadius: 13,
          background: "var(--col-accent)", display: "inline-flex",
          alignItems: "center", justifyContent: "center",
          color: "var(--col-bg)", fontFamily: "var(--serif)",
          fontSize: 26, fontStyle: "italic", fontWeight: 600, marginBottom: 14
        }}>P</div>
        <h1 className="serif" style={{
          fontSize: 34, fontStyle: "italic", color: "var(--col-text)",
          margin: 0, letterSpacing: "-0.02em", lineHeight: 1
        }}>Mein Planer</h1>
        <p style={{ fontSize: 13, color: "var(--col-text-sec)", marginTop: 6, fontFamily: "var(--sans)" }}>
          {mode === "login" ? window.t("auth.loginSubtitle") : window.t("auth.registerSubtitle")}
        </p>
      </div>

      {/* Card */}
      <div style={{
        width: "100%", maxWidth: 380,
        background: "var(--col-bg-sec)", border: "1px solid var(--col-border)",
        borderRadius: 14, padding: "28px 28px 24px"
      }}>
        <form onSubmit={handleSubmit} autoComplete="on">
          <div style={{ marginBottom: 16 }}>
            <label style={labelStyle}>{window.t("auth.username")}</label>
            <input
              value={username} onChange={e => setUsername(e.target.value)}
              placeholder={window.t("auth.usernamePlaceholder")}
              autoFocus autoCapitalize="none" autoCorrect="off"
              autoComplete="username" spellCheck={false}
              style={inputStyle}
            />
          </div>

          <div style={{ marginBottom: mode === "register" ? 16 : 22 }}>
            <label style={labelStyle}>{window.t("auth.password")}</label>
            <input
              type="password" value={password} onChange={e => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete={mode === "login" ? "current-password" : "new-password"}
              style={inputStyle}
            />
          </div>

          {mode === "register" && (
            <div style={{ marginBottom: 16 }}>
              <label style={labelStyle}>{window.t("auth.confirmPassword")}</label>
              <input
                type="password" value={password2} onChange={e => setPassword2(e.target.value)}
                placeholder="••••••••"
                autoComplete="new-password"
                style={inputStyle}
              />
            </div>
          )}

          {mode === "register" && (
            <div style={{ marginBottom: 22 }}>
              <label style={labelStyle}>{window.t("auth.email")}</label>
              <input
                type="email" value={email} onChange={e => setEmail(e.target.value)}
                placeholder={window.t("auth.emailPlaceholder")}
                autoComplete="email"
                style={inputStyle}
              />
            </div>
          )}

          {err && (
            <div style={{
              background: "#fde8e8", border: "1px solid #fca5a5",
              borderRadius: 8, padding: "9px 12px", marginBottom: 16,
              fontSize: 12.5, color: "#b91c1c", lineHeight: 1.4
            }}>
              {err}
            </div>
          )}

          <button type="submit" disabled={loading} style={{
            width: "100%", padding: "11px", borderRadius: 8,
            background: "var(--col-accent)", color: "var(--col-bg)",
            fontSize: 14, fontWeight: 600, border: "none",
            cursor: loading ? "wait" : "pointer",
            fontFamily: "var(--sans)", letterSpacing: "0.01em",
            opacity: loading ? 0.7 : 1, transition: "opacity 0.15s"
          }}>
            {loading ? "..." : (mode === "login" ? window.t("auth.login") : window.t("auth.createAccount"))}
          </button>
        </form>

        <div style={{ textAlign: "center", marginTop: 20 }}>{/* FIXED B5b: registration hidden behind toggle */}
          <span style={{ fontSize: 11, color: "var(--col-text-3)", cursor: "pointer" }}
            onClick={() => switchMode(mode === "login" ? "register" : "login")}>
            {mode === "login" ? window.t("auth.createAccount") : window.t("auth.backToLogin")}
          </span>
        </div>
      </div>

      <p style={{ marginTop: 24, fontSize: 11, color: "var(--col-text-3)", fontFamily: "var(--mono)", letterSpacing: "0.04em" }}>
        {window.t("auth.runningOnPi")}
      </p>
    </div>
  );
}

Object.assign(window, { LoginScreen });
})();
