/* Sign-in screen (LIVE mode, when no session). Lists the providers the backend
   reports as configured, with proper brand marks + order, and starts the real
   OAuth flow on click. Shown by App in place of the app shell until authenticated. */

// Brand marks (inline SVG so no external assets) + display order.
const PROVIDER_BRAND = {
  google: { order: 0, mark: (
    <svg viewBox="0 0 48 48" width="18" height="18" aria-hidden="true"><path fill="#4285F4" d="M45.12 24.5c0-1.56-.14-3.06-.4-4.5H24v8.51h11.84c-.51 2.75-2.06 5.08-4.39 6.64v5.52h7.11c4.16-3.83 6.56-9.47 6.56-16.17z"/><path fill="#34A853" d="M24 46c5.94 0 10.92-1.97 14.56-5.33l-7.11-5.52c-1.97 1.32-4.49 2.1-7.45 2.1-5.73 0-10.58-3.87-12.31-9.07H4.34v5.7A21.99 21.99 0 0 0 24 46z"/><path fill="#FBBC05" d="M11.69 28.18A13.2 13.2 0 0 1 11 24c0-1.45.25-2.86.69-4.18v-5.7H4.34A21.99 21.99 0 0 0 2 24c0 3.55.85 6.91 2.34 9.88l7.35-5.7z"/><path fill="#EA4335" d="M24 10.75c3.23 0 6.13 1.11 8.41 3.29l6.31-6.31C34.91 4.18 29.93 2 24 2 15.4 2 7.96 6.94 4.34 14.12l7.35 5.7C13.42 14.62 18.27 10.75 24 10.75z"/></svg>
  ) },
  microsoft: { order: 1, mark: (
    <svg viewBox="0 0 23 23" width="16" height="16" aria-hidden="true"><rect x="1" y="1" width="10" height="10" fill="#F25022"/><rect x="12" y="1" width="10" height="10" fill="#7FBA00"/><rect x="1" y="12" width="10" height="10" fill="#00A4EF"/><rect x="12" y="12" width="10" height="10" fill="#FFB900"/></svg>
  ) },
  apple: { order: 2, mark: (
    <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path fill="#000" d="M16.37 12.86c.03 3.16 2.77 4.21 2.8 4.22-.02.07-.44 1.51-1.45 2.99-.87 1.28-1.78 2.56-3.21 2.58-1.4.03-1.86-.83-3.46-.83-1.6 0-2.1.81-3.43.86-1.38.05-2.43-1.38-3.31-2.66-1.8-2.6-3.18-7.35-1.33-10.55.92-1.59 2.56-2.6 4.34-2.62 1.35-.03 2.63.91 3.46.91.83 0 2.38-1.13 4.01-.96.68.03 2.6.28 3.83 2.06-.1.06-2.29 1.34-2.27 3.99M13.9 4.6c.73-.89 1.22-2.12 1.09-3.35-1.05.04-2.32.7-3.08 1.58-.68.78-1.27 2.03-1.11 3.23 1.17.09 2.37-.6 3.1-1.46"/></svg>
  ) },
  facebook: { order: 3, mark: (
    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="#1877F2" d="M24 12a12 12 0 1 0-13.88 11.85v-8.38H7.08V12h3.04V9.36c0-3 1.79-4.67 4.53-4.67 1.31 0 2.68.24 2.68.24v2.95h-1.51c-1.49 0-1.96.93-1.96 1.87V12h3.33l-.53 3.47h-2.8v8.38A12 12 0 0 0 24 12"/></svg>
  ) },
  linkedin: { order: 4, mark: (
    <svg viewBox="0 0 24 24" width="17" height="17" aria-hidden="true"><path fill="#0A66C2" d="M20.45 20.45h-3.56v-5.57c0-1.33-.02-3.04-1.85-3.04-1.85 0-2.14 1.45-2.14 2.94v5.67H9.35V9h3.42v1.56h.05c.48-.9 1.64-1.85 3.37-1.85 3.6 0 4.27 2.37 4.27 5.46v6.28zM5.34 7.43a2.07 2.07 0 1 1 0-4.14 2.07 2.07 0 0 1 0 4.14zM7.12 20.45H3.55V9h3.57v11.45zM22.22 0H1.77C.79 0 0 .77 0 1.73v20.54C0 23.22.79 24 1.77 24h20.45c.98 0 1.78-.78 1.78-1.73V1.73C24 .77 23.2 0 22.22 0z"/></svg>
  ) },
  x: { order: 5, mark: (
    <svg viewBox="0 0 24 24" width="15" height="15" aria-hidden="true"><path fill="#000" d="M18.24 2h3.31l-7.23 8.26L22.86 22h-6.66l-5.22-6.82L4.99 22H1.68l7.73-8.84L1.14 2H7.97l4.72 6.24L18.24 2zm-1.16 18h1.83L7.01 3.9H5.05L17.08 20z"/></svg>
  ) },
};

