const LoginScreen = () => {
  const { authProfiles, login, busy, errorMessage } = useAinaApp();
  const [who, setWho] = React.useState("");
  const [pwd, setPwd] = React.useState("");
  const [shake, setShake] = React.useState(false);
  const [localError, setLocalError] = React.useState("");

  const submit = async () => {
    if (!who) {
      setLocalError("Elige un perfil primero.");
      setShake(true);
      window.setTimeout(() => setShake(false), 400);
      return;
    }

    if (!pwd.length) {
      setLocalError("Escribe la contraseña.");
      setShake(true);
      window.setTimeout(() => setShake(false), 400);
      return;
    }

    try {
      setLocalError("");
      await login(who, pwd);
    } catch (error) {
      setLocalError(error.message);
      setShake(true);
      window.setTimeout(() => setShake(false), 400);
    }
  };

  const visibleError = localError || errorMessage;

  return (
    <div
      style={{
        height: "100%",
        position: "relative",
        display: "flex",
        flexDirection: "column",
        padding: "90px 22px 34px"
      }}
    >
      <div style={{ textAlign: "center", marginBottom: 36 }}>
        <div
          style={{
            fontSize: 11,
            letterSpacing: "0.32em",
            textTransform: "uppercase",
            color: "rgba(255,255,255,0.55)",
            marginBottom: 14
          }}
        >
          · progreso compartido ·
        </div>
        <div
          className="serif"
          style={{
            fontSize: 56,
            lineHeight: 1,
            letterSpacing: "-0.02em",
            whiteSpace: "nowrap"
          }}
        >
          Aina<span style={{ color: "rgba(255,255,255,0.45)" }}> & </span>Victor
        </div>
        <div
          style={{
            marginTop: 18,
            fontSize: 14,
            color: "rgba(255,255,255,0.6)",
            lineHeight: 1.5
          }}
        >
          Un panel para los dos.
          <br />
          Cada uno con su propia cuenta real.
        </div>
      </div>

      {!who ? (
        <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 20 }}>
          {authProfiles.length ? (
            authProfiles.map((profile) => {
              const whoKey = getWhoForName(profile.name);
              return (
                <Glass
                  key={profile.id}
                  onClick={() => setWho(profile.id)}
                  padding={14}
                  radius={22}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 14,
                    paddingRight: 18
                  }}
                >
                  <Avatar who={whoKey} size={52} />
                  <div style={{ flex: 1 }}>
                    <div className="serif" style={{ fontSize: 24, lineHeight: 1 }}>
                      {profile.name}
                    </div>
                    <div style={{ fontSize: 12, color: "rgba(255,255,255,0.55)", marginTop: 4 }}>
                      Tu perfil personal
                    </div>
                  </div>
                  <I.Chev size={18} color="rgba(255,255,255,0.5)" />
                </Glass>
              );
            })
          ) : (
            <LoadingState title="Perfiles" body="Cargando perfiles reales..." />
          )}

          <div
            style={{
              marginTop: 18,
              textAlign: "center",
              fontSize: 12,
              color: "rgba(255,255,255,0.4)"
            }}
          >
            Cada perfil edita solo lo suyo.
            <br />
            Los dos veis el progreso del otro.
          </div>
        </div>
      ) : (
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 14,
            animation: shake ? "shake 0.4s" : "none"
          }}
        >
          <Glass padding={18}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 16 }}>
              <Avatar
                who={getWhoForName(authProfiles.find((profile) => profile.id === who)?.name)}
                size={48}
              />
              <div>
                <div className="serif" style={{ fontSize: 26, lineHeight: 1 }}>
                  {authProfiles.find((profile) => profile.id === who)?.name || who}
                </div>
                <button
                  onClick={() => {
                    setWho("");
                    setPwd("");
                    setLocalError("");
                  }}
                  style={{
                    marginTop: 4,
                    background: "none",
                    border: 0,
                    padding: 0,
                    color: "rgba(255,255,255,0.55)",
                    fontSize: 12,
                    cursor: "pointer"
                  }}
                >
                  ← cambiar perfil
                </button>
              </div>
            </div>

            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 10,
                padding: "12px 14px",
                borderRadius: 14,
                background: "rgba(0,0,0,0.25)",
                border: "0.5px solid rgba(255,255,255,0.1)"
              }}
            >
              <I.Lock size={16} color="rgba(255,255,255,0.5)" />
              <input
                type="password"
                placeholder="Contraseña"
                value={pwd}
                onChange={(event) => setPwd(event.target.value)}
                onKeyDown={(event) => event.key === "Enter" && submit()}
                style={{
                  flex: 1,
                  background: "transparent",
                  border: 0,
                  outline: "none",
                  color: "#fff",
                  fontSize: 16,
                  letterSpacing: "0.12em",
                  fontFamily: "inherit"
                }}
              />
            </div>
          </Glass>

          <PillBtn primary size="lg" onClick={submit} style={{ width: "100%", opacity: busy ? 0.7 : 1 }}>
            {busy ? "Entrando..." : "Entrar"}
          </PillBtn>

          {visibleError ? (
            <div
              style={{
                textAlign: "center",
                fontSize: 12,
                lineHeight: 1.45,
                color: "oklch(0.8 0.11 18)"
              }}
            >
              {visibleError}
            </div>
          ) : null}
        </div>
      )}

      <style>{`
        @keyframes shake {
          0%, 100% { transform: translateX(0); }
          25% { transform: translateX(-6px); }
          75% { transform: translateX(6px); }
        }
      `}</style>
    </div>
  );
};

window.LoginScreen = LoginScreen;
