// Sherpas Labs — Login page (production)
// Google OAuth → /auth/login
// Partner email+password → /auth/partner/login
// Access request → POST /api/access-request

const LoginPage = () => {
  const [requesting, setRequesting] = React.useState(false);
  const [partnerEmail, setPartnerEmail] = React.useState("");
  const [partnerPassword, setPartnerPassword] = React.useState("");
  const [partnerLoading, setPartnerLoading] = React.useState(false);
  const [partnerError, setPartnerError] = React.useState("");
  const [changePasswordUser, setChangePasswordUser] = React.useState(null);

  const params = new URLSearchParams(window.location.search);
  const error = params.get("error");
  const errorMessages = {
    oauth_denied: "Sign-in was cancelled.",
    invalid_callback: "Invalid OAuth callback. Please try again.",
    invalid_state: "Session expired. Please try again.",
    token_exchange: "Could not complete sign-in. Please try again.",
    userinfo: "Could not retrieve your profile. Please try again.",
    pending_approval: "Your request is pending review. We'll be in touch.",
    access_denied: "Access denied.",
    session_expired: "Your session expired. Please sign in again.",
  };
  const errorMsg = error ? (errorMessages[error] || "An error occurred. Please try again.") : null;

  const onGoogle = () => { window.location.href = "/auth/login"; };

  const onPartnerSubmit = async (e) => {
    e.preventDefault();
    if (!partnerEmail || !partnerPassword) return;
    setPartnerLoading(true); setPartnerError("");
    try {
      const res = await fetch("/auth/partner/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: partnerEmail, password: partnerPassword }),
        credentials: "include",
      });
      const data = await res.json();
      if (!res.ok) { setPartnerError(data.message || "Incorrect email or password."); return; }
      document.cookie = `sherpas_labs_session=${data.session_token}; path=/; SameSite=Lax`;
      if (data.must_change_password) {
        setChangePasswordUser({ email: partnerEmail, tempPassword: partnerPassword });
      } else {
        window.location.href = "/index";
      }
    } catch (err) {
      setPartnerError("Something went wrong. Please try again.");
    } finally {
      setPartnerLoading(false);
    }
  };

  // Responsive: detect mobile
  const isMobile = window.innerWidth < 768;

  return (
    <div className="sw" style={{
      width: "100%", minHeight: "100vh",
      display: "grid",
      gridTemplateColumns: isMobile ? "1fr" : "minmax(0, 1fr) minmax(480px, 580px)",
      background: "var(--bg)",
    }}>

      {/* LEFT — dark manifesto (hidden on mobile) */}
      {!isMobile && (
        <aside style={{
          background: "var(--bg-dark)", color: "var(--bg)",
          padding: "48px 56px",
          display: "flex", flexDirection: "column", justifyContent: "space-between",
          position: "relative", minHeight: "100vh",
        }}>
          <div className="t-mono" style={{
            position: "absolute", top: 24, left: 56, right: 56,
            fontSize: 10, letterSpacing: "0.3em",
            color: "rgba(251,250,247,0.3)", textTransform: "uppercase",
            display: "flex", justifyContent: "space-between",
          }}>
            <span>⌁ &nbsp; Restricted · Sherpas Labs</span>
            <span>do not redistribute</span>
          </div>

          <header style={{ paddingTop: 48 }}>
            <a href="https://sherpaswealth.com" style={{ display: "flex", alignItems: "center", gap: 12, textDecoration: "none" }}>
              <img src="/static/assets/sherpas-logo.png" alt="Sherpas" style={{ height: 24, width: "auto", filter: "invert(1) brightness(2)", display: "block" }} />
              <span style={{ width: 1, height: 18, background: "rgba(251,250,247,0.3)" }} />
              <span className="t-mono" style={{ fontSize: 12, color: "rgba(251,250,247,0.7)", letterSpacing: "0.18em", textTransform: "uppercase" }}>Labs</span>
            </a>
          </header>

          <div style={{ maxWidth: 520 }}>
            <div className="t-mono" style={{ fontSize: 11, color: "rgba(251,250,247,0.5)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 24 }}>§00 · Welcome</div>
            <h1 className="t-display-lg" style={{ margin: 0, color: "var(--bg)", fontWeight: 300, fontSize: 56, lineHeight: 1.0, letterSpacing: "-0.015em" }}>
              Working files.<br/>
              <span style={{ color: "rgba(251,250,247,0.55)" }}>Not yet public.</span>
            </h1>
            <p className="t-subhead" style={{ margin: "32px 0 0", color: "rgba(251,250,247,0.7)", fontStyle: "italic", maxWidth: 460 }}>
              A glimpse at what's next — grounded in the work we're shipping right now.
            </p>
          </div>

          <div />

          <footer className="t-mono" style={{ fontSize: 11, color: "rgba(251,250,247,0.4)", display: "flex", justifyContent: "space-between" }}>
            <span>labs.sherpaswealth.com</span>
            <span>v.2026.05 · build 0001</span>
          </footer>
        </aside>
      )}

      {/* RIGHT — form */}
      <section style={{
        padding: isMobile ? "48px 24px 64px" : "64px 72px",
        display: "flex", flexDirection: "column", justifyContent: "center",
        position: "relative", minHeight: "100vh",
      }}>
        {/* Mobile header */}
        {isMobile && (
          <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 48 }}>
            <img src="/static/assets/sherpas-logo.png" alt="Sherpas" style={{ height: 20, width: "auto", display: "block" }} />
            <span style={{ width: 1, height: 16, background: "var(--line-strong)" }} />
            <span className="t-mono" style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.18em", textTransform: "uppercase" }}>Labs</span>
          </div>
        )}

        {!isMobile && (
          <div className="t-mono" style={{ position: "absolute", top: 32, right: 72, fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.18em", textTransform: "uppercase" }}>
            ↗ &nbsp; <a href="https://sherpaswealth.com" style={{ color: "inherit" }}>sherpaswealth.com</a>
          </div>
        )}

        <div style={{ maxWidth: 420, width: "100%", margin: "0 auto" }}>
          <div className="t-eyebrow" style={{ marginBottom: 16 }}>Sign in</div>
          <h2 className="t-display-md" style={{ margin: 0, fontWeight: 400, fontSize: isMobile ? 32 : 44 }}>Open the file room.</h2>
          <p className="t-body" style={{ marginTop: 14, color: "var(--ink-2)", fontSize: isMobile ? 15 : 16 }}>
            Sherpas team uses Google. Design partners sign in with the credentials we issued.
          </p>

          {errorMsg && (
            <div className="t-mono" style={{ marginTop: 20, padding: "12px 16px", background: "var(--bg-tinted)", borderLeft: "2px solid var(--accent)", fontSize: 13, color: "var(--ink-2)" }}>
              {errorMsg}
            </div>
          )}

          {/* Google button */}
          <button onClick={onGoogle} style={{
            marginTop: 28, width: "100%",
            display: "flex", alignItems: "center", justifyContent: "center", gap: 12,
            padding: "16px 20px",
            background: "var(--ink)", color: "var(--bg)", border: "none",
            fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.06em",
            cursor: "pointer", borderRadius: 2,
          }}>
            <GoogleGlyph />
            <span>Continue with Google</span>
          </button>
          <div className="t-mono" style={{ fontSize: 10, color: "var(--ink-3)", marginTop: 8, letterSpacing: "0.14em", textTransform: "uppercase", textAlign: "center" }}>
            Sherpas team · @sherpaswealth.com only
          </div>

          {/* Divider */}
          <div style={{ display: "flex", alignItems: "center", gap: 16, margin: "28px 0 20px" }}>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
            <div className="t-mono" style={{ fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.22em", textTransform: "uppercase" }}>or, design partners</div>
            <div style={{ flex: 1, height: 1, background: "var(--line)" }} />
          </div>

          {/* Partner form */}
          <form onSubmit={onPartnerSubmit}>
            <Field label="Work email" type="email" value={partnerEmail} onChange={setPartnerEmail} placeholder="jane@cohenwealth.com" autoComplete="email" />
            <div style={{ marginTop: 20 }}>
              <Field label="Password" type="password" value={partnerPassword} onChange={setPartnerPassword} placeholder="••••••••••" autoComplete="current-password" />
            </div>
            {partnerError && (
              <div className="t-mono" style={{ fontSize: 12, color: "var(--accent)", marginTop: 10 }}>{partnerError}</div>
            )}
            <button type="submit" disabled={partnerLoading || !partnerEmail || !partnerPassword} style={{
              marginTop: 24, width: "100%", padding: "16px 20px",
              background: "var(--accent)", color: "var(--bg)", border: "none",
              fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.14em", textTransform: "uppercase",
              cursor: (partnerLoading || !partnerEmail || !partnerPassword) ? "default" : "pointer",
              opacity: (partnerLoading || !partnerEmail || !partnerPassword) ? 0.5 : 1, borderRadius: 2,
            }}>
              {partnerLoading ? "Signing in…" : "Sign in"}
            </button>
          </form>

          {/* Request access */}
          <div style={{ marginTop: 32, padding: "18px 20px", border: "1px solid var(--line)", background: "var(--bg-tinted)", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
            <div>
              <div className="t-mono" style={{ fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 3 }}>Not on the list?</div>
              <div style={{ fontSize: 13, color: "var(--ink-2)" }}>Request access — we read every one.</div>
            </div>
            <button onClick={() => setRequesting(true)} className="t-mono" style={{
              background: "transparent", border: "1px solid var(--ink)", color: "var(--ink)",
              padding: "9px 16px", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase",
              cursor: "pointer", borderRadius: 2, fontFamily: "var(--font-mono)", whiteSpace: "nowrap",
            }}>
              Request access →
            </button>
          </div>

          <div className="t-mono" style={{ fontSize: 11, color: "var(--ink-3)", letterSpacing: "0.04em", marginTop: 24, textAlign: "center" }}>
            By signing in you agree to Sherpas Labs access terms.
          </div>
        </div>
      </section>

      {requesting && <RequestAccessModal onClose={() => setRequesting(false)} />}
      {changePasswordUser && <ChangePasswordModal user={changePasswordUser} onDone={() => { window.location.href = "/index"; }} />}
    </div>
  );
};

// --- Google G glyph ---
const GoogleGlyph = () => (
  React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24" },
    React.createElement("path", { fill: "#4285F4", d: "M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" }),
    React.createElement("path", { fill: "#34A853", d: "M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" }),
    React.createElement("path", { fill: "#FBBC05", d: "M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" }),
    React.createElement("path", { fill: "#EA4335", d: "M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" })
  )
);

// --- Underline field ---
const Field = ({ label, type, value, onChange, placeholder, autoComplete }) => {
  const [focus, setFocus] = React.useState(false);
  return (
    <div>
      <label className="t-mono" style={{ display: "block", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 10 }}>
        {label}
      </label>
      <input
        type={type} value={value} onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder} autoComplete={autoComplete}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{
          width: "100%", border: "none", outline: "none",
          borderBottom: `1px solid ${focus ? "var(--ink)" : "var(--line-strong)"}`,
          padding: "10px 0", fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--ink)",
          background: "transparent", transition: "border-color 0.15s", boxSizing: "border-box",
        }}
      />
    </div>
  );
};

// --- Change password modal ---
const ChangePasswordModal = ({ user, onDone }) => {
  const [newPw, setNewPw] = React.useState("");
  const [confirmPw, setConfirmPw] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");

  const onSubmit = async (e) => {
    e.preventDefault();
    if (newPw.length < 8) { setErr("Password must be at least 8 characters."); return; }
    if (newPw !== confirmPw) { setErr("Passwords don't match."); return; }
    setLoading(true); setErr("");
    try {
      const res = await fetch("/auth/partner/change-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: user.email, current_password: user.tempPassword, new_password: newPw }),
        credentials: "include",
      });
      const data = await res.json();
      if (!res.ok) { setErr(data.detail || "Something went wrong."); return; }
      document.cookie = `sherpas_labs_session=${data.session_token}; path=/; SameSite=Lax`;
      onDone();
    } catch (e) {
      setErr("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(20,21,19,0.7)", backdropFilter: "blur(6px)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 200, padding: 24 }}>
      <div style={{ background: "var(--bg)", maxWidth: 480, width: "100%", padding: 40, border: "1px solid var(--line-strong)" }}>
        <div className="t-mono" style={{ fontSize: 11, color: "var(--accent)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 20 }}>● First login</div>
        <h3 style={{ fontFamily: "var(--font-serif)", fontSize: 26, fontWeight: 400, color: "var(--ink)", margin: "0 0 12px" }}>Set your password.</h3>
        <p style={{ fontSize: 15, color: "var(--ink-2)", margin: "0 0 28px" }}>Choose a password you'll use going forward. At least 8 characters.</p>
        {err && <div className="t-mono" style={{ fontSize: 12, color: "var(--accent)", marginBottom: 16 }}>{err}</div>}
        <form onSubmit={onSubmit}>
          <Field label="New password" type="password" value={newPw} onChange={setNewPw} placeholder="••••••••••" autoComplete="new-password" />
          <div style={{ marginTop: 20 }}>
            <Field label="Confirm password" type="password" value={confirmPw} onChange={setConfirmPw} placeholder="••••••••••" autoComplete="new-password" />
          </div>
          <button type="submit" disabled={loading || !newPw || !confirmPw} style={{
            marginTop: 28, width: "100%", padding: "16px 20px",
            background: "var(--ink)", color: "var(--bg)", border: "none",
            fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.14em", textTransform: "uppercase",
            cursor: (loading || !newPw || !confirmPw) ? "default" : "pointer",
            opacity: (loading || !newPw || !confirmPw) ? 0.5 : 1, borderRadius: 2,
          }}>{loading ? "Saving…" : "Set password & enter"}</button>
        </form>
      </div>
    </div>
  );
};

// --- Request access modal ---
const RequestAccessModal = ({ onClose }) => {
  const [sent, setSent] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [form, setForm] = React.useState({ name: "", company: "", email: "", role: "", reason: "" });
  const [err, setErr] = React.useState("");
  const set = (k) => (v) => setForm((f) => ({ ...f, [k]: v }));

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email) { setErr("Name and email are required."); return; }
    setLoading(true); setErr("");
    try {
      const res = await fetch("/api/access-request", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: form.name, email: form.email, company: form.company, role: form.role, reason: form.reason }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.detail || "Request failed");
      setSent(true);
    } catch (e) {
      setErr(e.message || "Something went wrong.");
    } finally { setLoading(false); }
  };

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(20,21,19,0.6)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 100, padding: 24 }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--bg)", maxWidth: 500, width: "100%", padding: 36, border: "1px solid var(--line-strong)", position: "relative" }}>
        <button onClick={onClose} style={{ position: "absolute", top: 14, right: 14, background: "transparent", border: "none", cursor: "pointer", fontSize: 20, color: "var(--ink-2)", fontFamily: "var(--font-mono)" }}>×</button>
        {!sent ? (
          <>
            <div className="t-eyebrow" style={{ marginBottom: 14 }}>Request access</div>
            <h3 style={{ fontFamily: "var(--font-serif)", fontSize: 28, fontWeight: 400, margin: "0 0 12px" }}>Tell us who you are.</h3>
            <p style={{ fontSize: 15, color: "var(--ink-2)", margin: "0 0 28px" }}>We read every request carefully, one at a time.</p>
            {err && <div className="t-mono" style={{ fontSize: 12, color: "var(--accent)", marginBottom: 14 }}>{err}</div>}
            <form onSubmit={onSubmit}>
              <Field label="Name *" type="text" value={form.name} onChange={set("name")} placeholder="Jane Cohen" autoComplete="name" />
              <div style={{ marginTop: 18 }}><Field label="Firm" type="text" value={form.company} onChange={set("company")} placeholder="Cohen Wealth Partners" autoComplete="organization" /></div>
              <div style={{ marginTop: 18 }}><Field label="Work email *" type="email" value={form.email} onChange={set("email")} placeholder="jane@cohenwealth.com" autoComplete="email" /></div>
              <div style={{ marginTop: 18 }}><Field label="Role" type="text" value={form.role} onChange={set("role")} placeholder="Partner, CIO, VP…" autoComplete="off" /></div>
              <div style={{ marginTop: 18 }}>
                <label className="t-mono" style={{ display: "block", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 10 }}>What do you want access to?</label>
                <textarea value={form.reason} onChange={(e) => set("reason")(e.target.value)} placeholder="A quick note on which projects and why."
                  style={{ width: "100%", border: "none", borderBottom: "1px solid var(--line-strong)", outline: "none", padding: "10px 0", fontFamily: "var(--font-mono)", fontSize: 14, color: "var(--ink)", background: "transparent", minHeight: 72, resize: "vertical", boxSizing: "border-box" }} />
              </div>
              <button type="submit" disabled={loading} style={{ marginTop: 28, width: "100%", padding: "14px 20px", background: loading ? "var(--ink-3)" : "var(--accent)", color: "var(--bg)", border: "none", fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.14em", textTransform: "uppercase", cursor: loading ? "default" : "pointer", borderRadius: 2 }}>
                {loading ? "Sending…" : "Submit request"}
              </button>
            </form>
          </>
        ) : (
          <div style={{ textAlign: "center", padding: "28px 0" }}>
            <div className="t-mono" style={{ fontSize: 11, color: "var(--accent)", letterSpacing: "0.18em", textTransform: "uppercase", marginBottom: 14 }}>● Filed</div>
            <h3 style={{ fontFamily: "var(--font-serif)", fontSize: 28, fontWeight: 400, margin: "0 0 12px" }}>Request received.</h3>
            <p style={{ fontSize: 15, color: "var(--ink-2)" }}>Someone from the team will read it and reply personally.</p>
            <button onClick={onClose} style={{ marginTop: 28, padding: "10px 24px", border: "1px solid var(--ink)", background: "transparent", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", cursor: "pointer", borderRadius: 2 }}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
};