function Login() {
  const [providers, setProviders] = React.useState(null); // null = loading
  const [password, setPassword] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [mode, setMode] = React.useState("signin"); // 'signin' | 'signup'
  const [email, setEmail] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [name, setName] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const errText = (e) => {
    try { return JSON.parse(e.body).message; } catch (x) { return null; }
  };
  const submitPassword = (ev) => {
    ev.preventDefault();
    setError(null); setBusy(true);
    const A = window.LeapAPI;
    const p = mode === "signup" ? A.passwordRegister(email.trim(), pw, name.trim()) : A.passwordLogin(email.trim(), pw);
    p.then(() => window.location.reload())
      .catch((e) => { setError(errText(e) || (mode === "signup" ? "Couldn't create your account." : "Incorrect email or password.")); setBusy(false); });
  };

  React.useEffect(() => {
    window.LeapAPI.providers()
      .then((r) => {
        const list = (r.providers || []).filter((p) => p.configured);
        list.sort((a, b) => ((PROVIDER_BRAND[a.id] || {}).order ?? 99) - ((PROVIDER_BRAND[b.id] || {}).order ?? 99));
        setProviders(list);
        setPassword(!!r.password);
      })
      .catch(() => { setProviders([]); setError("Couldn't reach the sign-in service."); });
    try {
      const e = new URL(window.location.href).searchParams.get("error");
      if (e) setError("Sign-in failed: " + e.replace(/_/g, " "));
    } catch (x) { /* ignore */ }
  }, []);

  const btn = {
    display: "flex", alignItems: "center", gap: 12, width: "100%", height: 46, padding: "0 16px",
    borderRadius: 12, border: "1px solid var(--border, #E5E7EB)", background: "var(--surface, #fff)",
    fontSize: 14, fontWeight: 600, color: "var(--fg1, #1F2937)", cursor: "pointer", textAlign: "left",
  };
  const field = {
    width: "100%", boxSizing: "border-box", height: 44, padding: "0 13px", borderRadius: 11,
    border: "1px solid var(--border-strong, #D1D5DB)", background: "var(--surface, #fff)",
    fontSize: 14, fontFamily: "inherit", color: "var(--fg1, #1F2937)", outline: "none",
  };

  return (
    <div style={{ minHeight: "100vh", display: "grid", placeItems: "center", background: "var(--surface-page, #F6F8FB)" }}>
      <div style={{ width: 380, maxWidth: "92vw", background: "var(--surface-card, #fff)", border: "1px solid var(--border, #E5E7EB)", borderRadius: 18, padding: 32, textAlign: "center", boxShadow: "0 10px 40px rgba(2,32,54,.08)" }}>
        <img src="assets/leap-mark.svg" alt="Leap" style={{ width: 44, height: 44 }} onError={(e) => { e.target.style.display = "none"; }} />
        <h1 style={{ fontSize: 22, fontWeight: 800, margin: "14px 0 4px" }}>Sign in to Leap</h1>
        <p style={{ fontSize: 13, color: "var(--fg3, #6B7280)", marginBottom: 22 }}>Post smarter. Make a Leap.</p>

        {providers === null && <p style={{ fontSize: 13, color: "var(--fg3, #6B7280)" }}>Loading sign-in options…</p>}

        {/* email + password (real credentials, scrypt-hashed server-side) */}
        {password && (
          <form onSubmit={submitPassword} style={{ display: "grid", gap: 10, textAlign: "left" }}>
            {mode === "signup" && (
              <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" autoComplete="name" style={field} />
            )}
            <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" required placeholder="you@company.com" autoComplete="email" style={field} />
            <input value={pw} onChange={(e) => setPw(e.target.value)} type="password" required minLength={mode === "signup" ? 8 : undefined}
              placeholder={mode === "signup" ? "Choose a password (8+ characters)" : "Password"} autoComplete={mode === "signup" ? "new-password" : "current-password"} style={field} />
            <button type="submit" disabled={busy} style={{ ...btn, justifyContent: "center", background: "var(--accent, #0B5FFF)", color: "#fff", border: 0, opacity: busy ? 0.7 : 1 }}>
              {busy ? "…" : mode === "signup" ? "Create account" : "Sign in"}
            </button>
            <div style={{ fontSize: 12.5, color: "var(--fg3, #6B7280)", textAlign: "center", marginTop: 2 }}>
              {mode === "signup" ? "Already have an account? " : "New to Leap? "}
              <button type="button" onClick={() => { setMode(mode === "signup" ? "signin" : "signup"); setError(null); }}
                style={{ border: 0, background: "none", color: "var(--accent, #0B5FFF)", fontWeight: 700, cursor: "pointer", padding: 0, fontFamily: "inherit", fontSize: 12.5 }}>
                {mode === "signup" ? "Sign in" : "Create one"}
              </button>
            </div>
          </form>
        )}

        {error && <p style={{ fontSize: 12, color: "var(--danger, #DC2626)", marginTop: 14 }}>{error}</p>}

        {password && providers !== null && providers.length > 0 && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "20px 0 6px" }}>
            <div style={{ flex: 1, height: 1, background: "var(--border, #E5E7EB)" }} />
            <span style={{ fontSize: 11, color: "var(--fg4, #9CA3AF)", fontWeight: 700, letterSpacing: ".04em" }}>OR</span>
            <div style={{ flex: 1, height: 1, background: "var(--border, #E5E7EB)" }} />
          </div>
        )}

        {providers !== null && providers.length > 0 && (
          <div style={{ display: "grid", gap: 10 }}>
            {providers.map((p) => (
              <button key={p.id} style={btn} onClick={() => window.LeapAuth.login(p.id)}
                onMouseEnter={(e) => { e.currentTarget.style.background = "var(--surface-hover, #F3F4F6)"; e.currentTarget.style.borderColor = "var(--border-strong, #D1D5DB)"; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = "var(--surface, #fff)"; e.currentTarget.style.borderColor = "var(--border, #E5E7EB)"; }}>
                <span style={{ width: 20, display: "inline-flex", justifyContent: "center" }}>{(PROVIDER_BRAND[p.id] || {}).mark || null}</span>
                <span>Continue with {p.label}</span>
              </button>
            ))}
          </div>
        )}

        {providers !== null && providers.length === 0 && !password && (
          <p style={{ fontSize: 13, color: "var(--fg3, #6B7280)" }}>No sign-in options are configured yet.</p>
        )}

        <p style={{ fontSize: 11, color: "var(--fg4, #9CA3AF)", marginTop: 22 }}>By continuing you agree to Leap's Terms & Privacy Policy.</p>
      </div>
    </div>
  );
}
window.Login = Login;
