/* global React, CampusAuth, BrandLogo, Icons, Button, Input, FormCtl, Card, Heading, Text, Divider, Checkbox, Alert, navigate, DATA */

// Real accounts (Supabase Auth).
// `enrollCourse`: reached from a course's "Crear cuenta e inscribirme" (#/registro/<courseId>);
// the account is enrolled on its first sign-in and taken to the first page of that course.
const LoginPage = ({ next, initialTab = "login", enrollCourse }) => {
  const [tab, setTab] = React.useState(initialTab);
  React.useEffect(() => setTab(initialTab), [initialTab]);
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [pwd, setPwd] = React.useState("");
  const [showPwd, setShowPwd] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");
  const [notice, setNotice] = React.useState("");
  React.useEffect(() => { setError(""); setNotice(""); }, [tab]);

  const course = enrollCourse && DATA.COURSES.find(c => c.id === enrollCourse && c.units);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (busy) return;
    setError(""); setNotice("");
    if (tab === "signup" && name.trim().length < 2) return setError("Escribe tu nombre completo.");
    if (pwd.length < 8) return setError("La contraseña debe tener al menos 8 caracteres.");
    setBusy(true);
    if (course) CampusAuth.rememberEnrollment(course.id);
    const res = tab === "login"
      ? await CampusAuth.signIn(email.trim(), pwd)
      : await CampusAuth.signUp(email.trim(), pwd, name.trim());
    setBusy(false);
    if (res.error) return setError(res.error);
    if (res.needsConfirmation) {
      setTab("login");
      setTimeout(() => setNotice(`Te hemos enviado un email a ${email.trim()}. Confirma tu cuenta desde el enlace y vuelve aquí para entrar${course ? `: quedarás inscrito en «${course.title}»` : ""}.`), 0);
      return;
    }
    if (course) return navigate(window.itemHref(course, window.nextItem(course)));
    if (!next) navigate("#/mi-espacio"); // with `next`, the router re-renders the private page once signed in
  };

  const forgot = async () => {
    setError(""); setNotice("");
    if (!email.trim()) return setError("Escribe tu email y vuelve a pulsar «¿Olvidaste tu contraseña?».");
    const res = await CampusAuth.resetPassword(email.trim());
    if (res.error) setError(res.error);
    else setNotice(`Si existe una cuenta con ${email.trim()}, recibirás un email para restablecer la contraseña.`);
  };

  return (
    <div data-screen-label="01 Login" style={{
      minHeight: "100vh",
      display: "grid",
      gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.1fr)",
      background: "var(--bg)",
    }}>
      {/* Left: form */}
      <div style={{ display: "flex", flexDirection: "column", padding: "32px 48px", minHeight: "100vh" }}>
        <a href="#/cursos" style={{ display: "inline-flex", alignSelf: "flex-start" }}>
          <BrandLogo size={30} />
        </a>

        <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center" }}>
          <div style={{ width: "100%", maxWidth: 380 }}>
            <span className="page-eyebrow">Campus virtual</span>
            <Heading size="h2" className="mb-2">
              {tab === "login" ? "Iniciar sesión" : "Crear cuenta"}
            </Heading>
            <Text muted className="mb-6">
              {tab === "login"
                ? "Continúa tu formación en derechos humanos, seguridad humana y construcción de paz."
                : "Únete a más de 18,000 estudiantes formándose en seguridad humana."}
            </Text>

            {course && (
              <div className="login-course">
                <Icons.Book size={16} />
                <span>{tab === "signup" ? "Crea tu cuenta para inscribirte en" : "Entra para continuar con"} <strong>{course.title}</strong></span>
              </div>
            )}
            {error && <Alert variant="contrast" className="mb-4" icon={<Icons.Flag size={16} />}>{error}</Alert>}
            {notice && <Alert className="mb-4" icon={<Icons.Mail size={16} />}>{notice}</Alert>}

            <form className="flex-col gap-4" onSubmit={onSubmit}>
              {tab === "signup" && (
                <FormCtl label="Nombre completo" required>
                  <Input placeholder="Nombre y apellidos" autoComplete="name" required
                         value={name} onChange={e => setName(e.target.value)} />
                </FormCtl>
              )}
              <FormCtl label="Email institucional" required>
                <Input
                  leading={<Icons.Mail size={16} style={{ color: "var(--text-subtle)" }} />}
                  type="email" placeholder="nombre@organizacion.org" required
                  value={email} onChange={e => setEmail(e.target.value)}
                  autoComplete="email"
                />
              </FormCtl>
              <FormCtl label="Contraseña" required>
                <Input
                  leading={<Icons.Lock size={16} style={{ color: "var(--text-subtle)" }} />}
                  trailing={
                    <button type="button" onClick={() => setShowPwd(s => !s)}
                      style={{ background: "none", border: "none", color: "var(--text-muted)", cursor: "pointer", padding: 0 }}>
                      <Icons.Eye size={16} />
                    </button>
                  }
                  type={showPwd ? "text" : "password"} placeholder="Mínimo 8 caracteres" required minLength={8}
                  autoComplete={tab === "login" ? "current-password" : "new-password"}
                  value={pwd} onChange={e => setPwd(e.target.value)}
                />
              </FormCtl>

              {tab === "login" && (
                <div className="flex items-center justify-end">
                  <Button type="button" variant="link" onClick={forgot}>¿Olvidaste tu contraseña?</Button>
                </div>
              )}

              <Button type="submit" size="lg" block disabled={busy} iconRight={busy ? null : <Icons.ArrowRight size={16} />}>
                {busy ? "Un momento…" : tab === "login" ? "Entrar al campus" : "Crear mi cuenta"}
              </Button>
            </form>

            <Text size="sm" muted className="text-center mt-6">
              {tab === "login" ? "¿Aún no tienes cuenta? " : "¿Ya tienes cuenta? "}
              <a onClick={() => setTab(tab === "login" ? "signup" : "login")}
                 style={{ color: "var(--bh-ocean)", fontWeight: 500, cursor: "pointer", textDecoration: "underline", textUnderlineOffset: 4 }}>
                {tab === "login" ? "Crear cuenta gratis" : "Iniciar sesión"}
              </a>
            </Text>

            <div className="flex items-center gap-3 mt-6">
              <Divider />
              <Text size="xs" muted>o</Text>
              <Divider />
            </div>
            <Button as="a" href="#/cursos" variant="ghost" block className="mt-4" iconRight={<Icons.ArrowRight size={16} />}>
              Explorar el catálogo sin cuenta
            </Button>
          </div>
        </div>

        <Text size="xs" subtle>
          © 2026 Blue Human · ONG de Seguridad Humana, DDHH y Paz Internacional.
        </Text>
      </div>

      {/* Right: visual */}
      <div style={{
        position: "relative",
        backgroundImage: `linear-gradient(180deg, rgba(10,30,51,0.55), rgba(10,30,51,0.94)), url(${DATA.PHOTOS.field})`,
        backgroundSize: "cover", backgroundPosition: "center",
        color: "#fff",
        display: "flex", flexDirection: "column", justifyContent: "flex-end",
        padding: "48px",
      }}>
        <div style={{
          position: "absolute", top: 32, right: 32,
          display: "flex", gap: 8, alignItems: "center",
          background: "rgba(10,30,51,0.6)",
          padding: "8px 14px", borderRadius: "var(--r-full)", border: "1px solid rgba(255,255,255,0.25)",
          fontSize: 12, fontWeight: 500,
        }}>

          Acreditados por el Instituto de DDHH de La Haya
        </div>

        <div style={{ maxWidth: 520 }}>
          <Text size="xs" style={{ color: "rgba(255,255,255,0.75)", fontWeight: 600, marginBottom: 14 }}>
            Formación · Investigación · Acción
          </Text>
          <h1 style={{
            fontFamily: "var(--font-display)",
            fontSize: 44, lineHeight: 1.08, fontWeight: 400,
            margin: "0 0 18px", letterSpacing: "-0.025em",
          }}>
            «Defender los derechos humanos es construir paz. Aquí entrenamos a quienes lo hacen.»
          </h1>
          <Text size="sm" style={{ color: "rgba(255,255,255,0.85)" }}>
            — Dra. Amina Khoury, Directora académica
          </Text>

          <div style={{
            marginTop: 36, display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
            gap: 24, paddingTop: 24, borderTop: "1px solid rgba(255,255,255,0.16)",
          }}>
            {[
              ["18,420", "estudiantes activos"],
              ["64", "cursos especializados"],
              ["31", "países"],
            ].map(([v, l]) => (
              <div key={l}>
                <div style={{ fontSize: 34, fontWeight: 500, fontFamily: "var(--font-display)", letterSpacing: "-0.03em", lineHeight: 1 }}>{v}</div>
                <div style={{ fontSize: 12, color: "rgba(255,255,255,0.75)" }}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

const GoogleIcon = () => (
  <svg width="16" height="16" viewBox="0 0 24 24">
    <path fill="#4285F4" d="M22.5 12.3c0-.8-.1-1.5-.2-2.2H12v4.2h5.9a5 5 0 0 1-2.2 3.3v2.7h3.6c2.1-2 3.3-4.8 3.3-8Z"/>
    <path fill="#34A853" d="M12 23c2.9 0 5.4-1 7.2-2.6l-3.5-2.7c-1 .7-2.2 1.1-3.7 1.1-2.8 0-5.3-1.9-6.1-4.5H2.3v2.8C4 20.4 7.7 23 12 23Z"/>
    <path fill="#FBBC05" d="M5.9 14.3a6.7 6.7 0 0 1 0-4.6V6.9H2.3a11 11 0 0 0 0 10.2l3.6-2.8Z"/>
    <path fill="#EA4335" d="M12 5.4c1.5 0 3 .5 4.1 1.6l3-3A11 11 0 0 0 12 1C7.7 1 4 3.6 2.3 7l3.6 2.8C6.7 7.3 9.2 5.4 12 5.4Z"/>
  </svg>
);

window.LoginPage = LoginPage;
