/* global React, Icons */
// Login modal — gates the app behind a branded sign-in screen.
const AuthLogo = ({ size = 40 }) => (
  <svg width={size} height={size} viewBox="0 0 40 40" fill="none">
    <rect width="40" height="40" rx="11" fill="#c6e84b" />
    <path d="M11 10 H29 V16 H17 V30 H11 Z" fill="#2d3122" />
    <path d="M29 30 V12 H23 V24 H13 V30 Z" fill="#3c4032" />
  </svg>
);

const GoogleMark = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 48 48">
    <path fill="#4285F4" d="M45 24c0-1.6-.1-2.8-.4-4H24v7.6h12c-.2 2-1.6 5-4.6 7l7 5.4C42.8 42.6 45 34 45 24Z" />
    <path fill="#34A853" d="M24 46c6 0 11-2 14.6-5.3l-7-5.4c-2 1.3-4.6 2.1-7.6 2.1-5.8 0-10.8-3.9-12.5-9.2l-7.3 5.6C7.9 41 15.3 46 24 46Z" />
    <path fill="#FBBC05" d="M11.5 28.2c-.5-1.3-.7-2.7-.7-4.2s.3-2.9.7-4.2l-7.3-5.6C2.8 17 2 20.4 2 24s.8 7 2.2 9.8l7.3-5.6Z" />
    <path fill="#EA4335" d="M24 10.7c3.3 0 6.2 1.1 8.5 3.3l6.3-6.3C35 4 30 2 24 2 15.3 2 7.9 7 4.2 14.2l7.3 5.6C13.2 14.6 18.2 10.7 24 10.7Z" />
  </svg>
);

function AuthField({ icon: Ico, type = "text", value, onChange, placeholder, autoFocus, trailing }) {
  const { useState } = React;
  const [focus, setFocus] = React.useState(false);
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 11, height: 52, padding: "0 14px", borderRadius: 14,
      background: "#fff", border: `1.5px solid ${focus ? "var(--lime-deep)" : "rgba(0,0,0,0.10)"}`,
      boxShadow: focus ? "0 0 0 4px rgba(180,221,47,0.18)" : "none", transition: "border .15s ease, box-shadow .15s ease" }}>
      <span style={{ color: focus ? "var(--ink-2)" : "var(--muted)", flex: "none", display: "flex" }}><Ico size={19} /></span>
      <input value={value} onChange={onChange} type={type} placeholder={placeholder} autoFocus={autoFocus}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontFamily: "Onest",
          fontSize: 15, color: "var(--ink)", minWidth: 0 }} />
      {trailing}
    </div>
  );
}

