Files
AgendaPro/src/pages/LoginPage.tsx
T
AgendaPro DevandClaude Opus 5 4c19244df9 feat: public landing page with magic login, brand palette and demo build flag
Adds a public funnel landing at `/` and moves the login to `/login`, rebuilt
around the panel's own colors instead of an invented palette.

Landing (`src/components/landing/`, one section per file, no props):
- Seven funnel sections composed by `LandingPage`. The hero's eight swatches are
  literally `PIE_COLORS` from `DashboardPage`, the same hex values the seed hands
  to avatars and services, so "your colors become your numbers" is literal.
- `BrandMark` becomes the single source for the logo, replicating
  `public/favicon.svg`. Blue is the action surface, orange only ever marks.
- `NotebookVisual` is the one deliberate exception to the palette: it is what the
  product replaces.
- Copy drops all system vocabulary; motion comes from `src/lib/motion.ts` with a
  single easing, and reduced-motion resolves `initial` to the final state so a
  never-firing `whileInView` cannot leave a section invisible forever.

Routing and bundle:
- `homePathFor` is the single definition of each role's destination.
- Landing, login, dashboard and calendar load lazily. Eager, the login dragged
  framer-motion (~40 KB gz) into every panel load and the landing downloaded
  recharts + FullCalendar (~187 KB gz) without charting anything. `clsx` is
  pinned to the `react` chunk because Rollup otherwise assigns it to `charts`,
  making the entry import 111 KB gz for a 200-byte utility.

Responsiveness (iPhone/iPad), verified with `npm run audit:responsive`:
- No touch form field below 16px, `dvh` height utilities, safe-area insets, and
  40px touch targets keyed off `pointer: coarse` rather than `sm:`.
- New `.ld-gutter`: `.safe-x` lives outside `@layer` and beats Tailwind's `px-*`,
  so it left the login's side padding at 0 on anything but an iPhone in
  landscape. No overflow check could see it — there was no overflow, just zero
  margin. The audit now guards it with a `gutter` check.
- `shell-height` no longer fires on pages that legitimately scroll; the static
  `raw-viewport-unit` scan covers those instead.

Production build:
- The Dockerfile now sets `VITE_DEMO_UI=1` as a build arg. `DEMO` is a build-time
  constant, so without it Vite eliminated the magic login and the "Ver como…"
  switcher: the deployed landing promised "no registration" and led to an empty
  form. Verified by building both ways and diffing the bundle.
- Service worker cache bumped to v2 so the orphaned pre-landing chunks get purged
  from returning visitors' caches.

Verified: typecheck clean; unit 39/39, e2e 33/33, admin 17/17, booking 12/12,
landing 13/13 (WebKit), PWA passed against the real production build.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-07-28 14:25:58 -06:00

311 lines
12 KiB
TypeScript

