// Login screen — gates the entire app. Credentials are validated by the
// backend (/api/auth/login). On success we persist the returned member as the
// session so the rest of the app can read the actor.
window.LoginScreen = function LoginScreen({ t, lang, setLang, theme, setTheme, onLogin }) {
  const Icons = window.Icons;
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [showPassword, setShowPassword] = React.useState(false);
  const [error, setError] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const toast = window.useToast();

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    const emailTrim = email.trim();
    if (!emailTrim || !/.+@.+\..+/.test(emailTrim)) {
      setError(lang === "es" ? "Introduce un email válido." : "Enter a valid email.");
      return;
    }
    if (!password) {
      setError(lang === "es" ? "Introduce tu contraseña." : "Enter your password.");
      return;
    }
    setError("");
    setSubmitting(true);
    try {
      const member = await window.api.auth.login(emailTrim, password);
      window.setSession(member);
      onLogin && onLogin();
    } catch (err) {
      const invalid = err?.status === 401;
      setError(invalid
        ? (lang === "es" ? "Email o contraseña incorrectos." : "Invalid email or password.")
        : (err?.message || (lang === "es" ? "No se pudo iniciar sesión." : "Could not sign in.")));
    } finally {
      setSubmitting(false);
    }
  };

  const onRegister = () => {
    toast(lang === "es" ? "Deshabilitado temporalmente" : "Temporarily disabled", "info");
  };

  return (
    <div className="onb-overlay">
      {/* Top-right utilities: language + theme */}
      <div style={{ position: "fixed", top: 16, right: 20, display: "flex", gap: 8, zIndex: 1 }}>
        <button
          className="lang-toggle"
          onClick={() => setLang(lang === "en" ? "es" : "en")}
          aria-label="Toggle language"
        >
          <Icons.Globe />
          <span className="lang-current">{lang === "en" ? "EN" : "ES"}</span>
        </button>
        <button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
          {theme === "dark" ? <Icons.Sun /> : <Icons.Moon />}
        </button>
      </div>

      <form className="onb-card" style={{ width: 420 }} onSubmit={submit} noValidate>
        <div style={{ textAlign: "center", marginBottom: 24 }}>
          <img src="assets/logo-small.png" alt="Vildez" style={{ width: 48, height: 48 }} />
          <h1 style={{ margin: "12px 0 4px", fontSize: 22, fontWeight: 700, letterSpacing: "-0.02em" }}>
            {lang === "es" ? "Inicia sesión" : "Sign in"}<span style={{ color: "var(--brand)" }}>.</span>
          </h1>
          <p style={{ color: "var(--text-muted)", margin: 0, fontSize: 13 }}>
            {lang === "es" ? "Accede a tu espacio de trabajo." : "Access your workspace."}
          </p>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <label className="field">
            {t("email")}
            <input
              className="input"
              type="email"
              autoComplete="email"
              autoFocus
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@company.com"
              disabled={submitting}
            />
          </label>

          <div className="field">
            <span>{lang === "es" ? "Contraseña" : "Password"}</span>
            <div style={{ position: "relative" }}>
              <input
                className="input"
                type={showPassword ? "text" : "password"}
                autoComplete="current-password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
                disabled={submitting}
                style={{ width: "100%", paddingRight: 36 }}
              />
              <button
                type="button"
                className="icon-btn"
                onClick={() => setShowPassword(s => !s)}
                style={{ position: "absolute", right: 4, top: "50%", transform: "translateY(-50%)" }}
                aria-label={showPassword ? "Hide password" : "Show password"}
                tabIndex={-1}
              >
                {showPassword ? <Icons.EyeOff /> : <Icons.Eye />}
              </button>
            </div>
          </div>

          {error && (
            <div style={{ color: "var(--danger)", fontSize: 12, marginTop: -4 }}>{error}</div>
          )}

          <button type="submit" className="btn brand" style={{ width: "100%", height: 38, marginTop: 4 }} disabled={submitting}>
            {submitting
              ? (lang === "es" ? "Entrando…" : "Signing in…")
              : (lang === "es" ? "Entrar" : "Sign in")}
          </button>

          <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--text-faint)", fontSize: 11, margin: "4px 0" }}>
            <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
            <span>{lang === "es" ? "o" : "or"}</span>
            <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
          </div>

          <button type="button" className="btn" style={{ width: "100%", height: 38 }} onClick={onRegister}>
            {lang === "es" ? "Registrarse" : "Sign up"}
          </button>
        </div>
      </form>
    </div>
  );
};

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