function LoginModal({ onAuthed }) {
  const [mode, setMode] = React.useState("signin"); // "signin" | "signup"
  const [email, setEmail] = React.useState("");
  const [pwd, setPwd] = React.useState("");
  const [name, setName] = React.useState("");
  const [show, setShow] = React.useState(false);
  const [remember, setRemember] = React.useState(true);
  const [err, setErr] = React.useState("");
  const [info, setInfo] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const sb = window.supabaseClient;

  const handleSignIn = async (e) => {
    e.preventDefault();
    if (!email.trim() || !pwd.trim()) { setErr("Ingresa tu correo y contraseña para continuar."); return; }
    setErr(""); setBusy(true);
    const { error } = await sb.auth.signInWithPassword({ email: email.trim(), password: pwd });
    setBusy(false);
    if (error) { setErr(error.message); return; }
    // Normally onAuthed fires from app.jsx via onAuthStateChange, but the
    // demo/offline stub client never emits that event — call it directly
    // so sign-in works after a logout in demo mode too.
    if (window.__PAMPA_DEMO__) onAuthed();
  };

  const handleSignUp = async (e) => {
    e.preventDefault();
    if (!email.trim() || !pwd.trim()) { setErr("Completá todos los campos."); return; }
    if (pwd.length < 6) { setErr("La contraseña debe tener al menos 6 caracteres."); return; }
    setErr(""); setBusy(true);
    const { error } = await sb.auth.signUp({
      email: email.trim(),
      password: pwd,
      options: {
        emailRedirectTo: window.location.origin,
        data: { full_name: name.trim() || email.split("@")[0] },
      },
    });
    setBusy(false);
    if (error) { setErr(error.message); return; }
    setInfo("¡Listo! Revisá tu correo para confirmar tu cuenta.");
  };

  const handleGoogle = async () => {
    setErr(""); setBusy(true);
    const { error } = await sb.auth.signInWithOAuth({
      provider: "google",
      options: {
        redirectTo: (window.campoAuthRedirect && window.campoAuthRedirect()) || (window.location.origin + "/"),
        queryParams: { prompt: "select_account" },
      },
    });
    if (error) { setErr(error.message); setBusy(false); return; }
    // Real Google OAuth redirects the whole page (app.jsx picks it up via
    // onAuthStateChange on return); the demo stub never redirects or fires
    // that event, so log the demo session in directly here.
    if (window.__PAMPA_DEMO__) { setBusy(false); onAuthed(); }
  };

  const isSignUp = mode === "signup";

  return (
    <div style={{ position: "absolute", inset: 0, zIndex: 1000, display: "flex", alignItems: "center", justifyContent: "center" }}>
      {/* backdrop */}
      <div style={{ position: "absolute", inset: 0, background: "rgba(22,28,12,0.55)",
        backdropFilter: "blur(7px) saturate(1.05)", WebkitBackdropFilter: "blur(7px) saturate(1.05)" }} />

      {/* card */}
      <div style={{ position: "relative", width: 884, borderRadius: 28, overflow: "hidden",
        display: "flex", boxShadow: "0 50px 110px -40px rgba(20,30,10,0.75)" }}>

        {/* ── left brand panel ── */}
        <div style={{ width: 360, flex: "none", position: "relative", background: "var(--olive-darker)",
          color: "#f2f3ea", padding: "40px 36px", display: "flex", flexDirection: "column", overflow: "hidden", minHeight: 568 }}>
          <div style={{ position: "absolute", right: -70, top: -70, width: 240, height: 240, borderRadius: 999,
            background: "radial-gradient(circle, rgba(198,232,75,0.22), transparent 68%)" }} />
          <div style={{ position: "absolute", left: -90, bottom: -110, width: 260, height: 260, borderRadius: 999,
            background: "radial-gradient(circle, rgba(198,232,75,0.10), transparent 70%)" }} />

          <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 11 }}>
            <AuthLogo size={38} />
            <span style={{ fontSize: 21, fontWeight: 700, letterSpacing: "-0.02em" }}>Pampa Go</span>
          </div>

          <div style={{ position: "relative", marginTop: "auto" }}>
            <div style={{ fontSize: 30, fontWeight: 800, lineHeight: 1.12, letterSpacing: "-0.02em" }}>
              Tu finca,<br />bajo control<br /><span style={{ color: "var(--lime)" }}>inteligente.</span>
            </div>
            <div style={{ fontSize: 14, color: "rgba(255,255,255,0.66)", marginTop: 14, lineHeight: 1.5, maxWidth: 260 }}>
              NDVI, riego, plagas e inventario de tus lotes en la Pampa argentina, en un solo lugar.
            </div>
          </div>

          <div style={{ position: "relative", display: "flex", gap: 22, marginTop: 30, paddingTop: 22, borderTop: "1px solid rgba(255,255,255,0.12)" }}>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: "var(--lime)", lineHeight: 1, whiteSpace: "nowrap" }}>960<span style={{ fontSize: 13 }}> ha</span></div>
              <div style={{ fontSize: 11.5, color: "rgba(255,255,255,0.6)", marginTop: 4 }}>cultivadas</div>
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: "var(--lime)", lineHeight: 1 }}>0,60</div>
              <div style={{ fontSize: 11.5, color: "rgba(255,255,255,0.6)", marginTop: 4 }}>NDVI medio</div>
            </div>
            <div>
              <div style={{ fontSize: 22, fontWeight: 800, color: "var(--lime)", lineHeight: 1 }}>8</div>
              <div style={{ fontSize: 11.5, color: "rgba(255,255,255,0.6)", marginTop: 4 }}>campos</div>
            </div>
          </div>
        </div>

        {/* ── right form panel ── */}
        <div style={{ flex: 1, background: "var(--cream)", padding: "44px 48px", display: "flex", flexDirection: "column", justifyContent: "center" }}>
          <div style={{ fontSize: 26, fontWeight: 800, letterSpacing: "-0.02em" }}>
            {isSignUp ? "Crear cuenta" : "Iniciar sesión"}
          </div>
          <div style={{ fontSize: 14.5, color: "var(--muted)", marginTop: 6 }}>
            {isSignUp ? "Completá tus datos para registrarte." : "Bienvenido de nuevo. Accede a tu panel."}
          </div>

          {!isSignUp && (
            <button onClick={handleGoogle} disabled={busy}
              style={{ marginTop: 24, height: 50, borderRadius: 14, border: "1.5px solid rgba(0,0,0,0.10)",
                background: "#fff", display: "flex", alignItems: "center", justifyContent: "center", gap: 11, cursor: "pointer",
                fontFamily: "Onest", fontSize: 14.5, fontWeight: 600, color: "var(--ink)", transition: "background .15s ease",
                opacity: busy ? 0.6 : 1 }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "#f3f3eb")}
              onMouseLeave={(e) => (e.currentTarget.style.background = "#fff")}>
              <GoogleMark /> Continuar con Google
            </button>
          )}

          {!isSignUp && (
            <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "20px 0 18px" }}>
              <div style={{ flex: 1, height: 1, background: "rgba(0,0,0,0.10)" }} />
              <span style={{ fontSize: 12, color: "var(--muted-2)", fontWeight: 600, whiteSpace: "nowrap" }}>o con tu correo</span>
              <div style={{ flex: 1, height: 1, background: "rgba(0,0,0,0.10)" }} />
            </div>
          )}

          {isSignUp && <div style={{ marginTop: 24 }} />}

          {info ? (
            <div style={{ background: "rgba(198,232,75,0.18)", border: "1.5px solid var(--lime-deep)", borderRadius: 14,
              padding: "16px 20px", fontSize: 14, color: "var(--ink-2)", lineHeight: 1.5, marginBottom: 16 }}>
              {info}
            </div>
          ) : (
            <form onSubmit={isSignUp ? handleSignUp : handleSignIn} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              {isSignUp && (
                <AuthField icon={Icons.user} type="text" value={name} onChange={(e) => setName(e.target.value)}
                  placeholder="Tu nombre completo" autoFocus />
              )}
              <AuthField icon={Icons.mail} type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                placeholder="tucorreo@finca.com" autoFocus={!isSignUp} />
              <AuthField icon={Icons.lock} type={show ? "text" : "password"} value={pwd} onChange={(e) => setPwd(e.target.value)}
                placeholder="Contraseña"
                trailing={
                  <button type="button" onClick={() => setShow((s) => !s)} aria-label="Mostrar contraseña"
                    style={{ border: "none", background: "transparent", color: "var(--muted)", cursor: "pointer", display: "flex", padding: 2 }}>
                    {show ? <Icons.eyeOff size={19} /> : <Icons.eye size={19} />}
                  </button>
                } />

              {err && <div style={{ fontSize: 12.5, color: "#c0492f", fontWeight: 600, marginTop: -2 }}>{err}</div>}

              {!isSignUp && (
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "2px 0 4px" }}>
                  <label style={{ display: "flex", alignItems: "center", gap: 9, cursor: "pointer", userSelect: "none" }} onClick={() => setRemember((r) => !r)}>
                    <span style={{ width: 20, height: 20, borderRadius: 6, flex: "none", display: "flex", alignItems: "center", justifyContent: "center",
                      background: remember ? "var(--lime)" : "#fff", border: `1.5px solid ${remember ? "var(--lime-deep)" : "rgba(0,0,0,0.18)"}`,
                      color: "var(--ink)", transition: "all .15s ease" }}>
                      {remember && <Icons.check size={14} />}
                    </span>
                    <span style={{ fontSize: 13.5, color: "var(--ink-2)", whiteSpace: "nowrap" }}>Recordarme</span>
                  </label>
                  <span style={{ fontSize: 13.5, color: "var(--ink-2)", fontWeight: 600, cursor: "pointer",
                    textDecoration: "underline", textUnderlineOffset: 3, whiteSpace: "nowrap" }}>
                    ¿Olvidaste tu contraseña?
                  </span>
                </div>
              )}

              <button type="submit" className="btn-lime" disabled={busy}
                style={{ height: 52, borderRadius: 14, fontSize: 15.5, display: "flex", alignItems: "center",
                  justifyContent: "center", gap: 9, opacity: busy ? 0.7 : 1 }}>
                {busy ? "Procesando…" : isSignUp
                  ? <React.Fragment>Crear cuenta <Icons.arrowRight size={18} /></React.Fragment>
                  : <React.Fragment>Entrar <Icons.arrowRight size={18} /></React.Fragment>}
              </button>
            </form>
          )}

          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginTop: 22, fontSize: 13.5, whiteSpace: "nowrap" }}>
            {isSignUp ? (
              <React.Fragment>
                <span style={{ color: "var(--muted)" }}>¿Ya tenés cuenta?</span>
                <span onClick={() => { setMode("signin"); setErr(""); setInfo(""); }}
                  style={{ color: "var(--ink)", fontWeight: 700, cursor: "pointer" }}>Iniciar sesión</span>
              </React.Fragment>
            ) : (
              <React.Fragment>
                <span style={{ color: "var(--muted)" }}>¿No tenés cuenta?</span>
                <span onClick={() => { setMode("signup"); setErr(""); setInfo(""); }}
                  style={{ color: "var(--ink)", fontWeight: 700, cursor: "pointer" }}>Crear una</span>
              </React.Fragment>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.LoginModal = LoginModal;