/* Login / Register — flujo de auth con email + password.
 *
 * Modos:
 *  - "login":     pide email + password, hace POST /auth/login.
 *  - "register":  pide email + password (+ nombre opcional), hace POST /auth/register
 *                 y, si 201, hace login automático y redirige a onboarding.
 *  - "demo":      no toca el backend, setea api_fit_demo=1 y entra a la app con MOCKs.
 *
 * Onboarding/instalación nueva: si el backend responde GET /auth/has_users { has_users: false }
 * el modo arranca en "register" para forzar la creación del primer usuario.
 */

const Login = ({ onAuthenticated, onRegisteredFirstTime }) => {
  const [mode, setMode] = React.useState("login"); // login | register
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [name, setName] = React.useState("");
  const [base, setBase] = React.useState(API.getBase());
  const [showHelp, setShowHelp] = React.useState(false);
  const [status, setStatus] = React.useState({ kind: "idle" });
  const [bootChecked, setBootChecked] = React.useState(false);

  // Boot: chequear si hay usuarios en el sistema. Si no, forzar registro.
  React.useEffect(() => {
    let alive = true;
    (async () => {
      try {
        const res = await API.authHasUsers();
        if (!alive) return;
        if (res && res.has_users === false) {
          setMode("register");
        }
      } catch (_) {
        // backend caído o endpoint no implementado todavía: dejamos modo login.
      } finally {
        if (alive) setBootChecked(true);
      }
    })();
    return () => { alive = false; };
  }, []);

  const validate = () => {
    if (!email.includes("@")) return "Ingresá un email válido.";
    if (mode === "register" && password.length < 8) return "La contraseña debe tener al menos 8 caracteres.";
    if (!password) return "Ingresá una contraseña.";
    return null;
  };

  const submit = async () => {
    const err = validate();
    if (err) {
      setStatus({ kind: "bad", msg: err });
      return;
    }
    if (base) API.setBase(base);
    setStatus({ kind: "loading" });

    try {
      if (mode === "register") {
        await API.authRegister({ email: email.trim(), password, name: name.trim() || undefined });
        // Auto-login después de registrar.
        await API.authLogin({ email: email.trim(), password });
        // Limpiar flag de demo si quedaba.
        API.setDemoMode(false);
        setStatus({ kind: "ok", msg: "Cuenta creada. Entrando…" });
        // Primera ejecución: ir al onboarding.
        setTimeout(() => (onRegisteredFirstTime || onAuthenticated)(), 250);
      } else {
        await API.authLogin({ email: email.trim(), password });
        API.setDemoMode(false);
        setStatus({ kind: "ok", msg: "Sesión iniciada." });
        setTimeout(onAuthenticated, 200);
      }
    } catch (e) {
      let msg;
      if (e.network) {
        msg = `El servidor no responde (${API.getBase() || "mismo origen"}). ¿Está corriendo el backend?`;
      } else if (e.status === 401) {
        msg = "Email o contraseña incorrectos.";
      } else if (e.status === 409) {
        msg = "Ese email ya está registrado. Probá iniciar sesión.";
      } else if (e.status === 400) {
        const detail = e.detail?.detail || "";
        if (/password/i.test(detail)) msg = "La contraseña debe tener al menos 8 caracteres.";
        else if (/email/i.test(detail)) msg = "Email inválido.";
        else msg = detail || e.message;
      } else if (e.status >= 500) {
        msg = "El servidor tuvo un error. Probá de nuevo en un momento.";
      } else {
        msg = e.message || "Algo no anduvo.";
      }
      setStatus({ kind: "bad", msg });
    }
  };

  const skipToDemo = () => {
    API.setDemoMode(true);
    API.clearToken();
    API.clearUser();
    onAuthenticated();
  };

  const onKeyDown = (e) => {
    if (e.key === "Enter") submit();
  };

  return (
    <div className="af-login-shell">
      <div className="af-login-card">
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 28 }}>
          <window.FtiMindLogo.Mark size={36} />
          <div>
            <window.FtiMindLogo.Wordmark size={18} />
            <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>tu salud, en tu casa</div>
          </div>
        </div>

        <h1 className="display" style={{ margin: 0, fontSize: 28, fontWeight: 400, letterSpacing: "-0.02em", marginBottom: 10 }}>
          {mode === "register" ? "Creá tu cuenta." : "Iniciá sesión."}
        </h1>
        <div style={{ fontSize: 13, color: "var(--text-2)", marginBottom: 22, lineHeight: 1.55 }}>
          {mode === "register"
            ? "Una sola cuenta por instalación de api_fit. Tus credenciales viven en tu base de datos local."
            : "Usá el email y la contraseña con los que te registraste en este servidor."}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 12 }}>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            onKeyDown={onKeyDown}
            placeholder="email@dominio.com"
            autoFocus
            autoComplete="email"
            className="af-login-input"
          />
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            onKeyDown={onKeyDown}
            placeholder={mode === "register" ? "contraseña (mínimo 8 caracteres)" : "contraseña"}
            autoComplete={mode === "register" ? "new-password" : "current-password"}
            className="af-login-input"
          />
          {mode === "register" && (
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              onKeyDown={onKeyDown}
              placeholder="nombre (opcional)"
              autoComplete="name"
              className="af-login-input"
            />
          )}
        </div>

        <button
          onClick={() => setShowHelp((v) => !v)}
          style={{ background: "none", border: "none", color: "var(--text-3)", fontSize: 11, padding: 0, marginBottom: 12, cursor: "pointer" }}
        >
          {showHelp ? "ocultar" : "¿el backend está en otro host?"}
        </button>

        {showHelp && (
          <input
            type="text"
            value={base}
            onChange={(e) => setBase(e.target.value)}
            placeholder="http://localhost:8000"
            className="af-login-input"
            style={{ marginBottom: 12 }}
          />
        )}

        {status.kind === "bad" && (
          <div style={{
            padding: "10px 12px", marginBottom: 12,
            background: "var(--bad-soft)",
            border: "1px solid color-mix(in srgb, var(--bad) 30%, transparent)",
            borderRadius: "var(--r-2)",
            fontSize: 12, color: "var(--text-2)",
          }}>
            <strong style={{ color: "var(--bad)" }}>Error:</strong> {status.msg}
          </div>
        )}
        {status.kind === "ok" && (
          <div style={{
            padding: "10px 12px", marginBottom: 12,
            background: "var(--good-soft)",
            border: "1px solid color-mix(in srgb, var(--good) 30%, transparent)",
            borderRadius: "var(--r-2)",
            fontSize: 12, color: "var(--good)",
            display: "flex", alignItems: "center", gap: 8,
          }}>
            <span>✓</span> {status.msg || "Listo. Entrando…"}
          </div>
        )}

        <button
          onClick={submit}
          disabled={status.kind === "loading"}
          style={{
            width: "100%", padding: "12px 16px",
            background: "var(--accent)", color: "var(--accent-fg)",
            border: "none", borderRadius: "var(--r-2)",
            fontSize: 13.5, fontWeight: 500,
            cursor: status.kind === "loading" ? "wait" : "pointer",
            display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
            marginBottom: 12,
          }}>
          {status.kind === "loading"
            ? (mode === "register" ? "Creando cuenta…" : "Iniciando sesión…")
            : (mode === "register" ? "Crear cuenta" : "Entrar")}
        </button>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 4, marginBottom: 10 }}>
          <button
            onClick={() => { setMode(mode === "register" ? "login" : "register"); setStatus({ kind: "idle" }); }}
            style={{ background: "none", border: "none", color: "var(--text-2)", fontSize: 12, padding: 0, cursor: "pointer", textDecoration: "underline" }}>
            {mode === "register" ? "¿Ya tenés cuenta? Iniciá sesión" : "¿No tenés cuenta? Crear cuenta"}
          </button>
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: 8, borderTop: "1px dashed var(--line-soft)" }}>
          <button
            onClick={skipToDemo}
            style={{ background: "none", border: "none", color: "var(--text-3)", fontSize: 11.5, padding: 0, cursor: "pointer", textDecoration: "underline" }}>
            Modo demo (sin backend)
          </button>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--text-4)" }}>
            🔒 local · datos en tu máquina
          </span>
        </div>
      </div>
    </div>
  );
};

window.Login = Login;
