// ============================================================ // Qestylo — Coco, asesor virtual (portado de la web principal) // Backend: api/chat.php · Panel: admin-chats.html // ============================================================ const { useState, useEffect, useRef, useCallback } = React; /* ─── Utilidades del efecto "genie" de macOS (scanline en canvas) ─── */ const cocoClamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v)); const cocoLerp = (a, b, t) => a + (b - a) * t; const cocoEaseInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2); const cocoEaseIn = (t) => t * t; const cocoEaseOut = (t) => 1 - (1 - t) * (1 - t); const COCO_GENIE_MS = 320; function cocoRenderGenie(ctx, off, W, H, rawT, dir, dock, win, winW, winH) { ctx.clearRect(0, 0, W, H); // Al cerrar se invierte el tiempo: es exactamente la animación inversa const t = dir === 'minimize' ? 1 - rawT : rawT; const step = 2; for (let y = 0; y < winH; y += step) { const r = y / winH; const rowXStart = r * 0.55; const xE = cocoEaseInOut(cocoClamp((t - rowXStart) / (1 - rowXStart), 0, 1)); const rowYStart = r * 0.25; const yE = cocoEaseIn(cocoClamp((t - rowYStart) / (1 - rowYStart), 0, 1)); const left = cocoLerp(dock.x, win.x, xE); const right = cocoLerp(dock.x, win.x + winW, xE); const destY = cocoLerp(dock.y, win.y + y, yE); const rowW = right - left; if (rowW < 0.8) continue; const sliceH = Math.min(step, winH - y); ctx.drawImage(off, 0, y, winW, sliceH, left, destY, rowW, sliceH); } // Resplandor ámbar al salir de / volver a la mascota const glowRaw = dir === 'minimize' ? rawT : 1 - rawT; if (glowRaw > 0.7) { const a = cocoEaseOut((glowRaw - 0.7) / 0.3) * 0.45; const hex = Math.round(a * 255).toString(16).padStart(2, '0'); const g = ctx.createRadialGradient(dock.x, dock.y, 0, dock.x, dock.y, 70); g.addColorStop(0, '#F5B07F' + hex); g.addColorStop(0.45, '#E97A38' + hex); g.addColorStop(1, 'transparent'); ctx.fillStyle = g; ctx.fillRect(0, 0, W, H); } } // Dibujo rápido de la ventana para la animación (el DOM real no se puede rasterizar con backdrop-filter) function cocoGenieCanvas(winW, winH) { const c = document.createElement('canvas'); c.width = winW; c.height = winH; const ctx = c.getContext('2d'); if (!ctx) return c; const rr = (x, y, w, h, r) => { ctx.beginPath(); if (ctx.roundRect) ctx.roundRect(x, y, w, h, r); else ctx.rect(x, y, w, h); }; ctx.save(); ctx.fillStyle = 'rgba(20, 17, 15, 0.96)'; rr(0, 0, winW, winH, [18]); ctx.fill(); ctx.strokeStyle = 'rgba(233, 122, 56, 0.4)'; ctx.lineWidth = 1; ctx.stroke(); // cabecera ctx.fillStyle = 'rgba(255, 255, 255, 0.03)'; ctx.fillRect(0, 0, winW, 64); ctx.fillStyle = 'rgba(255, 255, 255, 0.08)'; ctx.fillRect(0, 63, winW, 1); ctx.fillStyle = '#2A2521'; ctx.beginPath(); ctx.arc(36, 32, 20, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = 'rgba(233, 122, 56, 0.6)'; ctx.lineWidth = 1.5; ctx.stroke(); ctx.fillStyle = '#F5F1EA'; ctx.font = '600 16px Fraunces, serif'; ctx.fillText('Coco', 68, 29); ctx.fillStyle = 'rgba(233, 122, 56, 0.2)'; rr(118, 17, 60, 16, [8]); ctx.fill(); ctx.fillStyle = '#F5B07F'; ctx.font = 'bold 9px Inter, sans-serif'; ctx.fillText('ASESOR IA', 124, 28); ctx.fillStyle = 'rgba(245, 241, 234, 0.6)'; ctx.font = '11px Inter, sans-serif'; ctx.fillText('Ventanas Kömmerling · Valladolid', 68, 46); ctx.fillStyle = 'rgba(255, 255, 255, 0.06)'; ctx.beginPath(); ctx.arc(winW - 32, 32, 16, 0, Math.PI * 2); ctx.fill(); // burbuja de bienvenida ctx.fillStyle = 'rgba(255, 255, 255, 0.08)'; rr(56, 80, winW - 72, 90, [14]); ctx.fill(); ctx.fillStyle = 'rgba(245, 241, 234, 0.95)'; ctx.font = '13.5px Inter, sans-serif'; ctx.fillText('¡Hola! Soy Coco, el asesor virtual', 72, 104); ctx.fillText('de Qestylo en Valladolid.', 72, 124); ctx.fillText('¿En qué te puedo ayudar?', 72, 148); // barra de entrada ctx.fillStyle = 'rgba(14, 12, 10, 0.9)'; ctx.fillRect(0, winH - 76, winW, 76); ctx.fillStyle = 'rgba(255, 255, 255, 0.07)'; rr(16, winH - 60, winW - 32, 44, [22]); ctx.fill(); ctx.fillStyle = 'rgba(245, 241, 234, 0.4)'; ctx.font = '14px Inter, sans-serif'; ctx.fillText('Pregúntale a Coco por tus ventanas...', 32, winH - 33); ctx.restore(); return c; } function cocoCleanText(text) { if (!text || typeof text !== 'string') return ''; return text .replace(/\*\*([^*]+)\*\*/g, '$1') .replace(/\*([^*]+)\*/g, '$1') .replace(/\*{1,3}/g, '') .replace(/__([^_]+)__/g, '$1') .replace(/^#+\s*/gm, '') .replace(/^\s*-\s+/gm, '• ') .trim(); } /* ─── Sello "verificado" (Iconiq UI), en los tonos de esta web ─── */ const COCO_SCALLOP = 'M20.396 11c-.018-.646-.215-1.275-.57-1.816-.354-.54-.852-.972-1.438-1.246.223-.607.27-1.264.14-1.897-.131-.634-.437-1.218-.882-1.687-.47-.445-1.053-.75-1.687-.882-.633-.13-1.29-.083-1.897.14-.273-.587-.704-1.086-1.245-1.44S11.647 1.62 11 1.604c-.646.017-1.273.213-1.813.568s-.969.854-1.24 1.44c-.608-.223-1.267-.272-1.902-.14-.635.13-1.22.436-1.69.882-.445.47-.749 1.055-.878 1.688-.13.633-.08 1.29.144 1.896-.587.274-1.087.705-1.443 1.245-.356.54-.555 1.17-.574 1.817.02.647.218 1.276.574 1.817.356.54.856.972 1.443 1.245-.224.606-.274 1.263-.144 1.896.13.634.433 1.218.877 1.688.47.443 1.054.747 1.687.878.633.132 1.29.084 1.897-.136.274.586.705 1.084 1.246 1.439.54.354 1.17.551 1.816.569.647-.016 1.276-.213 1.817-.567s.972-.854 1.245-1.44c.604.239 1.266.296 1.903.164.636-.132 1.22-.447 1.68-.907.46-.46.776-1.044.908-1.681s.075-1.299-.165-1.903c.586-.274 1.084-.705 1.439-1.246.354-.54.551-1.17.569-1.816z'; const COCO_SCALLOP_MASK = `url("data:image/svg+xml,${encodeURIComponent( '' )}")`; function CocoVerifiedBadge({ size = 16, title = 'Asesor oficial verificado' }) { const checkSize = Math.round(size * 0.52); const mask = { maskImage: COCO_SCALLOP_MASK, WebkitMaskImage: COCO_SCALLOP_MASK, maskSize: '100% 100%', WebkitMaskSize: '100% 100%', maskRepeat: 'no-repeat', WebkitMaskRepeat: 'no-repeat', }; return ( ); } /* ─── Configuración ─── */ const COCO_WELCOME = '¡Hola! Soy Coco, el asesor virtual de Qestylo, distribuidor oficial Kömmerling en Valladolid.\n\n¿Te ayudo a elegir ventanas, puertas o persianas? Pregúntame lo que quieras o pide tu presupuesto sin compromiso.'; const COCO_ERROR = 'Perdona, ahora mismo no puedo responder. Llámanos al 983 266 408 y te atendemos encantados.'; const COCO_QUICK = [ 'Quiero pedir presupuesto', '¿Qué ventana me recomiendas?', 'Persianas y cajón RolaPlus', '¿Cómo es la instalación?', 'Tienda y teléfono', ]; const COCO_MAX_CHARS = 800; const COCO_TEASER_DELAY_MS = 1500; const COCO_TEASER_MS = 6000; // Zona que ocupa el botón flotante (esquina inferior izquierda) para no tapar CTA, teléfonos ni formularios const COCO_FAB_AVOID = '[data-fab-avoid], a[href^="tel:"], a[href^="mailto:"], input, textarea'; function cocoPrefersReducedMotion() { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } function cocoSaveData() { const c = navigator.connection; return !!(c && c.saveData); } function cocoStorage(kind) { try { return window[kind]; } catch (e) { return null; } } /* ─── CocoChat ─── */ function CocoChat() { const [phase, setPhase] = useState('idle'); // idle | opening | open | closing const [dockAbsorb, setDockAbsorb] = useState(false); const [teaser, setTeaser] = useState(false); const [fabHidden, setFabHidden] = useState(false); const [videoOn, setVideoOn] = useState(false); const [videoVisible, setVideoVisible] = useState(false); const [messages, setMessages] = useState([{ role: 'assistant', content: COCO_WELCOME, time: 'Ahora' }]); const [input, setInput] = useState(''); const [loading, setLoading] = useState(false); const [unread, setUnread] = useState(0); const [sessionId] = useState(() => { const store = cocoStorage('sessionStorage'); const make = () => 'kom_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 10); try { let id = store && store.getItem('qe_kom_chat_sid'); if (!id || !/^[A-Za-z0-9_-]{8,64}$/.test(id)) { id = make(); store && store.setItem('qe_kom_chat_sid', id); } return id; } catch (e) { return make(); } }); const endRef = useRef(null); const inputRef = useRef(null); const windowRef = useRef(null); const buttonRef = useRef(null); const fabRef = useRef(null); const teaserRef = useRef(null); const teaserOnRef = useRef(false); const canvasRef = useRef(null); const snapshotRef = useRef(null); const rafRef = useRef(0); const videoRef = useRef(null); const phaseRef = useRef('idle'); phaseRef.current = phase; teaserOnRef.current = teaser; const isOpen = phase === 'open'; const isAnimating = phase === 'opening' || phase === 'closing'; const hasUserMessages = messages.some((m) => m.role === 'user'); // Avisar al resto de la página (el botón de WhatsApp se oculta con el chat abierto) const announce = (open) => window.dispatchEvent(new CustomEvent('qestylo-chat-toggle', { detail: { open } })); useEffect(() => { if (isOpen) endRef.current?.scrollIntoView({ behavior: cocoPrefersReducedMotion() ? 'auto' : 'smooth', block: 'end' }); }, [messages, loading, isOpen]); useEffect(() => { if (!isOpen) return; setUnread(0); const t = setTimeout(() => { if (inputRef.current && window.innerWidth >= 768) inputRef.current.focus(); }, 100); return () => clearTimeout(t); }, [isOpen]); // Vídeo de la mascota: solo si no hay "reducir movimiento" ni ahorro de datos, y después de cargar la página useEffect(() => { if (cocoPrefersReducedMotion() || cocoSaveData()) return; const start = () => setVideoOn(true); if (document.readyState === 'complete') { const t = setTimeout(start, 1200); return () => clearTimeout(t); } window.addEventListener('load', start, { once: true }); return () => window.removeEventListener('load', start); }, []); // Bucle de la animación: se funde al terminar, descansa y vuelve a empezar useEffect(() => { const video = videoRef.current; if (!videoOn || !video) return; let restTimer = null; let fading = false; const restart = () => { setVideoVisible(false); clearTimeout(restTimer); restTimer = setTimeout(() => { fading = false; try { video.currentTime = 0; const p = video.play(); if (p && p.then) p.then(() => setVideoVisible(true)).catch(() => {}); else setVideoVisible(true); } catch (e) {} }, 350); }; const onTime = () => { const dur = video.duration || 5; if (video.currentTime >= dur - 0.25 && !fading) { fading = true; setVideoVisible(false); } }; const onPlaying = () => setVideoVisible(true); video.addEventListener('timeupdate', onTime); video.addEventListener('ended', restart); video.addEventListener('playing', onPlaying); const p = video.play(); if (p && p.catch) p.catch(() => {}); return () => { video.removeEventListener('timeupdate', onTime); video.removeEventListener('ended', restart); video.removeEventListener('playing', onPlaying); clearTimeout(restTimer); }; }, [videoOn]); // El botón flotante se esconde mientras debajo hay un CTA, un teléfono o un formulario useEffect(() => { let raf = 0; const check = () => { raf = 0; if (phaseRef.current !== 'idle') { setFabHidden(false); return; } const fab = fabRef.current; const btn = buttonRef.current; if (!fab || !btn) return; // Zona del botón (+ el bocadillo si está a la vista), sin el desplazamiento de la animación de ocultar const pad = 8; const shift = fab.classList.contains('translate-y-4') ? 16 : 0; const rb = btn.getBoundingClientRect(); let right = rb.right; let top = rb.top; if (teaserOnRef.current && teaserRef.current) { const rt = teaserRef.current.getBoundingClientRect(); right = Math.max(right, rt.right); top = Math.min(top, rt.top); } const zone = { left: 0, right: right + pad, top: top - shift - pad, bottom: window.innerHeight }; let hit = false; const els = document.querySelectorAll(COCO_FAB_AVOID); for (let i = 0; i < els.length && !hit; i++) { const el = els[i]; if (el.closest('#coco-root')) continue; const r = el.getBoundingClientRect(); if (r.width === 0 || r.height === 0) continue; if (r.left < zone.right && r.right > zone.left && r.top < zone.bottom && r.bottom > zone.top) hit = true; } setFabHidden(hit); }; const schedule = () => { if (!raf) raf = requestAnimationFrame(check); }; window.addEventListener('scroll', schedule, { passive: true }); window.addEventListener('resize', schedule); const interval = setInterval(schedule, 500); // por si cambia el contenido sin scroll (pestañas, modales...) schedule(); return () => { window.removeEventListener('scroll', schedule); window.removeEventListener('resize', schedule); clearInterval(interval); cancelAnimationFrame(raf); }; }, []); // Bocadillo de bienvenida (una vez por sesión) useEffect(() => { const store = cocoStorage('sessionStorage'); try { if (store && store.getItem('qe_kom_chat_seen')) return; } catch (e) {} const show = setTimeout(() => { if (phaseRef.current === 'idle') setTeaser(true); }, COCO_TEASER_DELAY_MS); const hide = setTimeout(() => setTeaser(false), COCO_TEASER_DELAY_MS + COCO_TEASER_MS); return () => { clearTimeout(show); clearTimeout(hide); }; }, []); const getDock = useCallback(() => { const btn = buttonRef.current; if (!btn) return { x: 60, y: window.innerHeight - 60 }; const r = btn.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }, []); const getWindowGeom = useCallback(() => { const r = windowRef.current.getBoundingClientRect(); return { win: { x: r.left, y: r.top }, winW: Math.round(r.width), winH: Math.round(r.height) }; }, []); const setupCanvas = useCallback(() => { const c = canvasRef.current; if (!c) return null; const dpr = Math.min(window.devicePixelRatio || 1, 2); c.width = window.innerWidth * dpr; c.height = window.innerHeight * dpr; const ctx = c.getContext('2d'); if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0); return ctx; }, []); const clearCanvas = useCallback(() => { const c = canvasRef.current; const ctx = c && c.getContext('2d'); if (!ctx) return; ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, c.width, c.height); ctx.restore(); }, []); useEffect(() => { if (phase === 'open' || phase === 'idle') clearCanvas(); }, [phase, clearCanvas]); const runGenie = useCallback((dir, done) => { const ctx = setupCanvas(); if (!ctx || cocoPrefersReducedMotion()) { done(); return; } const dock = getDock(); const { win, winW, winH } = getWindowGeom(); let off = snapshotRef.current; if (!off || off.width !== winW || off.height !== winH) { off = cocoGenieCanvas(winW, winH); snapshotRef.current = off; } const W = window.innerWidth; const H = window.innerHeight; let start = null; const frame = (ts) => { if (!start) start = ts; const t = cocoClamp((ts - start) / COCO_GENIE_MS, 0, 1); cocoRenderGenie(ctx, off, W, H, t, dir, dock, win, winW, winH); if (t < 1) rafRef.current = requestAnimationFrame(frame); else { clearCanvas(); done(); } }; rafRef.current = requestAnimationFrame(frame); }, [setupCanvas, getDock, getWindowGeom, clearCanvas]); const doOpen = useCallback(() => { if (phaseRef.current !== 'idle') return; cancelAnimationFrame(rafRef.current); if (windowRef.current) windowRef.current.style.opacity = ''; phaseRef.current = 'opening'; setPhase('opening'); announce(true); runGenie('open', () => { phaseRef.current = 'open'; setPhase('open'); }); }, [runGenie]); const doClose = useCallback(() => { if (phaseRef.current !== 'open') return; cancelAnimationFrame(rafRef.current); if (windowRef.current) windowRef.current.style.opacity = '0'; phaseRef.current = 'closing'; setPhase('closing'); announce(false); runGenie('minimize', () => { phaseRef.current = 'idle'; setPhase('idle'); setDockAbsorb(true); setTimeout(() => setDockAbsorb(false), 350); buttonRef.current?.focus({ preventScroll: true }); }); }, [runGenie]); const onTrigger = () => { try { cocoStorage('sessionStorage')?.setItem('qe_kom_chat_seen', '1'); } catch (e) {} setTeaser(false); if (phaseRef.current === 'open') doClose(); else if (phaseRef.current === 'idle') doOpen(); }; useEffect(() => { const onKey = (e) => { if (e.key === 'Escape' && phaseRef.current === 'open') doClose(); }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [doClose]); useEffect(() => () => cancelAnimationFrame(rafRef.current), []); const send = async (text) => { const query = (typeof text === 'string' ? text : input).trim().slice(0, COCO_MAX_CHARS); if (!query || loading) return; setInput(''); const time = new Date().toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit' }); setMessages((prev) => [...prev, { role: 'user', content: query, time }]); setLoading(true); let reply = COCO_ERROR; try { const res = await fetch('api/chat.php', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ message: query, sessionId }), }); const data = await res.json().catch(() => null); if (data && typeof data.reply === 'string' && data.reply.trim()) reply = cocoCleanText(data.reply); } catch (e) {} setMessages((prev) => [...prev, { role: 'assistant', content: reply, time }]); if (phaseRef.current !== 'open') setUnread((c) => c + 1); setLoading(false); }; const openPrivacy = (e) => { e.preventDefault(); if (window.onLegalTabChange) window.onLegalTabChange('privacidad'); }; const fabVisible = isOpen || isAnimating || !fabHidden; return (
Ventanas Kömmerling · Valladolid
Guardamos esta conversación para atender tu consulta. No compartas datos sensibles. Más info en la{' '} política de privacidad .
)} {/* Accesos rápidos */}