import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { AlertCircle, ArrowLeft, ArrowRight, Lock, Mail, Wand2 } from "lucide-react";
import { motion } from "framer-motion";
import { useAuth } from "../lib/auth";
import { api } from "../lib/api";
import { Spinner } from "../components/ui";
import { InstallAppPrompt } from "../components/InstallAppPrompt";
import { revealStagger, revealUp } from "../lib/motion";
import { useReducedMotion } from "../lib/useReducedMotion";
import { BrandMark } from "../components/BrandMark";
const DEMO = import.meta.env.DEV || import.meta.env.VITE_DEMO_UI === "1";
type DemoUser = { email: string; name: string; role: string; avatar_color: string };
/**
* Qué ve cada quien. Está escrito en el idioma del salón y no en el del sistema:
* quien entra a probar no sabe qué es un rol ni un tenant, pero sí sabe
* perfectamente quién hace qué en su negocio.
*
* Los rótulos no asumen género. No es un tecnicismo de estilo: la cuenta demo de
* empleado incluye a Carolina y a Diego, así que «tus muchachas» dejaba fuera a una
* de las dos tarjetas que la propia pantalla muestra debajo.
*/
const GRUPOS = [
{
role: "owner",
titulo: "Como quien manda",
detalle: "Ves todo: la agenda, las cuentas del día, tu gente y tus clientas.",
// Azul primario: es el camino principal, y comparte color con el CTA y la marca.
color: "var(--ld-azul)",
limite: 1,
},
{
role: "employee",
titulo: "Como alguien de tu equipo",
detalle: "Ve nomás su día y sus propias cuentas. Nada que configurar.",
color: "var(--ld-naranja)",
limite: 2,
},
{
role: "admin",
titulo: "Como quien lleva varios salones",
detalle: "Da de alta negocios y los ve todos juntos.",
color: "var(--ld-purpura)",
limite: 1,
},
] as const;
export function LoginPage() {
const { login, user } = useAuth();
const navigate = useNavigate();
const reduced = useReducedMotion();
const [email, setEmail] = useState(DEMO ? "[email protected]" : "");
const [password, setPassword] = useState(DEMO ? "demo1234" : "");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [pendiente, setPendiente] = useState<string | null>(null);
const [demoUsers, setDemoUsers] = useState<DemoUser[]>([]);
useEffect(() => {
if (user) navigate("/", { replace: true });
}, [user, navigate]);
useEffect(() => {
if (!DEMO) return;
api.auth
.demoUsers()
.then((r) => setDemoUsers(r.users))
.catch(() => {});
}, []);
const grupos = useMemo(
() =>
GRUPOS.map((g) => ({
...g,
cuentas: demoUsers.filter((u) => u.role === g.role).slice(0, g.limite),
})).filter((g) => g.cuentas.length > 0),
[demoUsers]
);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setLoading(true);
try {
await login(email, password);
navigate("/", { replace: true });
} catch (err: any) {
setError(err.message || "No pudimos iniciar sesión");
} finally {
setLoading(false);
}
};
// Acceso de un clic, solo demo. `DEMO` es una constante de build, así que esta rama
// entera —y con ella la contraseña— se elimina del bundle de producción por
// dead-code elimination. Por eso la contraseña vive aquí dentro y no arriba.
const quickLogin = DEMO
? async (mail: string) => {
setEmail(mail);
setPassword("demo1234");
setError(null);
setPendiente(mail);
setLoading(true);
try {
await login(mail, "demo1234");
navigate("/", { replace: true });
} catch (err: any) {
setError(err.message || "No pudimos iniciar sesión");
} finally {
setLoading(false);
setPendiente(null);
}
}
: undefined;
return (
<div className="landing relative min-h-screen-safe overflow-hidden">
<div
className="pointer-events-none absolute inset-0"
// Los mismos lavados del panel: brand-50 → orange-50 → el lienzo de la app.
// Entrar al producto desde aquí no debe sentirse como cambiar de sitio.
style={{ background: "linear-gradient(160deg, #eef4ff 0%, #fff7ed 55%, #f6f7fb 100%)" }}
/>
{/* `ld-gutter` en lugar de `safe-x px-5`: ver el comentario de la clase en
index.css — combinar las dos dejaba el padding lateral en 0. */}
<div className="safe-top ld-gutter relative mx-auto flex w-full max-w-5xl flex-col pb-12 pt-8 sm:pt-10">
<Link
to="/"
className="tap-target inline-flex w-fit items-center gap-2 text-[0.92rem] font-bold"
style={{ color: "var(--ld-muted)" }}
>
<ArrowLeft className="h-4 w-4" />
Volver
</Link>
<motion.div
className="mt-9 grid grid-cols-1 items-start gap-10 lg:mt-12 lg:grid-cols-[1.05fr_1fr] lg:gap-14"
initial="hidden"
animate="show"
variants={revealStagger(reduced)}
>
{/* ---- Columna izquierda: entrar de un clic ---- */}
<motion.div variants={revealUp(reduced)}>
<div className="flex items-center gap-2.5 text-[1.05rem] font-extrabold tracking-tight">
<BrandMark className="h-9 w-9" />
AgendaMax
</div>
<h1 className="ld-title mt-8 text-[clamp(1.75rem,4vw,2.6rem)]">
Entra sin llenar nada.
</h1>
<p className="ld-lead mt-4 max-w-md" style={{ color: "var(--ld-muted)" }}>
Escoge con qué ojos quieres verlo. Cada opción abre el mismo salón, pero desde el
lugar de una persona distinta.
</p>
{DEMO && (
<div className="mt-8 grid grid-cols-1 gap-6">
{grupos.map((g) => (
<div key={g.role} className="grid grid-cols-1 gap-2.5">
<div className="flex items-start gap-2.5">
<span
className="mt-1 h-5 w-1.5 shrink-0 rounded-full"
style={{ background: g.color }}
aria-hidden="true"
/>
<div>
<div className="text-[0.95rem] font-extrabold">{g.titulo}</div>
<div className="text-[0.85rem]" style={{ color: "var(--ld-muted)" }}>
{g.detalle}
</div>
</div>
</div>
<div className="grid grid-cols-1 gap-2 pl-4">
{g.cuentas.map((u) => (
<button
key={u.email}
type="button"
data-magic-login
data-role={u.role}
onClick={() => quickLogin?.(u.email)}
disabled={loading}
className="group flex min-h-[58px] w-full items-center gap-3 rounded-2xl bg-white/85 px-4 py-2.5 text-left ring-1 ring-black/[0.05] transition-all hover:bg-white hover:shadow-[0_14px_32px_-14px_rgba(27,21,51,0.28)] disabled:opacity-60"
>
<span
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-[11px] font-bold text-white"
style={{ background: u.avatar_color }}
>
{u.name
.split(" ")
.map((p) => p[0])
.slice(0, 2)
.join("")}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[0.95rem] font-extrabold">
{u.name}
</span>
<span
className="block truncate text-[0.78rem]"
style={{ color: "var(--ld-muted)" }}
>
{u.email}
</span>
</span>
{pendiente === u.email ? (
<Spinner />
) : (
<Wand2
className="h-4 w-4 shrink-0 opacity-30 transition-opacity group-hover:opacity-100"
style={{ color: g.color }}
/>
)}
</button>
))}
</div>
</div>
))}
</div>
)}
</motion.div>
{/* ---- Columna derecha: formulario manual ----
Visible sin interacción a propósito: visual-audit, responsive-audit y
pwa-e2e rellenan estos campos justo después del goto. Colapsarlo tras
un toggle rompería los tres. */}
<motion.div
className="w-full rounded-3xl bg-white/85 p-6 ring-1 ring-black/[0.05] backdrop-blur-sm sm:p-7"
variants={revealUp(reduced)}
>
<h2 className="text-lg font-extrabold">Ya tengo mi cuenta</h2>
<p className="mt-1 text-[0.9rem]" style={{ color: "var(--ld-muted)" }}>
Entra con tu correo y tu contraseña.
</p>
<form onSubmit={submit} className="mt-6 grid grid-cols-1 gap-4">
<div>
<label className="label">Correo</label>
<div className="relative">
<Mail className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
<input
type="email"
className="input pl-9"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="[email protected]"
autoComplete="email"
required
/>
</div>
</div>
<div>
<label className="label">Contraseña</label>
<div className="relative">
<Lock className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
<input
type="password"
className="input pl-9"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="••••••••"
autoComplete="current-password"
required
/>
</div>
</div>
{error && (
<div className="flex items-center gap-2 rounded-xl bg-rose-50 px-3 py-2.5 text-sm font-semibold text-rose-700">
<AlertCircle className="h-4 w-4 shrink-0" />
{error}
</div>
)}
<button type="submit" className="ld-cta w-full" disabled={loading}>
{loading && !pendiente ? (
<Spinner />
) : (
<>
Entrar <ArrowRight className="h-4 w-4" />
</>
)}
</button>
</form>
<div className="mt-5">
<InstallAppPrompt />
</div>
{DEMO && (
<p
className="mt-5 text-center text-[0.82rem] font-semibold"
style={{ color: "var(--ld-muted)" }}
>
Salón de práctica · todas las cuentas usan{" "}
<code className="font-mono font-bold" style={{ color: "var(--ld-tinta)" }}>
demo1234
</code>
</p>
)}
</motion.div>
</motion.div>
</div>
</div>
);
}