import React, { useState, useEffect, useCallback } from 'react'; import { Link } from 'react-router-dom'; import { PublicLayout } from '../../components/layout'; import { Button } from '../../components/ui'; import { getDemoAccounts, createDemoSession, DemoAccount, demoSessionAPI } from '../../api/services/demo'; import { apiClient } from '../../api/client'; import { Check, Clock, Shield, Play, Zap, ArrowRight, Store, Factory, Loader2 } from 'lucide-react'; import { markTourAsStartPending } from '../../features/demo-onboarding'; const POLL_INTERVAL_MS = 1500; // Poll every 1.5 seconds export const DemoPage: React.FC = () => { const [demoAccounts, setDemoAccounts] = useState([]); const [loading, setLoading] = useState(true); const [creatingSession, setCreatingSession] = useState(false); const [error, setError] = useState(null); const [progressPercentage, setProgressPercentage] = useState(0); const [estimatedTime, setEstimatedTime] = useState(5); useEffect(() => { const fetchDemoAccounts = async () => { try { const accounts = await getDemoAccounts(); setDemoAccounts(accounts); } catch (err) { setError('Error al cargar las cuentas demo'); console.error('Error fetching demo accounts:', err); } finally { setLoading(false); } }; fetchDemoAccounts(); }, []); const pollStatus = useCallback(async (sessionId: string) => { try { const statusData = await demoSessionAPI.getSessionStatus(sessionId); // Calculate progress - ALWAYS update, even if no progress data yet if (statusData.progress && Object.keys(statusData.progress).length > 0) { const services = Object.values(statusData.progress); const totalServices = services.length; if (totalServices > 0) { const completedServices = services.filter( (s) => s.status === 'completed' || s.status === 'failed' ).length; const percentage = Math.round((completedServices / totalServices) * 100); setProgressPercentage(percentage); // Estimate remaining time const remainingServices = totalServices - completedServices; setEstimatedTime(Math.max(remainingServices * 2, 1)); } else { // No services yet, show minimal progress setProgressPercentage(5); } } else { // No progress data yet, show initial state setProgressPercentage(10); } // Check if ready to redirect const hasUsableData = statusData.total_records_cloned > 100; const shouldRedirect = statusData.status === 'ready' || (statusData.status === 'partial' && hasUsableData) || (statusData.status === 'failed' && hasUsableData); if (shouldRedirect) { // Show 100% before redirect setProgressPercentage(100); // Small delay for smooth transition setTimeout(() => { window.location.href = `/app/dashboard?session=${sessionId}`; }, 300); return true; // Stop polling } return false; // Continue polling } catch (err) { console.error('Error polling session status:', err); return false; } }, []); const handleStartDemo = async (accountType: string) => { setCreatingSession(true); setError(null); setProgressPercentage(0); setEstimatedTime(6); try { const session = await createDemoSession({ demo_account_type: accountType as 'individual_bakery' | 'central_baker', }); console.log('✅ Demo session created:', session); // Store session ID in API client apiClient.setDemoSessionId(session.session_id); // Set the virtual tenant ID in API client apiClient.setTenantId(session.virtual_tenant_id); console.log('✅ Set API client tenant ID:', session.virtual_tenant_id); // Store session info in localStorage for UI localStorage.setItem('demo_mode', 'true'); localStorage.setItem('demo_session_id', session.session_id); localStorage.setItem('demo_account_type', accountType); localStorage.setItem('demo_expires_at', session.expires_at); localStorage.setItem('demo_tenant_id', session.virtual_tenant_id); // Start polling IMMEDIATELY in parallel with other setup const pollInterval = setInterval(async () => { const shouldStop = await pollStatus(session.session_id); if (shouldStop) { clearInterval(pollInterval); } }, POLL_INTERVAL_MS); // Initialize tenant store and other setup in parallel (non-blocking) Promise.all([ import('../../stores/tenant.store').then(({ useTenantStore }) => { const demoTenant = { id: session.virtual_tenant_id, name: session.demo_config?.name || `Demo ${accountType}`, business_type: accountType === 'individual_bakery' ? 'bakery' : 'central_baker', business_model: accountType, address: session.demo_config?.address || 'Demo Address', city: session.demo_config?.city || 'Madrid', postal_code: '28001', phone: null, is_active: true, subscription_tier: 'demo', ml_model_trained: false, last_training_date: null, owner_id: 'demo-user', created_at: new Date().toISOString(), }; useTenantStore.getState().setCurrentTenant(demoTenant); console.log('✅ Initialized tenant store with demo tenant:', demoTenant); }), // Mark tour to start automatically Promise.resolve(markTourAsStartPending()), ]).catch(err => console.error('Error initializing tenant store:', err)); // Initial poll (don't wait for tenant store) const shouldStop = await pollStatus(session.session_id); if (shouldStop) { clearInterval(pollInterval); } } catch (err: any) { setError(err?.message || 'Error al crear sesión demo'); console.error('Error creating demo session:', err); setCreatingSession(false); } }; const getAccountIcon = (accountType: string) => { return accountType === 'individual_bakery' ? Store : Factory; }; if (loading) { return (

Cargando cuentas demo...

); } return ( {/* Hero Section */}
Demo Interactiva

Prueba BakeryIA sin compromiso

Explora nuestro sistema con datos reales de panaderías españolas. Elige el tipo de negocio que mejor se adapte a tu caso.

Sin tarjeta de crédito
30 minutos de acceso
Datos aislados y seguros
{error && (
{error}
)} {/* Demo Account Cards */}
{demoAccounts.map((account) => { const Icon = getAccountIcon(account.account_type); return (
{/* Gradient overlay */}
{/* Header */}

{account.name}

{account.business_model}

DEMO
{/* Description */}

{account.description}

{/* Features */} {account.features && account.features.length > 0 && (

Funcionalidades incluidas:

{account.features.map((feature, idx) => (
{feature}
))}
)} {/* Demo Benefits */}
Datos reales en español
Sesión aislada de 30 minutos
Sin necesidad de registro
{/* CTA Button */}
); })}
{/* Footer CTA */}

¿Ya tienes una cuenta?

Inicia sesión aquí
{/* Loading Modal Overlay */} {creatingSession && (
{/* Animated loader */}
{Math.min(progressPercentage, 100)}%

{progressPercentage >= 100 ? '¡Listo! Redirigiendo...' : 'Preparando tu Demo'}

{progressPercentage >= 100 ? 'Tu entorno está listo. Accediendo al dashboard...' : 'Configurando tu entorno personalizado con datos de muestra...'}

{/* Progress bar */}
{/* Estimated time - Only show if not complete */} {progressPercentage < 100 && (
Tiempo estimado: ~{estimatedTime}s
)} {/* Tips while loading */} {progressPercentage < 100 && (

💡 Tip: La demo incluye datos reales de panaderías españolas para que puedas explorar todas las funcionalidades

)} {/* Error message if any */} {error && (
{error}
)}
)} ); }; export default DemoPage;