Files

1092 lines
69 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Wonderloo Indoor Park</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.2/babel.min.js"></script>
</head>
<body style="margin:0;padding:0;">
<div id="root"></div>
<script type="text/babel" data-presets="react">
const { useState, useRef, useEffect } = React;
const COLORS = {
warmBg: "#FFF9F0", cream: "#FFF5E6", bark: "#8B6914",
leaf: "#4CAF50", leafDark: "#2E7D32", sky: "#E3F2FD",
pink: "#E91E63", pinkSoft: "#FCE4EC", blue: "#1976D2",
orange: "#FF9800", orangeSoft: "#FFF3E0", text: "#3E2723",
textLight: "#6D4C41", border: "#D7CCC8", white: "#FFFFFF",
error: "#D32F2F", success: "#2E7D32",
};
// ═══════════════════════════════════════════════════════════
// API CONFIG
// El HTML siempre se sirve detrás de nginx (local: localhost:8080,
// prod: dominio del cliente). nginx hace proxy_pass de /api/ al servicio
// api interno, por eso basta con el mismo origen.
// ═══════════════════════════════════════════════════════════
const API_BASE = `${window.location.origin}/api`;
async function apiFetch(path, options = {}) {
const url = `${API_BASE}${path}`;
const res = await fetch(url, {
...options,
headers: {
"Content-Type": "application/json",
...(options.headers || {}),
},
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
const err = new Error(data.error || `HTTP ${res.status}`);
err.code = data.code;
err.status = res.status;
throw err;
}
return data;
}
// Convierte un tutor del API al shape que el UI espera (children, visitas, ultimaVisita)
function normalizeTutor(api) {
return {
id: api.id,
nombre: api.nombre,
telefono: api.telefono,
correo: api.correo || "",
children: (api.ninos || []).map((n) => ({
id: n.id,
nombre: n.nombre,
edad: String(n.edad_actual ?? n.edad ?? ""),
cumple: (n.fecha_nacimiento || "").split("T")[0],
condicion_medica: n.condicion_medica || "",
relacion: n.relacion || "",
})),
visitas: api.total_visitas ?? 0,
ultimaVisita: api.ultima_visita
? new Date(api.ultima_visita).toLocaleDateString("es-MX", { year: "numeric", month: "long", day: "numeric" })
: null,
};
}
// Calcula años completos entre un string YYYY-MM-DD y hoy (zona local).
function calcularEdad(dobStr) {
if (!dobStr) return null;
const parts = String(dobStr).split("-");
if (parts.length !== 3) return null;
const y = parseInt(parts[0], 10);
const mo = parseInt(parts[1], 10);
const d = parseInt(parts[2], 10);
if (!y || !mo || !d) return null;
const hoy = new Date();
const nowMonth = hoy.getMonth() + 1;
const nowDay = hoy.getDate();
let edad = hoy.getFullYear() - y;
if (nowMonth < mo || (nowMonth === mo && nowDay < d)) edad--;
return edad;
}
// Rango de fechas aceptadas para nacimiento (da entre 1 y 11 años hoy).
function dobRange() {
const hoy = new Date();
const y = hoy.getFullYear();
const m = hoy.getMonth();
const d = hoy.getDate();
const max = new Date(y - 1, m, d); // hace 1 año exacto
const min = new Date(y - 12, m, d + 1); // hace 12 años menos 1 día
const fmt = (x) => `${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`;
return { min: fmt(min), max: fmt(max) };
}
const RELACIONES = [
{ value: "Mamá", label: "Mamá" }, { value: "Papá", label: "Papá" },
{ value: "Abuelo/a", label: "Abuelo/a" }, { value: "Tío/a", label: "Tío/a" },
{ value: "Nana", label: "Nana" }, { value: "Hermano/a", label: "Hermano/a mayor" },
{ value: "Otro", label: "Otro tutor" },
];
const TreeIcon = ({ color1, color2, size = 40 }) => (
<svg width={size} height={size} viewBox="0 0 40 40" fill="none">
<rect x="18" y="28" width="4" height="10" rx="1" fill="#8B6914" />
<circle cx="20" cy="18" r="12" fill={color1} opacity="0.9" />
<circle cx="14" cy="14" r="7" fill={color2} opacity="0.8" />
<circle cx="26" cy="16" r="6" fill={color1} opacity="0.7" />
</svg>
);
const WonderlooLogo = () => (
<div style={{ display: "flex", alignItems: "flex-end", gap: "3px", justifyContent: "center" }}>
<TreeIcon color1="#1976D2" color2="#0D47A1" size={28} />
<TreeIcon color1="#E91E63" color2="#AD1457" size={34} />
<TreeIcon color1="#FF9800" color2="#F57F17" size={30} />
<TreeIcon color1="#4CAF50" color2="#2E7D32" size={26} />
</div>
);
const ProgressDots = ({ current, total }) => (
<div style={{ display: "flex", gap: "8px", justifyContent: "center", margin: "16px 0" }}>
{Array.from({ length: total }, (_, i) => (
<div key={i} style={{ width: i === current ? "28px" : "10px", height: "10px", borderRadius: "5px", background: i === current ? COLORS.bark : i < current ? COLORS.leaf : COLORS.border, transition: "all 0.4s cubic-bezier(0.4, 0, 0.2, 1)" }} />
))}
</div>
);
const SignaturePad = ({ onSign }) => {
const canvasRef = useRef(null);
const [isDrawing, setIsDrawing] = useState(false);
const [hasContent, setHasContent] = useState(false);
useEffect(() => { const c = canvasRef.current; if (!c) return; const ctx = c.getContext("2d"); const r = c.getBoundingClientRect(); c.width = r.width * 2; c.height = r.height * 2; ctx.scale(2, 2); ctx.strokeStyle = COLORS.text; ctx.lineWidth = 2.5; ctx.lineCap = "round"; ctx.lineJoin = "round"; }, []);
const getPos = (e) => { const r = canvasRef.current.getBoundingClientRect(); const t = e.touches ? e.touches[0] : e; return { x: t.clientX - r.left, y: t.clientY - r.top }; };
const startDraw = (e) => { e.preventDefault(); const ctx = canvasRef.current.getContext("2d"); const p = getPos(e); ctx.beginPath(); ctx.moveTo(p.x, p.y); setIsDrawing(true); };
const draw = (e) => { if (!isDrawing) return; e.preventDefault(); const ctx = canvasRef.current.getContext("2d"); const p = getPos(e); ctx.lineTo(p.x, p.y); ctx.stroke(); setHasContent(true); };
const endDraw = (e) => { if (!isDrawing) return; e.preventDefault(); setIsDrawing(false); if (hasContent) onSign(canvasRef.current.toDataURL()); };
const clear = () => { const c = canvasRef.current; c.getContext("2d").clearRect(0, 0, c.width, c.height); setHasContent(false); onSign(null); };
return (
<div>
<div style={{ position: "relative", border: `2px dashed ${COLORS.border}`, borderRadius: "16px", overflow: "hidden", background: COLORS.white, touchAction: "none" }}>
<canvas ref={canvasRef} style={{ width: "100%", height: "150px", cursor: "crosshair", display: "block" }} onMouseDown={startDraw} onMouseMove={draw} onMouseUp={endDraw} onMouseLeave={endDraw} onTouchStart={startDraw} onTouchMove={draw} onTouchEnd={endDraw} />
{!hasContent && <div style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, display: "flex", alignItems: "center", justifyContent: "center", pointerEvents: "none", color: COLORS.border, fontFamily: "'Nunito', sans-serif", fontSize: "16px" }}>Firma aquí con tu dedo ✍️</div>}
</div>
{hasContent && <button onClick={clear} style={{ marginTop: "8px", background: "none", border: "none", color: COLORS.error, fontFamily: "'Nunito', sans-serif", fontSize: "14px", cursor: "pointer", padding: "4px 8px" }}>Borrar firma</button>}
</div>
);
};
const InputField = ({ label, icon, value, onChange, type = "text", placeholder, required = true, options, helperText, large, min, max, digitsOnly }) => (
<div style={{ marginBottom: "16px" }}>
<label style={{ display: "block", fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: "15px", color: COLORS.text, marginBottom: "6px" }}>
{icon && <span style={{ marginRight: "6px" }}>{icon}</span>}{label}
{!required && <span style={{ fontWeight: 400, color: COLORS.textLight, fontSize: "13px" }}> (opcional)</span>}
</label>
{options ? (
<select value={value} onChange={(e) => onChange(e.target.value)} style={{ width: "100%", padding: "14px 16px", borderRadius: "14px", border: `2px solid ${COLORS.border}`, fontSize: "17px", fontFamily: "'Nunito', sans-serif", color: value ? COLORS.text : COLORS.textLight, background: COLORS.white, appearance: "none", backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%238B6914' d='M6 8L1 3h10z'/%3E%3C/svg%3E\")", backgroundRepeat: "no-repeat", backgroundPosition: "right 16px center", outline: "none", boxSizing: "border-box" }}>
<option value="">{placeholder || "Selecciona..."}</option>
{options.map((o) => <option key={o.value || o} value={o.value || o}>{o.label || o}</option>)}
</select>
) : (
<input type={type} value={value} onChange={(e) => onChange(digitsOnly ? e.target.value.replace(/\D/g, "").slice(0, 10) : e.target.value)} placeholder={placeholder} min={min} max={max} inputMode={digitsOnly ? "numeric" : undefined} maxLength={digitsOnly ? 10 : undefined} pattern={digitsOnly ? "[0-9]*" : undefined} style={{ width: "100%", padding: large ? "18px 16px" : "14px 16px", borderRadius: "14px", border: `2px solid ${COLORS.border}`, fontSize: large ? "22px" : "17px", fontFamily: "'Nunito', sans-serif", color: COLORS.text, fontWeight: large ? 700 : 400, background: COLORS.white, outline: "none", boxSizing: "border-box", textAlign: large ? "center" : "left", letterSpacing: large ? "2px" : "normal", transition: "border-color 0.2s" }} onFocus={(e) => e.target.style.borderColor = COLORS.bark} onBlur={(e) => e.target.style.borderColor = COLORS.border} />
)}
{helperText && <p style={{ margin: "4px 0 0 4px", fontSize: "13px", color: COLORS.textLight, fontFamily: "'Nunito', sans-serif" }}>{helperText}</p>}
</div>
);
const Btn = ({ children, onClick, disabled, variant = "primary" }) => {
const S = { primary: { bg: COLORS.bark, c: COLORS.white, sh: "0 4px 16px rgba(139,105,20,0.3)", bd: "none" }, success: { bg: COLORS.leaf, c: COLORS.white, sh: "0 4px 16px rgba(76,175,80,0.3)", bd: "none" }, outline: { bg: "transparent", c: COLORS.bark, sh: "none", bd: `2px solid ${COLORS.bark}` }, subtle: { bg: COLORS.cream, c: COLORS.bark, sh: "none", bd: "none" } };
const s = S[variant] || S.primary;
return <button onClick={onClick} disabled={disabled} style={{ width: "100%", padding: "16px 24px", borderRadius: "16px", background: disabled ? COLORS.border : s.bg, color: disabled ? COLORS.textLight : s.c, border: disabled ? "none" : s.bd, fontSize: "18px", fontWeight: 800, fontFamily: "'Nunito', sans-serif", cursor: disabled ? "not-allowed" : "pointer", boxShadow: disabled ? "none" : s.sh, transition: "all 0.2s ease", letterSpacing: "0.3px" }}>{children}</button>;
};
const Card = ({ children, style }) => <div style={{ background: COLORS.white, borderRadius: "20px", padding: "20px", boxShadow: "0 2px 12px rgba(0,0,0,0.06)", ...style }}>{children}</div>;
const RESPONSIVA = `Por medio de la presente, manifiesto que soy padre, madre o tutor del menor antes mencionado y autorizo su ingreso a la ludoteca Wonderloo Indoor Park®, ubicada en Paseo Opera número 11, Distrito Sonata en Lomas de Angelópolis II, Locales 7, 8, 9, en la Ciudad de San Andrés Cholula, Puebla C.P. 72830.
Declaro bajo protesta de decir verdad que:
1. Entiendo y acepto que la ludoteca es un espacio destinado a la recreación infantil, donde el personal encargado supervisará a los niños. Sin embargo, dicha supervisión no exime ni sustituye la responsabilidad del padre, madre o tutor legal.
2. Acepto que el menor a mi cargo deberá cumplir con el reglamento interno de la ludoteca y que, en caso de cualquier incidente, seré contactado de inmediato.
3. Libero de toda responsabilidad a la ludoteca y a su personal por cualquier accidente que pudiera ocurrir dentro de sus instalaciones.
4. En caso de emergencia, comprendo y acepto que el personal de la ludoteca no cuenta con la capacitación para brindar atención médica especializada ni para realizar el traslado del menor a un centro de salud en caso de ser necesario.
5. Acepto y estoy de acuerdo con el reglamento del establecimiento así como los reglamentos internos de cada área.`;
const Fonts = () => <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800;900&family=Fredoka:wght@400;500;600;700&display=swap" rel="stylesheet" />;
const Shell = ({ children: ch, bg }) => (
<div style={{ minHeight: "100vh", background: bg || `linear-gradient(180deg, ${COLORS.warmBg} 0%, ${COLORS.cream} 100%)`, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "24px", fontFamily: "'Nunito', sans-serif", boxSizing: "border-box" }}>
<Fonts />
<div style={{ maxWidth: "420px", width: "100%", animation: "fadeUp 0.5s ease-out" }}>{ch}</div>
<style>{`@keyframes fadeUp { from { opacity:0; transform:translateY(16px); } to { opacity:1; transform:translateY(0); } } @keyframes popIn { from { transform:scale(0); } to { transform:scale(1); } } * { -webkit-tap-highlight-color: transparent; } input, select { font-size: 17px !important; }`}</style>
</div>
);
const ToastBanner = ({ toast }) => (
<div style={{
position: "fixed", bottom: "100px", left: "16px", right: "16px",
maxWidth: "420px", margin: "0 auto",
background: toast.type === "success" ? COLORS.leaf : COLORS.error,
color: COLORS.white, padding: "14px 18px", borderRadius: "14px",
boxShadow: "0 8px 32px rgba(0,0,0,0.25)",
fontFamily: "'Nunito', sans-serif", fontSize: "14px", fontWeight: 700,
textAlign: "center", zIndex: 200,
animation: "fadeUp 0.3s ease-out"
}}>
{toast.message}
</div>
);
function WonderlooCheckin() {
const [mode, setMode] = useState(null);
const [step, setStep] = useState(0);
const [animDir, setAnimDir] = useState("right");
const [lookupPhone, setLookupPhone] = useState("");
const [foundUser, setFoundUser] = useState(null);
const [lookupError, setLookupError] = useState(false);
const [lookupLoading, setLookupLoading] = useState(false);
const [selectedChildren, setSelectedChildren] = useState([]);
const [addingNewChild, setAddingNewChild] = useState(false);
const [newChildForReturn, setNewChildForReturn] = useState({ nombre: "", cumple: "", condicion_medica: "", relacion: "" });
const [editingPhone, setEditingPhone] = useState(false);
const [newPhone, setNewPhone] = useState("");
const [tutorData, setTutorData] = useState({ nombre: "", telefono: "", correo: "" });
const [children, setChildren] = useState([{ nombre: "", cumple: "", condicion_medica: "", relacion: "" }]);
const [serviciosPorNino, setServiciosPorNino] = useState({});
const [metodoPago, setMetodoPago] = useState("mostrador");
const [aceptaResponsiva, setAceptaResponsiva] = useState(false);
const [signature, setSignature] = useState(null);
const [submitted, setSubmitted] = useState(false);
const [precios, setPrecios] = useState(null);
const [preciosLoading, setPreciosLoading] = useState(true);
const [toast, setToast] = useState(null);
const [submitLoading, setSubmitLoading] = useState(false);
const [editingChildId, setEditingChildId] = useState(null);
const [editChildForm, setEditChildForm] = useState({ nombre: "", cumple: "", condicion_medica: "", relacion: "" });
const [duplicateTutor, setDuplicateTutor] = useState(null);
const [checkingDuplicate, setCheckingDuplicate] = useState(false);
const [currentTime] = useState(new Date().toLocaleTimeString("es-MX", { hour: "2-digit", minute: "2-digit" }));
const [currentDate] = useState(new Date().toLocaleDateString("es-MX", { weekday: "long", year: "numeric", month: "long", day: "numeric" }));
useEffect(() => {
apiFetch("/precios")
.then((p) => setPrecios(p))
.catch(() => setToast({ message: "No pudimos cargar los precios. Recarga la página.", type: "error" }))
.finally(() => setPreciosLoading(false));
}, []);
useEffect(() => {
if (!toast) return;
const t = setTimeout(() => setToast(null), 4000);
return () => clearTimeout(t);
}, [toast]);
const resetAll = () => {
setSubmitted(false); setMode(null); setStep(0); setServiciosPorNino({}); setMetodoPago("mostrador");
setSignature(null); setAceptaResponsiva(false); setFoundUser(null);
setLookupPhone(""); setLookupError(false); setSelectedChildren([]);
setAddingNewChild(false); setNewChildForReturn({ nombre: "", cumple: "", condicion_medica: "", relacion: "" });
setEditingPhone(false); setNewPhone("");
setTutorData({ nombre: "", telefono: "", correo: "" });
setChildren([{ nombre: "", cumple: "", condicion_medica: "", relacion: "" }]);
setEditingChildId(null);
setEditChildForm({ nombre: "", cumple: "", condicion_medica: "", relacion: "" });
};
const goNext = () => { setAnimDir("right"); setStep(s => s + 1); };
const goBack = () => {
setAnimDir("left");
if (step === 0) { setMode(null); setFoundUser(null); setLookupPhone(""); setLookupError(false); setSelectedChildren([]); setEditingPhone(false); }
else setStep(s => s - 1);
};
const addChild = () => { if (children.length < 4) setChildren([...children, { nombre: "", cumple: "", condicion_medica: "", relacion: "" }]); };
const removeChild = (i) => { if (children.length > 1) setChildren(children.filter((_, idx) => idx !== i)); };
const updateChild = (i, f, v) => { const u = [...children]; u[i] = { ...u[i], [f]: v }; setChildren(u); };
const toggleChildSelection = (idx) => setSelectedChildren(prev => prev.includes(idx) ? prev.filter(i => i !== idx) : [...prev, idx]);
const handleLookup = async () => {
setLookupLoading(true);
setLookupError(false);
try {
const clean = lookupPhone.replace(/\D/g, "");
const apiTutor = await apiFetch("/tutores/lookup", {
method: "POST",
body: JSON.stringify({ telefono: clean }),
});
const tutor = normalizeTutor(apiTutor);
setFoundUser(tutor);
// Pre-seleccionar SOLO niños elegibles (<12 años). Niños con 12+ quedan disabled
// en el UI y no deberían estar en selectedChildren, porque el usuario no puede
// des-seleccionarlos y bloquearían el avance.
setSelectedChildren(
tutor.children
.map((c, i) => ({ i, edad: parseInt(c.edad, 10) }))
.filter(({ edad }) => !isNaN(edad) && edad < 12)
.map(({ i }) => i)
);
} catch (err) {
if (err.status === 404) {
setLookupError(true);
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message || "Error inesperado", type: "error" });
}
} finally {
setLookupLoading(false);
}
};
const confirmAddNewChild = async () => {
if (!newChildForReturn.nombre || !newChildForReturn.cumple || !newChildForReturn.relacion || !foundUser) return;
try {
const apiNino = await apiFetch(`/tutores/${foundUser.id}/ninos`, {
method: "POST",
body: JSON.stringify({
nombre: newChildForReturn.nombre,
fecha_nacimiento: newChildForReturn.cumple,
relacion: newChildForReturn.relacion,
condicion_medica: newChildForReturn.condicion_medica || undefined,
}),
});
const newChild = {
id: apiNino.id,
nombre: apiNino.nombre,
edad: String(apiNino.edad ?? ""),
cumple: (apiNino.fecha_nacimiento || "").split("T")[0],
condicion_medica: apiNino.condicion_medica || "",
relacion: apiNino.relacion,
};
const newIdx = foundUser.children.length;
setFoundUser(prev => ({ ...prev, children: [...prev.children, newChild] }));
setSelectedChildren(prev => [...prev, newIdx]);
setNewChildForReturn({ nombre: "", cumple: "", condicion_medica: "", relacion: "" });
setAddingNewChild(false);
} catch (err) {
if (err.code === "MAX_CHILDREN_REACHED") {
setToast({ message: "Este tutor ya tiene el máximo de 4 niños activos.", type: "error" });
} else if (err.code === "AGE_OUT_OF_RANGE") {
setToast({ message: "La edad del niño debe estar entre 1 y 11 años.", type: "error" });
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message, type: "error" });
}
}
};
const openEditChild = (child) => {
setEditingChildId(child.id);
setEditChildForm({
nombre: child.nombre || "",
cumple: child.cumple || "",
condicion_medica: child.condicion_medica || "",
relacion: child.relacion || "",
});
};
const closeEditChild = () => {
setEditingChildId(null);
setEditChildForm({ nombre: "", cumple: "", condicion_medica: "", relacion: "" });
};
const saveEditChild = async () => {
if (!editingChildId) return;
if (!editChildForm.nombre || !editChildForm.relacion || !editChildForm.cumple) return;
const edadNum = calcularEdad(editChildForm.cumple);
if (edadNum === null) return;
if (edadNum >= 12) {
setToast({ message: "Este niño ya cumplió el límite de edad. Para siguientes visitas ya no estará disponible.", type: "error" });
return;
}
if (edadNum < 1) return;
try {
const updated = await apiFetch(`/ninos/${editingChildId}`, {
method: "PATCH",
body: JSON.stringify({
nombre: editChildForm.nombre,
fecha_nacimiento: editChildForm.cumple,
relacion: editChildForm.relacion,
condicion_medica: editChildForm.condicion_medica || "",
}),
});
const normalized = {
id: updated.id,
nombre: updated.nombre,
edad: String(updated.edad ?? ""),
cumple: (updated.fecha_nacimiento || "").split("T")[0],
condicion_medica: updated.condicion_medica || "",
relacion: updated.relacion || "",
};
setFoundUser(prev => ({
...prev,
children: prev.children.map(c => c.id === normalized.id ? normalized : c),
}));
closeEditChild();
} catch (err) {
if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else if (err.code === "AGE_OUT_OF_RANGE") {
setToast({ message: "Este niño ya cumplió el límite de edad. Para siguientes visitas ya no estará disponible.", type: "error" });
} else {
setToast({ message: "No pudimos actualizar. Intenta de nuevo.", type: "error" });
}
}
};
const confirmPhoneChange = async () => {
const clean = newPhone.replace(/\D/g, "");
if (clean.length < 10 || !foundUser) return;
try {
const apiTutor = await apiFetch(`/tutores/${foundUser.id}`, {
method: "PATCH",
body: JSON.stringify({ telefono: clean }),
});
setFoundUser(prev => ({ ...prev, telefono: apiTutor.telefono }));
setEditingPhone(false);
setNewPhone("");
} catch (err) {
if (err.code === "PHONE_CONFLICT") {
setToast({ message: "Ese número ya pertenece a otro tutor.", type: "error" });
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message, type: "error" });
}
}
};
// Antes de avanzar del step "tutor", verifica si el teléfono ya existe.
// Si existe, abre el modal con opción de cambiar a flujo "Ya tengo cuenta".
const advanceFromTutor = async () => {
if (checkingDuplicate) return;
setCheckingDuplicate(true);
try {
const apiTutor = await apiFetch("/tutores/lookup", {
method: "POST",
body: JSON.stringify({ telefono: tutorData.telefono }),
});
setDuplicateTutor(normalizeTutor(apiTutor));
} catch (err) {
if (err.status === 404) {
goNext();
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message || "Error inesperado", type: "error" });
}
} finally {
setCheckingDuplicate(false);
}
};
const handleDuplicateUseIt = () => {
if (!duplicateTutor) return;
setMode("returning");
setFoundUser(duplicateTutor);
setSelectedChildren(
duplicateTutor.children
.map((c, i) => ({ i, edad: parseInt(c.edad, 10) }))
.filter(({ edad }) => !isNaN(edad) && edad < 12)
.map(({ i }) => i)
);
setTutorData({ nombre: "", telefono: "", correo: "" });
setChildren([{ nombre: "", cumple: "", condicion_medica: "", relacion: "" }]);
setStep(0);
setDuplicateTutor(null);
};
const handleDuplicateDismiss = () => {
setDuplicateTutor(null);
};
const handleSubmit = async () => {
setSubmitLoading(true);
try {
let tutorId;
let payloadNinos;
if (mode === "new") {
const clean = tutorData.telefono.replace(/\D/g, "");
const created = await apiFetch("/tutores", {
method: "POST",
body: JSON.stringify({
nombre: tutorData.nombre,
telefono: clean,
correo: tutorData.correo || "",
ninos: children.map((c) => ({
nombre: c.nombre,
fecha_nacimiento: c.cumple,
relacion: c.relacion,
condicion_medica: c.condicion_medica || undefined,
})),
}),
});
tutorId = created.id;
// created.ninos viene en el mismo orden que children → serviciosPorNino[i] matchea.
payloadNinos = created.ninos.map((n, i) => ({
nino_id: n.id,
tipo_servicio: serviciosPorNino[i],
}));
} else if (foundUser) {
tutorId = foundUser.id;
// activeChildren para ret_confirmed es foundUser.children filtrado; mismo índice.
payloadNinos = activeChildren.map((child, i) => ({
nino_id: child.id,
tipo_servicio: serviciosPorNino[i],
}));
}
await apiFetch("/visitas", {
method: "POST",
body: JSON.stringify({
tutor_id: tutorId,
ninos: payloadNinos,
metodo_pago: metodoPago,
firma_base64: signature,
}),
});
setSubmitted(true);
} catch (err) {
if (err.code === "PHONE_ALREADY_EXISTS") {
setToast({ message: 'Este teléfono ya está registrado. ¿Intenta con "Ya tengo cuenta"?', type: "error" });
} else if (err instanceof TypeError) {
setToast({ message: "Error de conexión. Intenta de nuevo.", type: "error" });
} else {
setToast({ message: err.message || "Error inesperado", type: "error" });
}
} finally {
setSubmitLoading(false);
}
};
const newSteps = ["tutor", "children", "promos", "service", "responsiva"];
const retSteps = ["select_children", "promos", "service", "responsiva"];
const activeSteps = mode === "ret_confirmed" ? retSteps : newSteps;
const currentStepName = activeSteps[step];
const totalSteps = activeSteps.length;
const isLastStep = step === totalSteps - 1;
const activeChildren = mode === "ret_confirmed" ? (foundUser?.children || []).filter((_, i) => selectedChildren.includes(i)) : children;
const activeName = foundUser ? foundUser.nombre : tutorData.nombre;
const activePhone = foundUser ? foundUser.telefono : tutorData.telefono;
const canProceed = () => {
switch (currentStepName) {
case "tutor": return tutorData.nombre && tutorData.telefono.length === 10;
case "children":
return children.every(c => {
if (!c.nombre || !c.cumple || !c.relacion) return false;
const e = calcularEdad(c.cumple);
return e !== null && e >= 1 && e <= 11;
});
case "select_children":
if (selectedChildren.length === 0 || addingNewChild || editingChildId) return false;
return selectedChildren.every(idx => {
const child = foundUser?.children?.[idx];
if (!child) return false;
const e = parseInt(child.edad, 10);
return !isNaN(e) && e < 12;
});
case "promos": return true;
case "service": return activeChildren.length > 0 && activeChildren.every((_, i) => serviciosPorNino[i]) && !!metodoPago;
case "responsiva": return aceptaResponsiva && signature;
default: return false;
}
};
if (preciosLoading) {
return (
<React.Fragment>
<Shell>
<div style={{ textAlign: "center" }}>
<div style={{ marginBottom: "20px" }}><WonderlooLogo /></div>
<h1 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "32px", fontWeight: 700, color: COLORS.text, margin: "0 0 2px 0" }}>wonderloo</h1>
<p style={{ fontSize: "13px", color: COLORS.textLight, margin: "0 0 28px 0", letterSpacing: "2.5px", textTransform: "uppercase", fontWeight: 600 }}>indoor park</p>
<p style={{ fontSize: "14px", color: COLORS.textLight }}>Cargando…</p>
</div>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (mode === null) {
return (
<React.Fragment>
<Shell>
<div style={{ textAlign: "center" }}>
<div style={{ marginBottom: "20px" }}><WonderlooLogo /></div>
<h1 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "32px", fontWeight: 700, color: COLORS.text, margin: "0 0 2px 0" }}>wonderloo</h1>
<p style={{ fontSize: "13px", color: COLORS.textLight, margin: "0 0 36px 0", letterSpacing: "2.5px", textTransform: "uppercase", fontWeight: 600 }}>indoor park</p>
<Card style={{ padding: "28px 24px", marginBottom: "16px" }}>
<p style={{ fontSize: "22px", fontWeight: 800, color: COLORS.text, margin: "0 0 6px 0", fontFamily: "'Fredoka', sans-serif" }}>¡Bienvenidos! 🎉</p>
<p style={{ fontSize: "15px", color: COLORS.textLight, margin: "0 0 28px 0", lineHeight: 1.5 }}>Registra tu visita para que los pequeños puedan entrar a jugar</p>
<div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
<Btn onClick={() => { setMode("new"); setStep(0); }}>Crear cuenta 🌟</Btn>
<Btn variant="outline" onClick={() => { setMode("returning"); setStep(0); }}>Ya tengo cuenta 📱</Btn>
</div>
</Card>
<p style={{ fontSize: "12px", color: COLORS.textLight, margin: 0 }}>{currentDate} · {currentTime}</p>
</div>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (mode === "returning" && !foundUser) {
return (
<React.Fragment>
<Shell>
<button onClick={() => { setMode(null); setLookupPhone(""); setLookupError(false); }} style={{ background: "none", border: "none", fontSize: "16px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif", padding: "8px 0", marginBottom: "12px" }}>← Inicio</button>
<Card style={{ padding: "28px 24px" }}>
<div style={{ textAlign: "center", marginBottom: "24px" }}>
<span style={{ fontSize: "48px" }}>📱</span>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "12px 0 6px 0" }}>¡Hola de nuevo!</h2>
<p style={{ fontSize: "15px", color: COLORS.textLight, margin: 0, lineHeight: 1.5 }}>Ingresa tu número de WhatsApp</p>
</div>
<div style={{ marginBottom: "16px" }}>
<label style={{ display: "block", fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: "15px", color: COLORS.text, marginBottom: "6px" }}>
<span style={{ marginRight: "6px" }}>📱</span>Tu número de WhatsApp
</label>
<input type="tel" value={lookupPhone} onChange={(e) => { setLookupPhone(e.target.value.replace(/\D/g, "").slice(0, 10)); setLookupError(false); }} placeholder="Ej: 2211234567" inputMode="numeric" maxLength={10} pattern="[0-9]*" style={{ width: "100%", padding: "18px 16px", borderRadius: "14px", border: `2px solid ${COLORS.border}`, fontSize: "22px", fontFamily: "'Nunito', sans-serif", color: COLORS.text, fontWeight: 700, background: COLORS.white, outline: "none", boxSizing: "border-box", textAlign: "center", letterSpacing: "2px" }} onFocus={(e) => e.target.style.borderColor = COLORS.bark} onBlur={(e) => e.target.style.borderColor = COLORS.border} />
</div>
{lookupError && (
<div style={{ background: "#FFEBEE", borderRadius: "12px", padding: "14px 16px", marginBottom: "16px", animation: "fadeUp 0.3s ease-out" }}>
<p style={{ margin: "0 0 6px 0", fontSize: "14px", color: COLORS.error, fontWeight: 700 }}>No encontramos ese número 🤔</p>
<button onClick={() => { setMode("new"); setStep(0); setLookupError(false); }} style={{ marginTop: "6px", background: "none", border: "none", color: COLORS.bark, fontWeight: 700, fontFamily: "'Nunito', sans-serif", fontSize: "14px", cursor: "pointer", textDecoration: "underline" }}>Crear cuenta nueva →</button>
</div>
)}
<Btn onClick={handleLookup} disabled={lookupPhone.replace(/\D/g, "").length < 10 || lookupLoading}>
{lookupLoading ? "Buscando..." : "Buscar mi cuenta →"}
</Btn>
<p style={{ fontSize: "12px", color: COLORS.textLight, textAlign: "center", marginTop: "16px" }}>
💡 <strong>Demo:</strong> prueba <strong>2222392995</strong> ó <strong>2211173907</strong>
</p>
</Card>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (mode === "returning" && foundUser) {
return (
<React.Fragment>
<Shell>
<button onClick={() => { setFoundUser(null); setLookupPhone(""); setSelectedChildren([]); setEditingPhone(false); }} style={{ background: "none", border: "none", fontSize: "16px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif", padding: "8px 0", marginBottom: "12px" }}>← Otro número</button>
<Card style={{ padding: "24px", marginBottom: "16px" }}>
<div style={{ textAlign: "center", marginBottom: "20px" }}>
<div style={{ width: "72px", height: "72px", borderRadius: "50%", background: `linear-gradient(135deg, ${COLORS.orangeSoft}, ${COLORS.pinkSoft})`, display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 12px", fontSize: "32px" }}>👋</div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "22px", color: COLORS.text, margin: "0 0 2px 0" }}>¡Hola, {foundUser.nombre.split(" ")[0]}!</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: 0 }}>
{foundUser.ultimaVisita
? `Visita #${foundUser.visitas + 1} · Última: ${foundUser.ultimaVisita}`
: "¡Tu primera visita con nosotros!"}
</p>
</div>
<div style={{ background: COLORS.cream, borderRadius: "14px", padding: "14px", marginBottom: "16px" }}>
{!editingPhone ? (
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
<div>
<div style={{ fontSize: "12px", fontWeight: 700, color: COLORS.bark }}>WhatsApp registrado</div>
<div style={{ fontSize: "16px", fontWeight: 700, color: COLORS.text, marginTop: "2px" }}>📱 {foundUser.telefono}</div>
</div>
<button onClick={() => { setEditingPhone(true); setNewPhone(foundUser.telefono); }} style={{ background: COLORS.white, border: `1px solid ${COLORS.border}`, borderRadius: "10px", padding: "6px 12px", fontSize: "13px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif" }}>Cambiar</button>
</div>
) : (
<div>
<div style={{ fontSize: "12px", fontWeight: 700, color: COLORS.bark, marginBottom: "8px" }}>Nuevo número de WhatsApp</div>
<InputField label="" type="tel" value={newPhone} onChange={setNewPhone} placeholder="Nuevo número" large digitsOnly />
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "8px" }}>
<button onClick={() => setEditingPhone(false)} style={{ padding: "10px", borderRadius: "12px", background: COLORS.white, border: `1px solid ${COLORS.border}`, color: COLORS.textLight, fontSize: "14px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: "pointer" }}>Cancelar</button>
<button onClick={confirmPhoneChange} disabled={newPhone.replace(/\D/g, "").length < 10} style={{ padding: "10px", borderRadius: "12px", background: newPhone.replace(/\D/g, "").length >= 10 ? COLORS.leaf : COLORS.border, border: "none", color: COLORS.white, fontSize: "14px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: newPhone.replace(/\D/g, "").length >= 10 ? "pointer" : "not-allowed" }}>Guardar ✓</button>
</div>
</div>
)}
</div>
{!editingPhone && <Btn onClick={() => { setMode("ret_confirmed"); setStep(0); }}>Soy yo — continuar →</Btn>}
</Card>
<p style={{ fontSize: "12px", color: COLORS.textLight, textAlign: "center" }}>
¿No eres tú? <button onClick={() => { setFoundUser(null); setLookupPhone(""); }} style={{ background: "none", border: "none", color: COLORS.bark, fontWeight: 700, fontFamily: "'Nunito', sans-serif", fontSize: "12px", cursor: "pointer", textDecoration: "underline" }}>Buscar otro número</button>
</p>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
if (submitted) {
return (
<React.Fragment>
<Shell bg={`linear-gradient(180deg, #E8F5E9 0%, ${COLORS.warmBg} 100%)`}>
<div style={{ textAlign: "center" }}>
<div style={{ width: "100px", height: "100px", borderRadius: "50%", background: COLORS.leaf, display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 24px", boxShadow: "0 8px 32px rgba(76,175,80,0.3)", animation: "popIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55)" }}>
<span style={{ fontSize: "48px", color: COLORS.white }}>✓</span>
</div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "28px", color: COLORS.text, margin: "0 0 8px 0" }}>¡Registro completo!</h2>
<p style={{ fontSize: "16px", color: COLORS.textLight, margin: "0 0 24px 0", lineHeight: 1.5 }}>
{activeName.split(" ")[0]}, todo está listo.<br />
{activeChildren.length === 1 ? `${activeChildren[0].nombre} ya puede` : "Los pequeños ya pueden"} pasar a divertirse 🎈
</p>
<Card style={{ padding: "20px", marginBottom: "16px", textAlign: "left" }}>
<div style={{ marginBottom: "12px" }}>
<span style={{ fontWeight: 700, color: COLORS.text }}>Resumen</span>
</div>
<div style={{ fontSize: "14px", color: COLORS.textLight, lineHeight: 1.8 }}>
<div>👤 {activeName}</div>
<div>📱 {activePhone}</div>
{activeChildren.map((c, i) => {
const edadShow = c.cumple ? calcularEdad(c.cumple) : (c.edad ? parseInt(c.edad, 10) : null);
const svc = serviciosPorNino[i];
const svcLabel = svc === "daypass" ? "Daypass" : svc === "playday" ? "PlayDay" : svc === "hora" ? "1 Hora" : "";
return (
<div key={i} style={{ marginBottom: c.condicion_medica ? "6px" : 0 }}>
<div>👶 {c.nombre}{edadShow !== null ? `, ${edadShow} ${edadShow === 1 ? "año" : "años"}` : ""} ({c.relacion}){svcLabel ? ` — ${svcLabel}` : ""}</div>
{c.condicion_medica && (
<div style={{ color: COLORS.orange, fontWeight: 700, marginLeft: "20px", fontSize: "13px", lineHeight: 1.4 }}>
⚠️ Condición médica: {c.condicion_medica}
</div>
)}
</div>
);
})}
<div>🕐 Entrada: {currentTime}</div>
<div>💳 Cobro en caja</div>
</div>
</Card>
<div style={{ marginTop: "24px" }}><WonderlooLogo /></div>
<button onClick={resetAll} style={{ marginTop: "20px", background: "none", border: "none", color: COLORS.bark, fontWeight: 700, fontFamily: "'Nunito', sans-serif", fontSize: "15px", cursor: "pointer", textDecoration: "underline" }}>Nuevo registro</button>
</div>
</Shell>
{toast && <ToastBanner toast={toast} />}
</React.Fragment>
);
}
const stepLabels = { tutor: "Responsable", children: "Niño(s)", select_children: "¿Quién viene?", promos: "Promos", service: "Entrada", responsiva: "Firma" };
const renderStep = () => {
switch (currentStepName) {
case "tutor":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Tus datos 👤</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Información del responsable</p>
<InputField label="Nombre completo" icon="👤" value={tutorData.nombre} onChange={(v) => setTutorData({ ...tutorData, nombre: v })} placeholder="Ej: María García López" />
<InputField label="WhatsApp" icon="📱" type="tel" value={tutorData.telefono} onChange={(v) => setTutorData({ ...tutorData, telefono: v })} placeholder="Ej: 2211234567" helperText="10 dígitos, solo números · Este será tu identificador para futuras visitas" digitsOnly />
<InputField label="Correo electrónico" icon="📧" type="email" value={tutorData.correo} onChange={(v) => setTutorData({ ...tutorData, correo: v })} placeholder="Ej: maria@correo.com" required={false} />
</div>);
case "children": {
const dob = dobRange();
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Datos de los pequeños 👶</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Niños que ingresan hoy (1 a 11 años)</p>
{children.map((child, idx) => {
const edadCalc = calcularEdad(child.cumple);
const tooOld = edadCalc !== null && edadCalc >= 12;
const nearLimit = edadCalc === 11;
const underMin = edadCalc !== null && edadCalc < 1;
return (
<Card key={idx} style={{ marginBottom: "16px", padding: "16px", border: `2px solid ${tooOld || underMin ? COLORS.error : COLORS.cream}`, boxShadow: "0 1px 4px rgba(0,0,0,0.04)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
<span style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "16px", fontWeight: 600, color: COLORS.bark }}>{children.length > 1 ? `Niño ${idx + 1}` : "Datos del niño/a"}</span>
{children.length > 1 && <button onClick={() => removeChild(idx)} style={{ background: COLORS.pinkSoft, border: "none", borderRadius: "8px", padding: "4px 10px", fontSize: "13px", color: COLORS.pink, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif" }}>Quitar ✕</button>}
</div>
<InputField label="Nombre del niño/a" value={child.nombre} onChange={(v) => updateChild(idx, "nombre", v)} placeholder="Nombre completo" />
<InputField label="Fecha de nacimiento" type="date" value={child.cumple} onChange={(v) => updateChild(idx, "cumple", v)} min={dob.min} max={dob.max} />
{edadCalc !== null && !tooOld && !underMin && (
<p style={{ margin: "-8px 0 12px 4px", fontSize: "14px", fontWeight: 700, color: COLORS.bark, fontFamily: "'Nunito', sans-serif" }}>
Edad: {edadCalc} {edadCalc === 1 ? "año" : "años"}
</p>
)}
{tooOld && (
<div style={{ background: "#FFEBEE", borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.error, fontWeight: 700, lineHeight: 1.4 }}>
Wonderloo es para niños de 1 a 11 años. No podemos registrar a menores de 12 años o más.
</div>
)}
{underMin && (
<div style={{ background: "#FFEBEE", borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.error, fontWeight: 700, lineHeight: 1.4 }}>
La edad debe ser de al menos 1 año.
</div>
)}
{nearLimit && !tooOld && (
<div style={{ background: COLORS.orangeSoft, borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.orange, fontWeight: 700, lineHeight: 1.4 }}>
⚠️ Edad próxima al límite. Wonderloo es para niños hasta 11 años.
</div>
)}
<InputField label="Parentesco contigo" icon="👨‍👩‍👧" value={child.relacion} onChange={(v) => updateChild(idx, "relacion", v)} options={RELACIONES} placeholder="¿Qué eres del niño/a?" />
<InputField label="Condición médica" value={child.condicion_medica} onChange={(v) => updateChild(idx, "condicion_medica", v)} placeholder="Ej: Autismo, Síndrome de Down, TDAH" required={false} />
</Card>
);
})}
{children.length < 4 && <button onClick={addChild} style={{ width: "100%", padding: "14px", borderRadius: "14px", border: `2px dashed ${COLORS.bark}`, background: COLORS.cream, color: COLORS.bark, fontSize: "16px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: "pointer" }}>+ Agregar otro niño</button>}
</div>);
}
case "select_children": {
const dob = dobRange();
const editEdadCalc = calcularEdad(editChildForm.cumple);
const editTooOld = editEdadCalc !== null && editEdadCalc >= 12;
const editNearLimit = editEdadCalc === 11;
const editUnderMin = editEdadCalc !== null && editEdadCalc < 1;
const newChildEdadCalc = calcularEdad(newChildForReturn.cumple);
const newChildTooOld = newChildEdadCalc !== null && newChildEdadCalc >= 12;
const newChildNearLimit = newChildEdadCalc === 11;
const newChildUnderMin = newChildEdadCalc !== null && newChildEdadCalc < 1;
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>¿Quién viene hoy? 👶</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Selecciona a los niños que asisten</p>
{(foundUser?.children || []).map((child, idx) => {
const sel = selectedChildren.includes(idx);
const childEdad = parseInt(child.edad, 10);
const childTooOld = !isNaN(childEdad) && childEdad >= 12;
const isEditingThis = editingChildId === child.id;
const disabled = childTooOld || editingChildId;
return (
<React.Fragment key={child.id || idx}>
<div
role="button"
onClick={() => { if (!disabled) toggleChildSelection(idx); }}
style={{
width: "100%", display: "flex", alignItems: "center", gap: "14px",
padding: "16px 18px", borderRadius: "16px", marginBottom: "12px",
border: childTooOld ? `2px solid ${COLORS.border}` : (sel ? `3px solid ${COLORS.leaf}` : `2px solid ${COLORS.border}`),
background: childTooOld ? "#F5F5F5" : (sel ? "#E8F5E9" : COLORS.white),
opacity: childTooOld ? 0.6 : 1,
cursor: disabled ? "not-allowed" : "pointer",
transition: "all 0.2s ease", textAlign: "left", boxSizing: "border-box"
}}
>
<div style={{ width: "32px", height: "32px", borderRadius: "10px", flexShrink: 0, background: childTooOld ? COLORS.border : (sel ? COLORS.leaf : COLORS.white), border: `2px solid ${childTooOld ? COLORS.border : (sel ? COLORS.leaf : COLORS.border)}`, display: "flex", alignItems: "center", justifyContent: "center" }}>
{sel && !childTooOld && <span style={{ color: COLORS.white, fontSize: "18px", fontWeight: 900 }}>✓</span>}
</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: "16px", fontWeight: 700, color: childTooOld ? COLORS.textLight : COLORS.text, fontFamily: "'Nunito', sans-serif" }}>{child.nombre}</div>
<div style={{ fontSize: "13px", color: COLORS.textLight, marginTop: "2px" }}>
{child.edad} años · {child.relacion}
</div>
{childTooOld && (
<div style={{ fontSize: "12px", color: COLORS.error, fontWeight: 700, marginTop: "4px" }}>
Ya no aplica (+12 años)
</div>
)}
{child.condicion_medica && !childTooOld && (
<div style={{ fontSize: "12px", color: COLORS.error, fontWeight: 700, marginTop: "4px" }}>
⚠️ Condición médica: {child.condicion_medica}
</div>
)}
</div>
<button
onClick={(e) => { e.stopPropagation(); openEditChild(child); }}
disabled={!!editingChildId || addingNewChild}
style={{
background: COLORS.cream, border: `1px solid ${COLORS.border}`, borderRadius: "10px",
padding: "6px 10px", fontSize: "12px", color: COLORS.bark, fontWeight: 700,
fontFamily: "'Nunito', sans-serif",
cursor: (editingChildId || addingNewChild) ? "not-allowed" : "pointer",
opacity: (editingChildId || addingNewChild) ? 0.5 : 1, flexShrink: 0
}}
>
✏️ Editar
</button>
</div>
{isEditingThis && (
<Card style={{ marginTop: "-4px", marginBottom: "12px", padding: "16px", border: `2px solid ${COLORS.bark}`, boxShadow: "0 4px 16px rgba(139,105,20,0.1)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
<span style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "16px", fontWeight: 600, color: COLORS.bark }}>Editar niño/a</span>
<button onClick={closeEditChild} style={{ background: COLORS.pinkSoft, border: "none", borderRadius: "8px", padding: "4px 10px", fontSize: "13px", color: COLORS.pink, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif" }}>Cancelar ✕</button>
</div>
<InputField label="Nombre" value={editChildForm.nombre} onChange={(v) => setEditChildForm({ ...editChildForm, nombre: v })} placeholder="Nombre del niño/a" />
<InputField label="Fecha de nacimiento" type="date" value={editChildForm.cumple} onChange={(v) => setEditChildForm({ ...editChildForm, cumple: v })} min={dob.min} max={dob.max} />
{editEdadCalc !== null && !editTooOld && !editUnderMin && (
<p style={{ margin: "-8px 0 12px 4px", fontSize: "14px", fontWeight: 700, color: COLORS.bark, fontFamily: "'Nunito', sans-serif" }}>
Edad: {editEdadCalc} {editEdadCalc === 1 ? "año" : "años"}
</p>
)}
{editTooOld && (
<div style={{ background: "#FFEBEE", borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.error, fontWeight: 700, lineHeight: 1.4 }}>
Este niño ya cumplió el límite de edad. Para siguientes visitas ya no estará disponible.
</div>
)}
{editUnderMin && (
<div style={{ background: "#FFEBEE", borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.error, fontWeight: 700, lineHeight: 1.4 }}>
La edad debe ser de al menos 1 año.
</div>
)}
{editNearLimit && !editTooOld && (
<div style={{ background: COLORS.orangeSoft, borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.orange, fontWeight: 700, lineHeight: 1.4 }}>
⚠️ Edad próxima al límite. Wonderloo es para niños hasta 11 años.
</div>
)}
<InputField label="Parentesco contigo" icon="👨‍👩‍👧" value={editChildForm.relacion} onChange={(v) => setEditChildForm({ ...editChildForm, relacion: v })} options={RELACIONES} placeholder="¿Qué eres del niño/a?" />
<InputField label="Condición médica" value={editChildForm.condicion_medica} onChange={(v) => setEditChildForm({ ...editChildForm, condicion_medica: v })} placeholder="Ej: Autismo, Síndrome de Down, TDAH" required={false} />
<Btn onClick={saveEditChild} disabled={!editChildForm.nombre || !editChildForm.cumple || !editChildForm.relacion || editTooOld || editUnderMin || editEdadCalc === null}>Guardar cambios ✓</Btn>
</Card>
)}
</React.Fragment>
);
})}
{!addingNewChild && !editingChildId ? (
<button onClick={() => setAddingNewChild(true)} style={{ width: "100%", padding: "14px", borderRadius: "14px", border: `2px dashed ${COLORS.bark}`, background: COLORS.cream, color: COLORS.bark, fontSize: "16px", fontWeight: 700, fontFamily: "'Nunito', sans-serif", cursor: "pointer", marginTop: "4px" }}>+ Agregar un niño nuevo</button>
) : addingNewChild ? (
<Card style={{ marginTop: "8px", padding: "16px", border: `2px solid ${COLORS.bark}`, boxShadow: "0 4px 16px rgba(139,105,20,0.1)" }}>
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
<span style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "16px", fontWeight: 600, color: COLORS.bark }}>Nuevo niño/a</span>
<button onClick={() => setAddingNewChild(false)} style={{ background: COLORS.pinkSoft, border: "none", borderRadius: "8px", padding: "4px 10px", fontSize: "13px", color: COLORS.pink, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif" }}>Cancelar ✕</button>
</div>
<InputField label="Nombre" value={newChildForReturn.nombre} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, nombre: v })} placeholder="Nombre del niño/a" />
<InputField label="Fecha de nacimiento" type="date" value={newChildForReturn.cumple} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, cumple: v })} min={dob.min} max={dob.max} />
{newChildEdadCalc !== null && !newChildTooOld && !newChildUnderMin && (
<p style={{ margin: "-8px 0 12px 4px", fontSize: "14px", fontWeight: 700, color: COLORS.bark, fontFamily: "'Nunito', sans-serif" }}>
Edad: {newChildEdadCalc} {newChildEdadCalc === 1 ? "año" : "años"}
</p>
)}
{newChildTooOld && (
<div style={{ background: "#FFEBEE", borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.error, fontWeight: 700, lineHeight: 1.4 }}>
Wonderloo es para niños de 1 a 11 años. No podemos registrar a menores de 12 años o más.
</div>
)}
{newChildUnderMin && (
<div style={{ background: "#FFEBEE", borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.error, fontWeight: 700, lineHeight: 1.4 }}>
La edad debe ser de al menos 1 año.
</div>
)}
{newChildNearLimit && !newChildTooOld && (
<div style={{ background: COLORS.orangeSoft, borderRadius: "10px", padding: "10px 12px", marginBottom: "12px", fontSize: "13px", color: COLORS.orange, fontWeight: 700, lineHeight: 1.4 }}>
⚠️ Edad próxima al límite. Wonderloo es para niños hasta 11 años.
</div>
)}
<InputField label="Parentesco contigo" icon="👨‍👩‍👧" value={newChildForReturn.relacion} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, relacion: v })} options={RELACIONES} placeholder="¿Qué eres del niño/a?" />
<InputField label="Condición médica" value={newChildForReturn.condicion_medica} onChange={(v) => setNewChildForReturn({ ...newChildForReturn, condicion_medica: v })} placeholder="Ej: Autismo, Síndrome de Down, TDAH" required={false} />
<Btn onClick={confirmAddNewChild} disabled={!newChildForReturn.nombre || !newChildForReturn.cumple || !newChildForReturn.relacion || newChildTooOld || newChildUnderMin || newChildEdadCalc === null}>Agregar a mi cuenta ✓</Btn>
</Card>
) : null}
</div>);
}
case "service": {
const serviceOptions = [
{ id: "hora", title: "1 Hora", price: `$${precios.nino_hora}`, extra: `+ $${precios.hora_extra} hora extra`, color: COLORS.orangeSoft, accent: COLORS.orange, icon: "⏱️" },
{ id: "daypass", title: "Daypass", price: `$${precios.nino_daypass}`, extra: "Todo el día", color: COLORS.pinkSoft, accent: COLORS.pink, icon: "🌟" },
{ id: "playday", title: "PlayDay", price: `$${precios.playday_10_entradas}`, extra: "10 visitas", color: "#E8F5E9", accent: COLORS.leaf, icon: "🎟️" },
];
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Tipo de entrada 🎟️</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Selecciona el servicio para cada niño</p>
{activeChildren.map((child, idx) => (
<Card key={child.id || idx} style={{ marginBottom: "14px", padding: "14px 16px" }}>
<div style={{ fontSize: "16px", fontWeight: 800, color: COLORS.text, fontFamily: "'Fredoka', sans-serif", marginBottom: "10px" }}>👶 {child.nombre}</div>
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: "8px" }}>
{serviceOptions.map((o) => {
const sel = serviciosPorNino[idx] === o.id;
return (
<button
key={o.id}
onClick={() => setServiciosPorNino({ ...serviciosPorNino, [idx]: o.id })}
style={{
padding: "10px 6px", borderRadius: "12px",
border: sel ? `3px solid ${o.accent}` : `2px solid ${COLORS.border}`,
background: sel ? o.color : COLORS.white,
cursor: "pointer", textAlign: "center", boxSizing: "border-box",
transition: "all 0.15s ease",
boxShadow: sel ? `0 2px 10px ${o.accent}22` : "none",
}}
>
<div style={{ fontSize: "22px", lineHeight: 1 }}>{o.icon}</div>
<div style={{ fontSize: "13px", fontWeight: 700, color: COLORS.text, marginTop: "4px" }}>{o.title}</div>
<div style={{ fontSize: "14px", fontWeight: 900, color: o.accent, fontFamily: "'Fredoka', sans-serif", marginTop: "2px" }}>{o.price}</div>
<div style={{ fontSize: "10px", color: COLORS.textLight, marginTop: "2px", lineHeight: 1.2 }}>{o.extra}</div>
</button>
);
})}
</div>
</Card>
))}
<Card style={{ padding: "14px 16px", background: COLORS.sky, boxShadow: "none", marginBottom: "20px" }}>
<p style={{ margin: 0, fontSize: "13px", color: COLORS.blue, lineHeight: 1.5 }}>💡 Precios por niño. Adultos: Daypass ${precios.adulto_daypass}, 1 Hora ${precios.adulto_hora}. Calcetas: ${precios.calcetas}.</p>
</Card>
<h3 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "20px", color: COLORS.text, margin: "0 0 4px 0" }}>Método de pago 💳</h3>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 16px 0" }}>Un solo método disponible por ahora</p>
<button onClick={() => setMetodoPago("mostrador")} style={{ width: "100%", padding: "22px 20px", borderRadius: "18px", border: `3px solid ${COLORS.bark}`, background: COLORS.cream, cursor: "pointer", textAlign: "left", boxSizing: "border-box", display: "flex", alignItems: "center", gap: "16px", marginBottom: "12px" }}>
<div style={{ fontSize: "36px", flexShrink: 0 }}>🏪</div>
<div>
<div style={{ fontSize: "18px", fontWeight: 800, color: COLORS.text, fontFamily: "'Fredoka', sans-serif" }}>Cobro en caja</div>
<div style={{ fontSize: "13px", color: COLORS.textLight, marginTop: "3px" }}>Efectivo o tarjeta</div>
</div>
</button>
</div>);
}
case "promos":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Promociones de la semana 🎁</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 20px 0" }}>Aplica al instante en mostrador</p>
{[
{ icon: "🧁", titulo: "Muffin del día", desc: "Daypass + bebida especial incluida. Lunes a viernes.", accent: COLORS.orange, bg: COLORS.orangeSoft },
{ icon: "🎉", titulo: "Pack familiar", desc: "2 o más niños: 15% de descuento en Daypass", accent: COLORS.pink, bg: COLORS.pinkSoft },
{ icon: "🌟", titulo: "Cumpleañero gratis", desc: "Si el niño cumple años esta semana, su Daypass es cortesía", accent: COLORS.leaf, bg: "#E8F5E9" },
].map((p, i) => (
<Card key={i} style={{ marginBottom: "12px", padding: "16px 18px", border: `2px solid ${p.bg}`, background: p.bg, boxShadow: "none" }}>
<div style={{ display: "flex", alignItems: "flex-start", gap: "14px" }}>
<div style={{ fontSize: "32px", flexShrink: 0, lineHeight: 1 }}>{p.icon}</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: "17px", fontWeight: 800, color: COLORS.text, fontFamily: "'Fredoka', sans-serif" }}>{p.titulo}</div>
<div style={{ fontSize: "13px", color: COLORS.textLight, marginTop: "4px", lineHeight: 1.5 }}>{p.desc}</div>
</div>
</div>
</Card>
))}
<Card style={{ padding: "14px 16px", background: COLORS.sky, boxShadow: "none", marginTop: "12px" }}>
<p style={{ margin: 0, fontSize: "12px", color: COLORS.blue, lineHeight: 1.5, fontWeight: 700 }}>
Precios sin promoción — Daypass ${precios.nino_daypass} · 1 Hora ${precios.nino_hora} · PlayDay ${precios.playday_10_entradas} (10 entradas)
</p>
</Card>
</div>);
case "responsiva":
return (<div>
<h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: "24px", color: COLORS.text, margin: "0 0 4px 0" }}>Responsiva y firma ✍️</h2>
<p style={{ fontSize: "14px", color: COLORS.textLight, margin: "0 0 16px 0" }}>Último paso — lee y firma</p>
<div style={{ maxHeight: "200px", overflowY: "auto", padding: "16px", background: COLORS.white, borderRadius: "14px", border: `1px solid ${COLORS.border}`, marginBottom: "16px", fontSize: "13px", color: COLORS.textLight, lineHeight: 1.7, whiteSpace: "pre-line" }}>{RESPONSIVA}</div>
<label style={{ display: "flex", alignItems: "flex-start", gap: "12px", marginBottom: "20px", cursor: "pointer", padding: "14px 16px", borderRadius: "14px", background: aceptaResponsiva ? "#E8F5E9" : COLORS.cream, border: `2px solid ${aceptaResponsiva ? COLORS.leaf : COLORS.border}`, transition: "all 0.2s" }}>
<div onClick={() => setAceptaResponsiva(!aceptaResponsiva)} style={{ width: "28px", height: "28px", borderRadius: "8px", flexShrink: 0, background: aceptaResponsiva ? COLORS.leaf : COLORS.white, border: `2px solid ${aceptaResponsiva ? COLORS.leaf : COLORS.border}`, display: "flex", alignItems: "center", justifyContent: "center", marginTop: "2px", cursor: "pointer", transition: "all 0.2s" }}>
{aceptaResponsiva && <span style={{ color: COLORS.white, fontSize: "16px", fontWeight: 900 }}>✓</span>}
</div>
<span style={{ fontSize: "15px", color: COLORS.text, fontWeight: 600, lineHeight: 1.5 }}>He leído y acepto la responsiva y el reglamento de Wonderloo Indoor Park</span>
</label>
{aceptaResponsiva && <div style={{ animation: "fadeUp 0.3s ease-out" }}><p style={{ fontSize: "15px", fontWeight: 700, color: COLORS.text, margin: "0 0 8px 0" }}>Tu firma:</p><SignaturePad onSign={setSignature} /></div>}
</div>);
default: return null;
}
};
return (
<React.Fragment>
<div style={{ minHeight: "100vh", background: `linear-gradient(180deg, ${COLORS.warmBg} 0%, ${COLORS.cream} 100%)`, fontFamily: "'Nunito', sans-serif" }}>
<Fonts />
<div style={{ position: "sticky", top: 0, zIndex: 10, background: `${COLORS.warmBg}F0`, backdropFilter: "blur(12px)", padding: "12px 20px 4px", borderBottom: `1px solid ${COLORS.cream}` }}>
<div style={{ maxWidth: "420px", margin: "0 auto", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
<button onClick={goBack} style={{ background: "none", border: "none", fontSize: "16px", color: COLORS.bark, cursor: "pointer", fontWeight: 700, fontFamily: "'Nunito', sans-serif", padding: "8px 0" }}>← Atrás</button>
<span style={{ fontSize: "14px", color: COLORS.textLight, fontWeight: 600 }}>{stepLabels[currentStepName]} · Paso {step + 1} de {totalSteps}</span>
<div style={{ width: "60px" }} />
</div>
<div style={{ maxWidth: "420px", margin: "0 auto" }}><ProgressDots current={step} total={totalSteps} /></div>
</div>
<div style={{ maxWidth: "420px", margin: "0 auto", padding: "20px 20px 100px" }}>{renderStep()}</div>
<div style={{ position: "fixed", bottom: 0, left: 0, right: 0, padding: "16px 20px", background: `linear-gradient(0deg, ${COLORS.warmBg} 80%, ${COLORS.warmBg}00 100%)` }}>
<div style={{ maxWidth: "420px", margin: "0 auto" }}>
<Btn onClick={isLastStep ? handleSubmit : (currentStepName === "tutor" ? advanceFromTutor : goNext)} disabled={submitLoading || checkingDuplicate || !canProceed()} variant={isLastStep ? "success" : "primary"}>{submitLoading ? "Registrando..." : (checkingDuplicate ? "Verificando..." : (isLastStep ? "Firmar y registrar ✓" : "Continuar →"))}</Btn>
</div>
</div>
<style>{`@keyframes fadeUp { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } } @keyframes popIn { from { transform:scale(0); } to { transform:scale(1); } } * { -webkit-tap-highlight-color: transparent; } input, select { font-size: 17px !important; }`}</style>
</div>
{toast && <ToastBanner toast={toast} />}
{duplicateTutor && (
<div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.55)", zIndex: 300, display: "flex", alignItems: "center", justifyContent: "center", padding: "20px", fontFamily: "'Nunito', sans-serif" }}>
<Card style={{ maxWidth: "420px", width: "100%", padding: "28px 24px" }}>
<div style={{ textAlign: "center", marginBottom: "20px" }}>
<div style={{ fontSize: "48px", marginBottom: "10px" }}>📱</div>
<h3 style={{ margin: "0 0 8px 0", fontFamily: "'Fredoka', sans-serif", fontSize: "22px", color: COLORS.text }}>Ya tenemos este número</h3>
<p style={{ margin: 0, fontSize: "15px", color: COLORS.textLight, lineHeight: 1.5 }}>
El teléfono <strong>{duplicateTutor.telefono}</strong> ya está registrado a nombre de <strong>{duplicateTutor.nombre.split(" ")[0]}</strong>.
</p>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: "10px" }}>
<Btn onClick={handleDuplicateUseIt} variant="success">Sí, usar esta cuenta →</Btn>
<Btn onClick={handleDuplicateDismiss} variant="outline">No, cambiar número</Btn>
</div>
</Card>
</div>
)}
</React.Fragment>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(<WonderlooCheckin />);
</script>
</body>
</html>