// Login screen
const { useState: useStateLogin } = React;

function Login({ onLogin }) {
  const [email,    setEmail]    = useStateLogin("");
  const [password, setPassword] = useStateLogin("");
  const [show,     setShow]     = useStateLogin(false);
  const [errors,   setErrors]   = useStateLogin({});
  const [loading,  setLoading]  = useStateLogin(false);

  function clearErr(k) { setErrors((e) => ({ ...e, [k]: null })); }

  async function submit(e) {
    e.preventDefault();
    const errs = {};
    if (!email.trim())    errs.email    = "Email is required.";
    if (!password.trim()) errs.password = "Password is required.";
    if (Object.keys(errs).length) { setErrors(errs); return; }

    setErrors({});
    setLoading(true);

    try {
      const r = await window.api.login(email.trim(), password);

      if (r?.status === "success" && r?.data) {
        const { token, full_name, email: userEmail, id, current_role } = r.data;
        localStorage.setItem("roa_access_token",  token.access_token);
        localStorage.setItem("roa_refresh_token", token.refresh_token);
        localStorage.setItem("roa_user", JSON.stringify({ id, full_name, email: userEmail, current_role }));
        onLogin({ id, full_name, email: userEmail, current_role });
        return;
      }

      // Field-level errors
      const data = r?.data;
      if (data && typeof data === "object") {
        const fe = {};
        if (data.email)    fe.email    = Array.isArray(data.email)    ? data.email[0]    : data.email;
        if (data.password) fe.password = Array.isArray(data.password) ? data.password[0] : data.password;
        if (Object.keys(fe).length) { setErrors(fe); return; }
      }
      setErrors({ password: typeof data === "string" ? data : "Invalid credentials." });
    } catch (_) {
      setErrors({ password: "Could not reach the server. Try again." });
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ minHeight: "calc(100vh / 0.8)", display: "grid", gridTemplateColumns: "1.05fr 1fr" }}>
      {/* left: brand panel */}
      <div style={{ position: "relative", overflow: "hidden",
        background: "linear-gradient(155deg, #10295A 0%, #16356f 55%, #1c4488 100%)",
        display: "flex", flexDirection: "column", justifyContent: "flex-start", padding: "48px 56px", color: "#fff" }}>
        <div style={{ position: "absolute", inset: 0, opacity: .5,
          background: "radial-gradient(900px 500px at 80% -10%, #2f5da333, transparent), radial-gradient(700px 600px at -10% 110%, #1A917522, transparent)" }}></div>
        <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 14 }}>
          <img src="assets/roa-logo-white.svg" alt="Realty of America" style={{ height: 24, width: "auto", display: "block" }} />
          <span style={{ width: 1, height: 28, background: "#ffffff33" }}></span>
          <span style={{ fontWeight: 800, fontSize: 17, letterSpacing: "-.01em" }}>Mainstay</span>
        </div>

        <div style={{ position: "relative", flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", maxWidth: 440 }}>
          <h1 style={{ fontSize: 38, lineHeight: 1.12, fontWeight: 800, margin: "0 0 16px", letterSpacing: "-.02em" }}>
            Log every lead the moment the call ends.
          </h1>
          <p style={{ fontSize: 15.5, lineHeight: 1.6, color: "#ffffffcc", margin: 0, fontWeight: 500 }}>
            No more shared spreadsheets or manual exports. Log a lead in under a minute, then see the
            assigned agent, live status, and a shared comment thread - all in one place.
          </p>
          <div style={{ marginTop: 38, position: "relative", maxWidth: 430 }}>
            <svg width="100%" viewBox="0 0 440 150" fill="none" style={{ display: "block" }} aria-hidden="true">
              <rect x="8" y="10" width="150" height="22" rx="7" fill="#ffffff" fillOpacity="0.06" stroke="#ffffff" strokeOpacity="0.16" />
              <rect x="22" y="34" width="150" height="22" rx="7" fill="#ffffff" fillOpacity="0.1" stroke="#ffffff" strokeOpacity="0.2" />
              <rect x="22" y="40" width="56" height="6" rx="3" fill="#ffffff" fillOpacity="0.35" />
              <rect x="86" y="40" width="30" height="6" rx="3" fill="#1A9175" />
              <path d="M97 56 C 97 84, 70 84, 70 104" stroke="#ffffff" strokeOpacity="0.22" strokeWidth="2" strokeDasharray="2 6" strokeLinecap="round" />
              <path d="M40 110 H410" stroke="#ffffff" strokeOpacity="0.16" strokeWidth="2" strokeLinecap="round" />
              <path d="M40 110 H255" stroke="#1A9175" strokeWidth="3" strokeLinecap="round" />
              <circle cx="40" cy="110" r="6" fill="#ffffff" />
              <circle cx="147" cy="110" r="6" fill="#ffffff" />
              <circle cx="255" cy="110" r="9" fill="#1A9175" stroke="#0f2a4d" strokeWidth="3" />
              <circle cx="362" cy="110" r="6" fill="#ffffff" fillOpacity="0.4" />
            </svg>
            <p style={{ fontSize: 13.5, lineHeight: 1.55, color: "#ffffffb0", margin: "14px 0 0", fontWeight: 500 }}>
              Every Mainstay lead flows through one validated pipeline - from submission to an assigned ROA agent, all the way to close.
            </p>
          </div>
        </div>
      </div>

      {/* right: form */}
      <div style={{ display: "grid", placeItems: "center", padding: 32, background: "var(--bg-app)" }}>
        <form onSubmit={submit} className="fade-up" style={{ width: "100%", maxWidth: 380 }}>
          <div style={{ marginBottom: 28 }}>
            <h2 style={{ fontSize: 24, fontWeight: 800, margin: "0 0 7px", color: "var(--navy)", letterSpacing: "-.01em" }}>Sign in</h2>
            <p style={{ margin: 0, color: "var(--muted)", fontSize: 14 }}>
              Use your Mainstay partner credentials.
            </p>
          </div>

          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <Field label="Email" error={errors.email}>
              <input className={"input" + (errors.email ? " err" : "")} value={email}
                onChange={(e) => { setEmail(e.target.value); clearErr("email"); }}
                type="email" autoComplete="email" placeholder="you@mainstay.com" />
            </Field>
            <Field label="Password" error={errors.password}>
              <div style={{ position: "relative" }}>
                <input className={"input" + (errors.password ? " err" : "")} type={show ? "text" : "password"}
                  value={password} onChange={(e) => { setPassword(e.target.value); clearErr("password"); }}
                  autoComplete="current-password" placeholder="Enter password" style={{ paddingRight: 44 }} />
                <button type="button" onClick={() => setShow(!show)} aria-label="Toggle password"
                  style={{ position: "absolute", right: 6, top: 6, width: 32, height: 32, borderRadius: 8,
                    border: "none", background: "transparent", color: "var(--muted)", cursor: "pointer",
                    display: "grid", placeItems: "center" }}>
                  <Icon name="eye" size={17} />
                </button>
              </div>
            </Field>

            <button className="btn btn-navy" type="submit" disabled={loading} style={{ height: 46, marginTop: 4 }}>
              {loading ? "Signing in..." : <>Sign in <Icon name="arrowRight" size={17} /></>}
            </button>
          </div>

          <div style={{ marginTop: 22, padding: "12px 14px", background: "#fff", border: "1px solid var(--border)",
            borderRadius: 10, display: "flex", gap: 10, alignItems: "flex-start" }}>
            <Icon name="lock" size={15} style={{ color: "var(--muted)", marginTop: 1, flexShrink: 0 }} />
            <div style={{ fontSize: 12.5, color: "var(--muted)", lineHeight: 1.5 }}>
              This is a shared account. Every lead you submit is attributed to <b style={{ color: "var(--label-2)" }}>Mainstay</b> and visible to your whole team.
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

window.Login = Login;
