/* ── LOGIN PAGE — light theme + CRM motion ─────────────────────────── */

function LoginPage() {
  const [email, setEmail] = useState("");
  const [pwd, setPwd] = useState("");
  const [showPwd, setShowPwd] = useState(false);
  const [keepSigned, setKeepSigned] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  // Rotating brand statements
  const STATEMENTS = [
    { line1: "Every lead",  line2: "in one place.",          sub: "Auto-captured from Meta, Google, and your booking links — directly in your pipeline." },
    { line1: "Every reply", line2: "on autopilot.",          sub: "n8n flows fire WhatsApp, email, and SMS the moment a lead is ready to talk." },
    { line1: "Every deal",  line2: "visible in real-time.",  sub: "A live pipeline that your whole team is looking at — together — like a Figma file." },
  ];
  const [stmt, setStmt] = useState(0);
  useEffect(() => {
    const t = setInterval(() => setStmt(s => (s + 1) % STATEMENTS.length), 5200);
    return () => clearInterval(t);
  }, []);

  async function submit(e) {
    e.preventDefault();
    setError("");
    setSubmitting(true);
    try {
      const base = (window.VITE_API_URL) || "/api";
      const res = await fetch(base + "/auth/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password: pwd }),
      });
      if (!res.ok) {
        let msg = "Sign-in failed";
        try { const j = await res.json(); msg = j.error || j.message || msg; } catch {}
        throw new Error(msg);
      }
      const data = await res.json();
      if (data.token) localStorage.setItem("lf_token", data.token);
      window.location.href = "/dashboard";
    } catch (err) {
      setError(err.message || "Something went wrong");
      setSubmitting(false);
    }
  }

  function loginAsDemo(e) {
    if (e && e.preventDefault) e.preventDefault();
    localStorage.setItem("lf_token", "demo-mode");
    window.location.href = "/dashboard";
  }

  return (
    <div className="kr-page" style={{ minHeight: "100vh", background: "#fff", color: "var(--ink)" }}>
      <div className="kr-login-layout" style={{ display: "grid", gridTemplateColumns: "1.05fr 1fr", minHeight: "100vh" }}>

        {/* ════════ LEFT — Light + CRM motion ════════ */}
        <div className="kr-login-left" style={{
          position: "relative", overflow: "hidden",
          background: "linear-gradient(180deg, #f5f8ff 0%, #ffffff 60%, #fafbfd 100%)",
          color: "var(--ink)",
          display: "flex", flexDirection: "column", padding: "32px 48px",
        }}>
          {/* subtle grid */}
          <div className="kr-grid" style={{ position: "absolute", inset: 0, opacity: .35, pointerEvents: "none" }} />
          {/* dot mesh */}
          <div className="kr-dots" style={{ position: "absolute", inset: 0, opacity: .35, pointerEvents: "none" }} />
          {/* drifting orbs */}
          <div style={{
            position: "absolute", top: -120, left: -100, width: 460, height: 460, borderRadius: "50%",
            background: "radial-gradient(circle, rgba(147,197,253,.5), transparent 70%)",
            filter: "blur(46px)", animation: "kr-orb-drift 14s ease-in-out infinite", pointerEvents: "none",
          }} />
          <div style={{
            position: "absolute", bottom: -140, right: -120, width: 520, height: 520, borderRadius: "50%",
            background: "radial-gradient(circle, rgba(196,181,253,.45), transparent 70%)",
            filter: "blur(50px)", animation: "kr-orb-drift 18s ease-in-out infinite", animationDelay: "-6s", pointerEvents: "none",
          }} />
          <div style={{
            position: "absolute", top: "40%", right: -80, width: 280, height: 280, borderRadius: "50%",
            background: "radial-gradient(circle, rgba(254,229,138,.55), transparent 70%)",
            filter: "blur(36px)", animation: "kr-orb-drift 12s ease-in-out infinite", animationDelay: "-3s", pointerEvents: "none",
          }} />

          {/* TOP — logo + status */}
          <div style={{ position: "relative", display: "flex", alignItems: "center", justifyContent: "space-between", zIndex: 5 }}>
            <KredooLogo size={28} />
            <div style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "8px 14px", borderRadius: 999, background: "rgba(255,255,255,.85)", border: "1px solid var(--line)", backdropFilter: "blur(8px)" }}>
              <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--emerald)", boxShadow: "0 0 0 4px rgba(16,185,129,.18)" }} className="kr-pulse-dot" />
              <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".14em", textTransform: "uppercase", color: "var(--ink)" }}>All systems operational</span>
            </div>
          </div>

          {/* MIDDLE — brand statement + CRM visual */}
          <div style={{ position: "relative", zIndex: 2, flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", padding: "40px 0" }}>
            {/* Statement */}
            <div style={{ maxWidth: 540, marginInline: "auto", width: "100%" }}>
              <div className="kr-pill" style={{ background: "rgba(255,255,255,.85)", marginBottom: 18 }}>
                <span className="kr-dot" />
                The Modern Sales CRM
              </div>

              <div key={stmt} style={{ animation: "kr-rise .5s var(--ease)" }}>
                <h2 className="display" style={{
                  margin: 0, fontSize: "clamp(40px, 4.4vw, 56px)", fontWeight: 800, lineHeight: 1.02, letterSpacing: "-.03em",
                  color: "var(--ink)",
                }}>
                  {STATEMENTS[stmt].line1}<br />
                  <span style={{
                    background: "linear-gradient(135deg,#0a0e1a 0%, #2D3436 60%, #0a0e1a 100%)",
                    WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent",
                    backgroundClip: "text", position: "relative",
                  }}>
                    {STATEMENTS[stmt].line2}
                  </span>
                </h2>
                <p style={{ marginTop: 14, fontSize: 15, lineHeight: 1.55, fontWeight: 500, color: "var(--muted)", maxWidth: 480 }}>
                  {STATEMENTS[stmt].sub}
                </p>
              </div>

              {/* dots */}
              <div style={{ marginTop: 22, display: "flex", gap: 8 }}>
                {STATEMENTS.map((_, i) => (
                  <button key={i} onClick={() => setStmt(i)} aria-label={`Statement ${i + 1}`} style={{
                    width: i === stmt ? 32 : 8, height: 4, borderRadius: 4,
                    background: i === stmt ? "linear-gradient(90deg,#0a0e1a,#2D3436)" : "rgba(15,23,42,.14)",
                    border: 0, cursor: "pointer", padding: 0,
                    transition: "width .3s var(--ease), background .3s var(--ease)",
                  }} />
                ))}
              </div>
            </div>

            {/* CRM motion visual */}
            <div style={{ marginTop: 48, position: "relative", paddingInline: 36 }}>
              <CRMVisual />
            </div>
          </div>

          {/* BOTTOM — testimonial */}
          <div style={{ position: "relative", zIndex: 2, marginTop: 56, padding: "16px 20px", borderRadius: 16, background: "rgba(255,255,255,.7)", backdropFilter: "blur(8px)", border: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 14 }}>
            <div style={{ display: "flex", flexShrink: 0 }}>
              {["#3b82f6","#8b5cf6","#10b981","#C9A227"].map((c, i) => (
                <span key={i} style={{ width: 28, height: 28, borderRadius: "50%", background: c, marginLeft: i === 0 ? 0 : -8, border: "2px solid #fff", display: "grid", placeItems: "center", color: "#fff", fontSize: 10, fontWeight: 800 }}>
                  {["RP","SA","AK","VT"][i]}
                </span>
              ))}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <p style={{ margin: 0, fontSize: 13, fontWeight: 600, color: "var(--ink)", lineHeight: 1.45 }}>
                "Kredoo is the first CRM my team didn't fight me on. Pipeline became <span style={{ background: "linear-gradient(135deg,#E0B842,#C9A227)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", fontWeight: 800 }}>real</span> overnight."
              </p>
              <p style={{ margin: "4px 0 0", fontSize: 11, fontWeight: 700, color: "var(--muted-2)" }}>Ananya R. · VP Sales, Trustfire Realty</p>
            </div>
            <div style={{ display: "flex", gap: 2, color: "var(--gold)" }}>
              {[0,1,2,3,4].map(i => (
                <svg key={i} width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><polygon points="12 2 15 9 22 9 16.5 13.5 18.5 21 12 17 5.5 21 7.5 13.5 2 9 9 9 12 2" /></svg>
              ))}
            </div>
          </div>
        </div>

        {/* ════════ RIGHT — Form ════════ */}
        <div className="kr-login-right" style={{ position: "relative", display: "flex", flexDirection: "column", padding: "32px 48px", background: "#fff" }}>
          <div className="kr-dots" style={{ position: "absolute", inset: 0, opacity: .35, pointerEvents: "none" }} />

          {/* Mobile-only logo */}
          <div className="kr-login-mobile-logo" style={{ position: "relative", zIndex: 5 }}>
            <KredooLogo size={24} />
          </div>

          <div style={{ position: "relative", display: "flex", justifyContent: "flex-end" }}>
            <a href="/" style={{ display: "inline-flex", alignItems: "center", gap: 6, height: 36, padding: "0 14px", borderRadius: 999, fontSize: 12, fontWeight: 700, color: "var(--muted)", border: "1px solid var(--line-2)" }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></svg>
              Back to home
            </a>
          </div>

          <div style={{ position: "relative", flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
            <div style={{ width: "100%", maxWidth: 440, animation: "kr-rise .6s var(--ease)" }}>
              <div className="kr-pill" style={{ marginBottom: 18 }}>
                <span className="kr-dot" />
                Welcome back
              </div>
              <h1 className="display" style={{ margin: 0, fontSize: 48, fontWeight: 800, lineHeight: 1.02, letterSpacing: "-.028em", color: "var(--ink)" }}>
                Sign in to<br />Kredoo.
              </h1>
              <p style={{ margin: "14px 0 0", fontSize: 15, lineHeight: 1.55, fontWeight: 500, color: "var(--muted)" }}>
                Pick up where you left off. Your pipeline never stopped.
              </p>

              <form onSubmit={submit} style={{ marginTop: 28 }}>
                <label style={{ display: "block", fontSize: 11, fontWeight: 800, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--muted)", marginBottom: 8 }}>
                  Work email
                </label>
                <div className="kr-input-wrap">
                  <span className="kr-input-icon">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16v16H4z" /><polyline points="22 6 12 13 2 6" /></svg>
                  </span>
                  <input type="email" className="kr-input" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@company.com" autoComplete="email" />
                </div>

                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 18, marginBottom: 8 }}>
                  <label style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--muted)" }}>Password</label>
                  <a href="/" style={{ fontSize: 12, fontWeight: 700, color: "var(--ink)", textDecoration: "underline", textDecorationColor: "var(--gold)", textUnderlineOffset: 4 }}>
                    Forgot?
                  </a>
                </div>
                <div className="kr-input-wrap">
                  <span className="kr-input-icon">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>
                  </span>
                  <input type={showPwd ? "text" : "password"} className="kr-input" value={pwd} onChange={e => setPwd(e.target.value)} placeholder="••••••••••••" autoComplete="current-password" />
                  <button type="button" className="kr-input-right" onClick={() => setShowPwd(s => !s)} aria-label="Show password">
                    {showPwd ? (
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" /><line x1="1" y1="1" x2="23" y2="23" /></svg>
                    ) : (
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" /><circle cx="12" cy="12" r="3" /></svg>
                    )}
                  </button>
                </div>

                <label style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 18, cursor: "pointer" }}>
                  <button type="button" role="checkbox" aria-checked={keepSigned} onClick={() => setKeepSigned(v => !v)} style={{
                    width: 20, height: 20, borderRadius: 6, border: `1.5px solid ${keepSigned ? "var(--ink)" : "var(--line-2)"}`,
                    background: keepSigned ? "var(--ink)" : "#fff", display: "grid", placeItems: "center",
                    cursor: "pointer", padding: 0, transition: "all .2s var(--ease)",
                  }}>
                    {keepSigned && <Check size={12} color="#fff" />}
                  </button>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "var(--muted)" }}>Keep me signed in for 30 days</span>
                </label>

                {error && (
                  <div style={{ marginTop: 16, padding: "10px 14px", borderRadius: 12, background: "#fef2f2", border: "1px solid #fecaca", fontSize: 13, fontWeight: 600, color: "#dc2626" }}>
                    {error}
                  </div>
                )}

                <button type="submit" className="kr-cta-primary" disabled={submitting} style={{ marginTop: 22, width: "100%", height: 56, borderRadius: 16 }}>
                  {submitting ? (
                    <>
                      <span style={{ width: 14, height: 14, borderRadius: "50%", border: "2px solid rgba(255,255,255,.3)", borderTopColor: "var(--gold)", animation: "kr-spin-slow .8s linear infinite" }} />
                      Signing in…
                    </>
                  ) : (
                    <>Sign in <span className="kr-arrow">→</span></>
                  )}
                </button>

                <div style={{ display: "grid", gridTemplateColumns: "1fr auto 1fr", alignItems: "center", gap: 12, margin: "24px 0" }}>
                  <span style={{ height: 1, background: "var(--line-2)" }} />
                  <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".18em", color: "var(--muted-2)" }}>OR</span>
                  <span style={{ height: 1, background: "var(--line-2)" }} />
                </div>

                <button type="button" onClick={loginAsDemo} className="kr-cta-ghost" style={{ width: "100%", textDecoration: "none" }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--gold)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 2h4" /><path d="M12 14v-4" /><path d="M4.93 19.07A10 10 0 1 1 19.07 4.93" /><circle cx="12" cy="14" r="6" /></svg>
                  Continue with Demo Mode
                </button>
                <p style={{ margin: "8px 0 0", textAlign: "center", fontSize: 11, fontWeight: 600, color: "var(--muted-2)" }}>
                  Explore with sample data — no account needed
                </p>

                <p style={{ margin: "26px 0 0", textAlign: "center", fontSize: 13, fontWeight: 600, color: "var(--muted)" }}>
                  Don't have an account?{" "}
                  <a href="/get-started" style={{ color: "var(--ink)", fontWeight: 800, textDecoration: "underline", textDecorationColor: "var(--gold)", textUnderlineOffset: 4 }}>
                    Start free trial
                  </a>
                </p>
              </form>
            </div>
          </div>

          <div style={{ position: "relative", display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 11, fontWeight: 600, color: "var(--muted-2)" }}>
            <Footnote />
            <div style={{ display: "flex", gap: 14 }}>
              <a href="/">Privacy</a>
              <a href="/">Terms</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginPage });
