// prototype-generator.jsx — Software Blueprint Generator & Lead Capture loop for bulltech_
const DS3 = window.BulltechDesignSystem_fb9019 || {};
const { Button: DSButton } = DS3;

// Inline SVG Icon Helpers to avoid external dependencies
const Icons = {
  SaaS: () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
      <line x1="8" y1="21" x2="16" y2="21" />
      <line x1="12" y1="17" x2="12" y2="21" />
    </svg>
  ),
  PWA: () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <rect x="5" y="2" width="14" height="20" rx="2" ry="2" />
      <line x1="12" y1="18" x2="12.01" y2="18" />
    </svg>
  ),
  Ecommerce: () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <circle cx="9" cy="21" r="1" />
      <circle cx="20" cy="21" r="1" />
      <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6" />
    </svg>
  ),
  Automation: () => (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <polyline points="22 12 18 12 15 21 9 3 6 12 2 12" />
    </svg>
  ),
  Clinic: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <path d="M22 12h-4l-3 9L9 3l-3 9H2" />
    </svg>
  ),
  Operations: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
      <line x1="2" y1="10" x2="22" y2="10" />
    </svg>
  ),
  Logistics: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <rect x="1" y="3" width="15" height="13" />
      <polygon points="16 8 20 8 23 11 23 16 16 16 16 8" />
      <circle cx="5.5" cy="18.5" r="2.5" />
      <circle cx="18.5" cy="18.5" r="2.5" />
    </svg>
  ),
  Startup: () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
    </svg>
  ),
  Terminal: () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <polyline points="4 17 10 11 4 5" />
      <line x1="12" y1="19" x2="20" y2="19" />
    </svg>
  ),
  ArrowLeft: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <line x1="19" y1="12" x2="5" y2="12" />
      <polyline points="12 19 5 12 12 5" />
    </svg>
  ),
  ArrowRight: () => (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="square" strokeLinejoin="miter">
      <line x1="5" y1="12" x2="19" y2="12" />
      <polyline points="12 5 19 12 12 19" />
    </svg>
  ),
  Check: () => (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="square" strokeLinejoin="miter">
      <polyline points="20 6 9 17 4 12" />
    </svg>
  )
};

const SOFTWARE_TYPES = [
  { id: 'SaaS', title: 'SaaS Platform', desc: 'Software en la nube multiusuario, dashboard analítico y roles.', icon: Icons.SaaS },
  { id: 'PWA', title: 'PWA Móvil', desc: 'Instalable en iOS/Android, uso offline, notificaciones y carga rápida.', icon: Icons.PWA },
  { id: 'Ecommerce', title: 'E-commerce Engine', desc: 'Catálogo de productos, checkout integrado, envíos y control de stocks.', icon: Icons.Ecommerce },
  { id: 'Automation', title: 'Automatización / IA', desc: 'Integración de flujos de trabajo, API y agentes autónomos inteligentes.', icon: Icons.Automation }
];

const VERTICALS = [
  { id: 'Salud', title: 'Salud y Clínicas', desc: 'Fichas de pacientes, citas médicas/veterinarias e historial.', icon: Icons.Clinic },
  { id: 'PyME', title: 'Operaciones PyME', desc: 'Control interno, flujos de caja, tareas y procesos administrativos.', icon: Icons.Operations },
  { id: 'Tienda', title: 'Tienda y Logística', desc: 'Facturación rápida, control de lotes, almacenes y despachos.', icon: Icons.Logistics },
  { id: 'Idea', title: 'Idea y Startup', desc: 'Prototipo escalable de validación rápida y base de datos ágil.', icon: Icons.Startup }
];

const MODULE_OPTIONS = [
  { id: 'inventario', label: 'Inventario inteligente', desc: 'Escaneo simulado, stock bajo y alertas automáticas' },
  { id: 'agenda', label: 'Agenda y Citas', desc: 'Calendario reactivo, slots ocupados y asignación' },
  { id: 'clientes', label: 'Expediente de clientes', desc: 'Perfiles ricos, búsqueda en tiempo real e historial' },
  { id: 'reportes', label: 'Reportes y BI', desc: 'Gráficas SVG vectoriales y recálculo interactivo' },
  { id: 'pagos', label: 'Pagos integrados', desc: 'Pasarela Stripe/Local simulada con checkout rápido' },
  { id: 'ia', label: 'Procesos IA', desc: 'Caja de sugerencias ejecutada por modelo generativo' }
];

// Main Component
function PrototypeGenerator({ setView }) {
  const [step, setStep] = React.useState(1);
  
  // Selections
  const [selectedType, setSelectedType] = React.useState('SaaS');
  const [selectedVertical, setSelectedVertical] = React.useState('Salud');
  const [selectedModules, setSelectedModules] = React.useState(['inventario', 'agenda', 'clientes']);
  
  // Build Simulator State
  const [buildLogs, setBuildLogs] = React.useState([]);
  const [buildProgress, setBuildProgress] = React.useState(0);
  
  // Interactive Workspace State
  const [activeTab, setActiveTab] = React.useState('');
  
  // Module 1: Inventory state
  const [inventoryItems, setInventoryItems] = React.useState([
    { id: 1, name: 'Reactors Core v2', stock: 12, code: 'RC-102-X' },
    { id: 2, name: 'Neural Chip set', stock: 4, code: 'NC-991-A' },
    { id: 3, name: 'Bifrost Cable 10m', stock: 25, code: 'BC-004-M' }
  ]);
  const [scanning, setScanning] = React.useState(false);
  
  // Module 2: Appointments state
  const [appointments, setAppointments] = React.useState([
    { id: 1, time: '09:00 AM', name: 'Ana Gómez', module: 'Consulta General' },
    { id: 2, time: '11:30 AM', name: 'Carlos Ruíz', module: 'Revisión Técnica' },
    { id: 3, time: '03:00 PM', name: 'Mariana Pérez', module: 'Asesoría VIP' }
  ]);
  const [newApptName, setNewApptName] = React.useState('');
  const [newApptTime, setNewApptTime] = React.useState('04:30 PM');
  
  // Module 3: CRM state
  const [clients, setClients] = React.useState([
    { id: 1, name: 'Alejandro Estrada', email: 'ale@estrada.dev', phone: '+502 4432-1100', status: 'Activo' },
    { id: 2, name: 'Beatriz Ovalle', email: 'beatriz@ovalle.net', phone: '+502 5990-2342', status: 'Inactivo' },
    { id: 3, name: 'Eduardo Samayoa', email: 'edu@samayoa.com', phone: '+502 3012-9988', status: 'Activo' }
  ]);
  const [clientSearch, setClientSearch] = React.useState('');
  const [selectedClientDetail, setSelectedClientDetail] = React.useState(null);
  
  // Module 4: BI Analytics state
  const [biRevenue, setBiRevenue] = React.useState([2400, 3100, 2900, 4200, 3800, 5400, 6100]);
  const [updatingBI, setUpdatingBI] = React.useState(false);

  // Module 5: Stripe simulation state
  const [transactions, setTransactions] = React.useState([
    { id: 'tx_8819', amount: '$120.00', status: 'Succeeded', email: 'pago1@gmail.com' },
    { id: 'tx_5521', amount: '$450.00', status: 'Succeeded', email: 'pago2@gmail.com' }
  ]);
  const [processingPayment, setProcessingPayment] = React.useState(false);
  const [payAmount, setPayAmount] = React.useState('75.00');

  // Module 6: AI state
  const [aiOutput, setAiOutput] = React.useState('');
  const [aiInput, setAiInput] = React.useState('');
  const [generatingAI, setGeneratingAI] = React.useState(false);
  
  // Step 5: Contact Lead Form
  const [leadForm, setLeadForm] = React.useState({
    name: '',
    email: '',
    phone: '',
    budget: '$3,000 - $6,000 USD'
  });
  const [formErrors, setFormErrors] = React.useState({});
  
  // Scroll to top on step change
  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [step]);

  // Handle Tab Initialization when stepping into Workspace
  React.useEffect(() => {
    if (step === 4 && selectedModules.length > 0) {
      setActiveTab(selectedModules[0]);
    } else if (step === 4) {
      setActiveTab('general');
    }
  }, [step, selectedModules]);

  // Terminal Build Log Simulation Sequence
  const runBuildSimulation = () => {
    setStep(3);
    setBuildProgress(0);
    setBuildLogs([]);
    
    // Safely process list of active modules
    const modulesList = (selectedModules || []).map(m => {
      const opt = MODULE_OPTIONS.find(o => o.id === m);
      return opt ? opt.label : m;
    });

    const logs = [
      `$ bulltech-builder --init --type=${(selectedType || '').toLowerCase()}`,
      `⚙️  Configuring digital stack for ${selectedType || 'SaaS'} (${selectedVertical || 'Salud'} vertical)...`,
      `✓ Database instance created successfully.`,
      `✓ Model schemas registered for: ${modulesList.join(', ')}.`,
      `📦 Injecting system components & custom design system tokens...`,
      `⚙️  Generating workspace blueprint wireframes...`,
      `✓ Active module compiled: ${(selectedModules || []).map(m => String(m).toUpperCase()).join(', ')}`,
      `⚡ Deployment successful to: https://sandbox-preview.bulltech.dev/`,
      `✓ Environment ready. Opening live blueprint...`
    ];

    let currentLogIndex = 0;
    const interval = setInterval(() => {
      try {
        if (currentLogIndex < logs.length) {
          const nextLog = logs[currentLogIndex];
          setBuildLogs(prev => [...prev, nextLog]);
          setBuildProgress(Math.floor(((currentLogIndex + 1) / logs.length) * 100));
          currentLogIndex++;
        } else {
          clearInterval(interval);
          setTimeout(() => {
            setStep(4);
          }, 600);
        }
      } catch (err) {
        console.error("Interval processing error: ", err);
        clearInterval(interval);
      }
    }, 450);
  };

  // Modules toggler
  const toggleModule = (id) => {
    if (selectedModules.includes(id)) {
      setSelectedModules(selectedModules.filter(m => m !== id));
    } else {
      setSelectedModules([...selectedModules, id]);
    }
  };

  // Simulator actions: Inventory scan
  const triggerInventoryScan = () => {
    if (scanning) return;
    setScanning(true);
    setTimeout(() => {
      const names = ['Micro-server node', 'Optic connector RX', 'Laser tracker V3', 'Cooling Grid'];
      const randomName = names[Math.floor(Math.random() * names.length)];
      const randomCode = 'SC-' + Math.floor(100 + Math.random() * 900) + '-S';
      const newStock = Math.floor(Math.random() * 15) + 1;
      
      setInventoryItems(prev => [
        ...prev, 
        { id: Date.now(), name: randomName, stock: newStock, code: randomCode }
      ]);
      setScanning(false);
    }, 1000);
  };

  const updateStock = (id, amount) => {
    setInventoryItems(prev => prev.map(item => {
      if (item.id === id) {
        return { ...item, stock: Math.max(0, item.stock + amount) };
      }
      return item;
    }));
  };

  // Simulator actions: Add appointment
  const addAppointment = (e) => {
    e.preventDefault();
    if (!newApptName.trim()) return;
    setAppointments(prev => [
      ...prev,
      { id: Date.now(), time: newApptTime, name: newApptName, module: 'Cita Automatizada' }
    ]);
    setNewApptName('');
  };

  // Simulator actions: Update BI data
  const refreshBI = () => {
    if (updatingBI) return;
    setUpdatingBI(true);
    setTimeout(() => {
      setBiRevenue(prev => prev.map(val => Math.floor(val * (0.9 + Math.random() * 0.3))));
      setUpdatingBI(false);
    }, 800);
  };

  // Simulator actions: Stripe payment simulation
  const executePayment = (e) => {
    e.preventDefault();
    if (!payAmount || processingPayment) return;
    setProcessingPayment(true);
    setTimeout(() => {
      const newTx = {
        id: 'tx_' + Math.floor(1000 + Math.random() * 9000),
        amount: `$${parseFloat(payAmount).toFixed(2)}`,
        status: 'Succeeded',
        email: `client_${Math.floor(Math.random()*100)}@bulltech.dev`
      };
      setTransactions(prev => [newTx, ...prev]);
      setProcessingPayment(false);
      setPayAmount('75.00');
    }, 1200);
  };

  // Simulator actions: AI typewriter simulation
  const queryAI = (e) => {
    e.preventDefault();
    if (!aiInput.trim() || generatingAI) return;
    setGeneratingAI(true);
    setAiOutput('Analizando datos de la vertical ' + selectedVertical + '...');
    
    setTimeout(() => {
      const responses = {
        Salud: `[AI Autopilot] Recomendación operativa: Basado en el flujo de citas actual, el 45% de los pacientes veterinarios/dentales faltan por falta de confirmación. Sugerimos activar recordatorios SMS automáticos. Tu stack actual soporta una automatización de cola de mensajes en un 92% de efectividad.`,
        PyME: `[AI Autopilot] Análisis administrativo: Se detecta que el flujo de aprobación de facturas tarda un promedio de 4 días hábiles. Integrar alertas de Slack/WhatsApp reducirá este tiempo a 1.2 horas promedio.`,
        Tienda: `[AI Autopilot] Logística & Stock: El producto "Reactors Core v2" presenta una rotación alta con un lead time de proveedor de 5 días. Recomendamos disparar orden de compra automática al caer a 5 unidades para evitar quiebre de inventario.`,
        Idea: `[AI Autopilot] Growth Stack: Para validar este MVP en Guatemala rápidamente, sugerimos lanzar una pauta A/B orientada al sector servicios y capturar leads mediante este flujo dinámico. Costo de adquisición estimado: $1.20 USD por lead.`
      };
      
      const targetResponse = responses[selectedVertical] || `[AI Autopilot] Análisis del sistema: El stack modular seleccionado (${(selectedModules || []).join(', ')}) se encuentra balanceado. El tiempo de respuesta de la base de datos es de 42ms.`;
      
      let index = 0;
      setAiOutput('');
      const typeInterval = setInterval(() => {
        try {
          if (index < targetResponse.length) {
            setAiOutput(prev => prev + targetResponse.charAt(index));
            index++;
          } else {
            clearInterval(typeInterval);
            setGeneratingAI(false);
          }
        } catch (err) {
          clearInterval(typeInterval);
          setGeneratingAI(false);
        }
      }, 15);
    }, 1000);
  };

  // Lead Form Validation
  const validateForm = () => {
    let errors = {};
    if (!leadForm.name.trim()) errors.name = 'El nombre completo es obligatorio.';
    if (!leadForm.email.trim()) {
      errors.email = 'El correo electrónico es obligatorio.';
    } else if (!/\S+@\S+\.\S+/.test(leadForm.email)) {
      errors.email = 'El correo electrónico no es válido.';
    }
    if (!leadForm.phone.trim()) {
      errors.phone = 'El teléfono o WhatsApp es obligatorio.';
    } else if (leadForm.phone.replace(/\D/g, '').length < 8) {
      errors.phone = 'Ingresa un número telefónico válido.';
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleLeadSubmit = (e) => {
    e.preventDefault();
    if (!validateForm()) return;
    
    // Construct WhatsApp content
    const waText = 
`◆ NUEVA SOLICITUD DE BLUEPRINT - BULLTECH ◆
---------------------------------------------
👤 CLIENTE:
- Nombre: ${leadForm.name}
- Email: ${leadForm.email}
- Tel/WA: ${leadForm.phone}

🛠️ ESPECIFICACIONES DEL BLUEPRINT:
- Tipo: ${selectedType}
- Vertical: ${selectedVertical}
- Módulos Activos: ${(selectedModules || []).map(m => {
    const opt = MODULE_OPTIONS.find(o => o.id === m);
    return opt ? opt.label : m;
  }).join(', ')}
- Presupuesto Estimado: ${leadForm.budget}

Generated via sandbox-preview.bulltech.dev`;

    const waLink = `https://wa.me/50256631375?text=${encodeURIComponent(waText)}`;
    
    // Backup email mailto
    const mailtoLink = `mailto:hola@bulltechnologies.dev?subject=Blueprint%20Software%20-%20${encodeURIComponent(leadForm.name)}&body=${encodeURIComponent(waText)}`;

    // Try opening WhatsApp
    window.open(waLink, '_blank');
    
    // Backup fallback triggers mailto if WhatsApp fails/user wants it
    setTimeout(() => {
      if (confirm('¿Deseas enviar también una copia del Blueprint por correo electrónico a hola@bulltechnologies.dev?')) {
        window.location.href = mailtoLink;
      }
    }, 1000);
  };

  try {
    return (
      <div style={{ background: 'var(--paper)', minHeight: '80vh', color: 'var(--ink)' }}>
        {/* Step Indicators */}
        <div style={{ borderBottom: '1px solid var(--line)', background: 'var(--surface-2)' }}>
          <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: '16px 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ color: 'var(--red)', fontWeight: 800, fontFamily: 'var(--font-mono)' }}>[BLUEPRINT LOOP]</span>
              <span style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
                Paso {step} de 5
              </span>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              {[1, 2, 3, 4, 5].map((s) => (
                <div 
                  key={s} 
                  style={{ 
                    width: 32, 
                    height: 6, 
                    background: step >= s ? 'var(--red)' : 'var(--line)', 
                    transition: 'background 0.3s ease' 
                  }} 
                />
              ))}
            </div>
          </div>
        </div>

        {/* STEP 1: Type & Vertical Selection */}
        {step === 1 && (
          <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: '48px 24px' }}>
            <div style={{ textAlign: 'center', marginBottom: 40 }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
                <span style={{ color: 'var(--red)', fontSize: 8 }}>◆</span>
                <span style={{ fontSize: 'var(--text-label)', fontWeight: 500, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--text-secondary)' }}>Configurador del Sistema</span>
              </div>
              <h1 style={{ margin: '0 0 12px', fontSize: 'var(--text-h1)', fontWeight: 800, letterSpacing: 'var(--tracking-headline)' }}>¿Qué tipo de software necesitas?</h1>
              <p style={{ margin: 0, fontSize: 16, color: 'var(--text-secondary)', maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
                Selecciona el formato de tu plataforma y el sector de tu negocio para inicializar el blueprint interactivo.
              </p>
            </div>

            <h2 style={{ fontSize: 14, textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 16, borderBottom: '1px solid var(--line)', paddingBottom: 8 }}>1. Formato del Producto</h2>
            <div style={{ marginBottom: 40 }} className="bt-products-grid">
              {SOFTWARE_TYPES.map((t) => {
                const Icon = t.icon;
                const isSelected = selectedType === t.id;
                return (
                  <div 
                    key={t.id}
                    onClick={() => setSelectedType(t.id)}
                    style={{
                      border: isSelected ? '1px solid var(--red)' : '1px solid var(--line)',
                      background: isSelected ? 'var(--red-tint)' : 'var(--paper)',
                      padding: 24,
                      cursor: 'pointer',
                      transition: 'all 0.2s ease',
                      boxShadow: isSelected ? '0 0 0 1px var(--red)' : 'none'
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                      <div style={{ color: isSelected ? 'var(--red)' : 'var(--ink-2)' }}>
                        <Icon />
                      </div>
                      <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>{t.title}</h3>
                    </div>
                    <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: 'var(--text-secondary)' }}>{t.desc}</p>
                  </div>
                );
              })}
            </div>

            <h2 style={{ fontSize: 14, textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 16, borderBottom: '1px solid var(--line)', paddingBottom: 8 }}>2. Vertical de Negocio</h2>
            <div style={{ marginBottom: 48 }} className="bt-products-grid">
              {VERTICALS.map((v) => {
                const Icon = v.icon;
                const isSelected = selectedVertical === v.id;
                return (
                  <div 
                    key={v.id}
                    onClick={() => setSelectedVertical(v.id)}
                    style={{
                      border: isSelected ? '1px solid var(--red)' : '1px solid var(--line)',
                      background: isSelected ? 'var(--red-tint)' : 'var(--paper)',
                      padding: 24,
                      cursor: 'pointer',
                      transition: 'all 0.2s ease',
                      boxShadow: isSelected ? '0 0 0 1px var(--red)' : 'none'
                    }}
                  >
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                      <div style={{ color: isSelected ? 'var(--red)' : 'var(--ink-2)' }}>
                        <Icon />
                      </div>
                      <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>{v.title}</h3>
                    </div>
                    <p style={{ margin: 0, fontSize: 13, lineHeight: 1.6, color: 'var(--text-secondary)' }}>{v.desc}</p>
                  </div>
                );
              })}
            </div>

            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 16, borderTop: '1px solid var(--line)', paddingTop: 24 }}>
              <button 
                onClick={() => setView('landing')} 
                style={{
                  background: 'none',
                  border: '1px solid var(--line)',
                  padding: '12px 24px',
                  fontFamily: 'var(--font-mono)',
                  fontSize: 13,
                  cursor: 'pointer'
                }}
              >
                Cancelar
              </button>
              <button 
                onClick={() => setStep(2)}
                style={{
                  background: 'var(--ink)',
                  color: 'var(--paper)',
                  border: 'none',
                  padding: '12px 28px',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8
                }}
              >
                Siguiente Paso <Icons.ArrowRight />
              </button>
            </div>
          </div>
        )}

        {/* STEP 2: Module Selections */}
        {step === 2 && (
          <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: '48px 24px' }}>
            <div style={{ textAlign: 'center', marginBottom: 40 }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
                <span style={{ color: 'var(--red)', fontSize: 8 }}>◆</span>
                <span style={{ fontSize: 'var(--text-label)', fontWeight: 500, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--text-secondary)' }}>Arquitectura Funcional</span>
              </div>
              <h1 style={{ margin: '0 0 12px', fontSize: 'var(--text-h1)', fontWeight: 800, letterSpacing: 'var(--tracking-headline)' }}>¿Qué módulos integrará tu software?</h1>
              <p style={{ margin: 0, fontSize: 16, color: 'var(--text-secondary)', maxWidth: 600, marginLeft: 'auto', marginRight: 'auto' }}>
                Elige los módulos de ingeniería requeridos. Crearemos un prototipo funcional personalizado a partir de tu selección.
              </p>
            </div>

            <div style={{ marginBottom: 48 }} className="bt-products-grid">
              {MODULE_OPTIONS.map((m) => {
                const isSelected = selectedModules.includes(m.id);
                return (
                  <div 
                    key={m.id}
                    onClick={() => toggleModule(m.id)}
                    style={{
                      border: isSelected ? '1px solid var(--red)' : '1px solid var(--line)',
                      background: isSelected ? 'var(--red-tint)' : 'var(--paper)',
                      padding: 24,
                      cursor: 'pointer',
                      display: 'flex',
                      alignItems: 'flex-start',
                      gap: 16,
                      transition: 'all 0.2s ease'
                    }}
                  >
                    <div style={{
                      width: 20,
                      height: 20,
                      border: isSelected ? '1px solid var(--red)' : '1px solid var(--border-input)',
                      background: isSelected ? 'var(--red)' : 'none',
                      color: 'var(--paper)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      marginTop: 2,
                      flexShrink: 0
                    }}>
                      {isSelected && <Icons.Check />}
                    </div>
                    <div>
                      <h3 style={{ margin: '0 0 6px', fontSize: 16, fontWeight: 800 }}>{m.label}</h3>
                      <p style={{ margin: 0, fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5 }}>{m.desc}</p>
                    </div>
                  </div>
                );
              })}
            </div>

            <div style={{ display: 'flex', justifyContent: 'space-between', borderTop: '1px solid var(--line)', paddingTop: 24 }}>
              <button 
                onClick={() => setStep(1)} 
                style={{
                  background: 'none',
                  border: '1px solid var(--line)',
                  padding: '12px 24px',
                  fontFamily: 'var(--font-mono)',
                  fontSize: 13,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8
                }}
              >
                <Icons.ArrowLeft /> Anterior
              </button>
              <button 
                onClick={runBuildSimulation}
                disabled={selectedModules.length === 0}
                style={{
                  background: selectedModules.length === 0 ? 'var(--ink-3)' : 'var(--ink)',
                  color: 'var(--paper)',
                  border: 'none',
                  padding: '12px 28px',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: selectedModules.length === 0 ? 'not-allowed' : 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8
                }}
              >
                Compilar Sandbox ◆
              </button>
            </div>
          </div>
        )}

        {/* STEP 3: Compiler Terminal Animation */}
        {step === 3 && (
          <div style={{ maxWidth: 700, margin: '0 auto', padding: '96px 24px' }}>
            <div style={{ border: '1px solid var(--ink)', background: 'var(--paper)', boxShadow: '4px 4px 0 var(--ink)' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 16px', borderBottom: '1px solid var(--ink)', background: 'var(--surface-2)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Icons.Terminal />
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, fontWeight: 600 }}>compilando_blueprint.sh</span>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <span style={{ width: 8, height: 8, border: '1px solid var(--ink-3)' }}></span>
                  <span style={{ width: 8, height: 8, border: '1px solid var(--ink-3)' }}></span>
                  <span style={{ width: 8, height: 8, background: 'var(--red)' }}></span>
                </div>
              </div>
              <div style={{ padding: 24, minHeight: 280, background: 'var(--paper)', fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.7 }}>
                {(buildLogs || []).map((log, i) => (
                  <div key={i} style={{ 
                    color: String(log).startsWith('$') ? 'var(--text-body)' : String(log).startsWith('✓') ? 'var(--ok)' : 'var(--text-secondary)',
                    marginBottom: 6,
                    whiteSpace: 'pre-wrap'
                  }}>
                    {String(log)}
                  </div>
                ))}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 24, borderTop: '1px dashed var(--line)', paddingTop: 16 }}>
                  <div style={{ flexGrow: 1, height: 4, background: 'var(--line)' }}>
                    <div style={{ height: '100%', width: `${buildProgress}%`, background: 'var(--red)', transition: 'width 0.2s ease' }}></div>
                  </div>
                  <span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{buildProgress}%</span>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* STEP 4: High-Fidelity Interactive Preview Workspace */}
        {step === 4 && (
          <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: '40px 24px' }}>
            <div style={{ marginBottom: 24, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
              <div>
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <span style={{ color: 'var(--red)', fontSize: 8 }}>◆</span>
                  <span style={{ fontSize: 'var(--text-label)', fontWeight: 500, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--text-secondary)' }}>Sandbox Interactivo</span>
                </div>
                <h1 style={{ margin: 0, fontSize: 'var(--text-h2)', fontWeight: 800, letterSpacing: 'var(--tracking-headline)' }}>Tu Prototipo Funcional</h1>
              </div>
              <button 
                onClick={() => setStep(5)}
                style={{
                  background: 'var(--red)',
                  color: 'var(--paper)',
                  border: 'none',
                  padding: '12px 24px',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8,
                  transition: 'background 0.2s ease'
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--red-press)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'var(--red)'}
              >
                Confirmar Blueprint y Cotizar ◆
              </button>
            </div>

            {/* Browser Window Wrapper */}
            <div style={{ border: '2px solid var(--ink)', background: 'var(--paper)', minHeight: 500, display: 'flex', flexDirection: 'column' }}>
              {/* Header Browser Bar */}
              <div className="bt-sandbox-header" style={{ padding: '12px 16px', borderBottom: '2px solid var(--ink)', background: 'var(--surface-2)' }}>
                {/* Window Controls */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ display: 'flex', gap: 6 }}>
                    <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#FF5F56' }}></span>
                    <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#FFBD2E' }}></span>
                    <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#27C93F' }}></span>
                  </div>
                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-tertiary)', marginLeft: 8 }}>preview-sandbox</span>
                </div>
                {/* URL Address Bar */}
                <div style={{ flexGrow: 1, display: 'flex', alignItems: 'center', background: 'var(--paper)', border: '1px solid var(--border-input)', padding: '6px 12px', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-secondary)', width: '100%', boxSizing: 'border-box' }}>
                  <span style={{ color: 'var(--ok)', marginRight: 4 }}>🔒</span>
                  https://app.bulltech.dev/{(selectedType || '').toLowerCase()}-{(selectedVertical || '').toLowerCase()}/sandbox
                </div>
              </div>

              {/* Inner Dashboard Layout */}
              <div className="bt-sandbox-layout">
                {/* Sidebar Tabs */}
                <div className="bt-sandbox-sidebar">
                  {(selectedModules || []).map((modId) => {
                    const label = MODULE_OPTIONS.find(o => o.id === modId)?.label || modId;
                    const isActive = activeTab === modId;
                    return (
                      <button
                        key={modId}
                        onClick={() => setActiveTab(modId)}
                        className={`bt-sandbox-sidebar-btn ${isActive ? 'active' : ''}`}
                      >
                        <span>{label}</span>
                        {isActive && <span className="bt-hide-mobile" style={{ color: 'var(--red)' }}>◆</span>}
                      </button>
                    );
                  })}
                  {(selectedModules || []).length === 0 && (
                    <div style={{ padding: 20, fontSize: 12, color: 'var(--text-secondary)' }}>Ningún módulo activo</div>
                  )}
                </div>

                {/* Workspace Board Viewport */}
                <div style={{ flexGrow: 1, padding: 24, background: 'var(--paper)', minHeight: 400 }}>
                  {/* 1. MODULE: INVENTARIO */}
                  {activeTab === 'inventario' && (
                    <div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, borderBottom: '1px solid var(--line)', paddingBottom: 12 }}>
                        <div>
                          <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>Inventario Inteligente</h3>
                          <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--text-secondary)' }}>Módulo de simulación de stock y códigos.</p>
                        </div>
                        <button 
                          onClick={triggerInventoryScan}
                          disabled={scanning}
                          style={{
                            background: 'var(--ink)',
                            color: 'var(--paper)',
                            border: 'none',
                            padding: '8px 14px',
                            fontSize: 12,
                            fontWeight: 600,
                            cursor: 'pointer'
                          }}
                        >
                          {scanning ? 'Escaneando...' : '+ Simular Escaneo'}
                        </button>
                      </div>

                      <div style={{ border: '1px solid var(--ink)', overflowX: 'auto' }}>
                        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, textAlign: 'left', minWidth: 400 }}>
                          <thead>
                            <tr style={{ background: 'var(--surface-2)', borderBottom: '1px solid var(--ink)' }}>
                              <th style={{ padding: 12 }}>Código</th>
                              <th style={{ padding: 12 }}>Descripción</th>
                              <th style={{ padding: 12, textAlign: 'center' }}>Stock</th>
                              <th style={{ padding: 12, textAlign: 'right' }}>Acción</th>
                            </tr>
                          </thead>
                          <tbody>
                            {inventoryItems.map(item => (
                              <tr key={item.id} style={{ borderBottom: '1px solid var(--line)' }}>
                                <td style={{ padding: 12, fontFamily: 'var(--font-mono)', color: 'var(--text-secondary)' }}>{item.code}</td>
                                <td style={{ padding: 12, fontWeight: 600 }}>{item.name}</td>
                                <td style={{ padding: 12, textAlign: 'center', fontFamily: 'var(--font-mono)' }}>
                                  <span style={{ 
                                    color: item.stock <= 5 ? 'var(--red)' : 'var(--text-body)',
                                    fontWeight: item.stock <= 5 ? 700 : 400 
                                  }}>
                                    {item.stock} {item.stock <= 5 && '(Bajo)'}
                                  </span>
                                </td>
                                <td style={{ padding: 12, textAlign: 'right' }}>
                                  <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 6 }}>
                                    <button onClick={() => updateStock(item.id, -1)} style={{ width: 24, height: 24, background: 'none', border: '1px solid var(--border-input)', cursor: 'pointer' }}>-</button>
                                    <button onClick={() => updateStock(item.id, 1)} style={{ width: 24, height: 24, background: 'none', border: '1px solid var(--border-input)', cursor: 'pointer' }}>+</button>
                                  </div>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  )}

                  {/* 2. MODULE: AGENDA */}
                  {activeTab === 'agenda' && (
                    <div>
                      <div style={{ borderBottom: '1px solid var(--line)', paddingBottom: 12, marginBottom: 20 }}>
                        <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>Agenda y Citas</h3>
                        <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--text-secondary)' }}>Planificador dinámico de horarios de atención.</p>
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 20 }} className="bt-products-grid">
                        {/* List */}
                        <div>
                          <div style={{ border: '1px solid var(--ink)', background: 'var(--surface-2)', padding: 12, fontWeight: 700, fontSize: 12, borderBottom: 'none' }}>
                            Citas Programadas para Hoy
                          </div>
                          <div style={{ border: '1px solid var(--ink)', padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
                            {appointments.map(appt => (
                              <div key={appt.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 12px', border: '1px solid var(--line)', background: 'var(--paper)' }}>
                                <div>
                                  <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, background: 'var(--surface-3)', padding: '2px 6px', marginRight: 10 }}>{appt.time}</span>
                                  <span style={{ fontWeight: 600 }}>{appt.name}</span>
                                </div>
                                <span style={{ fontSize: 11, background: 'var(--red-tint)', color: 'var(--red)', padding: '2px 8px' }}>
                                  {appt.module}
                                </span>
                              </div>
                            ))}
                          </div>
                        </div>

                        {/* Add Form */}
                        <form onSubmit={addAppointment} style={{ border: '1px solid var(--ink)', padding: 16 }}>
                          <h4 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 800 }}>+ Agendar Cita de Prueba</h4>
                          <div style={{ marginBottom: 12 }}>
                            <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>Nombre del Cliente</label>
                            <input 
                              type="text" 
                              value={newApptName} 
                              onChange={(e) => setNewApptName(e.target.value)}
                              placeholder="Ej: Laura Méndez" 
                              style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border-input)', padding: 8, fontSize: 13 }}
                            />
                          </div>
                          <div style={{ marginBottom: 16 }}>
                            <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>Hora</label>
                            <select 
                              value={newApptTime} 
                              onChange={(e) => setNewApptTime(e.target.value)}
                              style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border-input)', padding: 8, fontSize: 13 }}
                            >
                              <option value="08:00 AM">08:00 AM</option>
                              <option value="10:00 AM">10:00 AM</option>
                              <option value="01:30 PM">01:30 PM</option>
                              <option value="04:30 PM">04:30 PM</option>
                            </select>
                          </div>
                          <button type="submit" style={{ width: '100%', background: 'var(--ink)', color: 'var(--paper)', border: 'none', padding: '10px', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
                            Agregar a la Agenda
                          </button>
                        </form>
                      </div>
                    </div>
                  )}

                  {/* 3. MODULE: CLIENTES */}
                  {activeTab === 'clientes' && (
                    <div>
                      <div style={{ borderBottom: '1px solid var(--line)', paddingBottom: 12, marginBottom: 20 }}>
                        <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>Expediente de Clientes</h3>
                        <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--text-secondary)' }}>CRM y registros históricos de clientes / pacientes.</p>
                      </div>

                      <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
                        <input 
                          type="text" 
                          placeholder="🔍 Buscar cliente por nombre..." 
                          value={clientSearch}
                          onChange={(e) => setClientSearch(e.target.value)}
                          style={{ flexGrow: 1, border: '1px solid var(--border-input)', padding: '10px 12px', fontSize: 13 }}
                        />
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 20 }} className="bt-products-grid">
                        <div style={{ border: '1px solid var(--ink)', overflowX: 'auto' }}>
                          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, minWidth: 350 }}>
                            <thead>
                              <tr style={{ background: 'var(--surface-2)', borderBottom: '1px solid var(--ink)', textAlign: 'left' }}>
                                <th style={{ padding: 12 }}>Nombre</th>
                                <th style={{ padding: 12 }}>Estado</th>
                                <th style={{ padding: 12, textAlign: 'right' }}>Acción</th>
                              </tr>
                            </thead>
                            <tbody>
                              {clients
                                .filter(c => c.name.toLowerCase().includes(clientSearch.toLowerCase()))
                                .map(c => (
                                  <tr key={c.id} style={{ borderBottom: '1px solid var(--line)' }}>
                                    <td style={{ padding: 12, fontWeight: 600 }}>{c.name}</td>
                                    <td style={{ padding: 12 }}>
                                      <span style={{ 
                                        fontSize: 11, 
                                        background: c.status === 'Activo' ? 'var(--ok-tint)' : 'var(--surface-3)', 
                                        color: c.status === 'Activo' ? 'var(--ok)' : 'var(--ink-2)',
                                        padding: '2px 6px'
                                      }}>{c.status}</span>
                                    </td>
                                    <td style={{ padding: 12, textAlign: 'right' }}>
                                      <button 
                                        onClick={() => setSelectedClientDetail(c)}
                                        style={{ background: 'none', border: '1px solid var(--border-input)', padding: '4px 10px', fontSize: 12, cursor: 'pointer' }}
                                      >
                                        Detalles
                                      </button>
                                    </td>
                                  </tr>
                                ))
                              }
                            </tbody>
                          </table>
                        </div>

                        {/* Detail Drawer */}
                        <div style={{ border: '1px solid var(--ink)', padding: 16, background: 'var(--surface-2)' }}>
                          <h4 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 800 }}>Ficha del Cliente</h4>
                          {selectedClientDetail ? (
                            <div style={{ fontSize: 13, display: 'flex', flexDirection: 'column', gap: 8 }}>
                              <div><strong>Nombre:</strong> {selectedClientDetail.name}</div>
                              <div><strong>Email:</strong> {selectedClientDetail.email}</div>
                              <div><strong>Teléfono:</strong> {selectedClientDetail.phone}</div>
                              <div><strong>Estado:</strong> {selectedClientDetail.status}</div>
                              <div style={{ borderTop: '1px solid var(--line)', paddingTop: 10, marginTop: 10 }}>
                                <span style={{ fontSize: 11, color: 'var(--text-secondary)' }}>Historial de Operación:</span>
                                <p style={{ margin: '4px 0 0', fontSize: 12, fontStyle: 'italic' }}>1 consulta y 2 cotizaciones cargadas.</p>
                              </div>
                            </div>
                          ) : (
                            <span style={{ fontSize: 12, color: 'var(--text-secondary)' }}>Haz clic en "Detalles" para abrir la ficha.</span>
                          )}
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 4. MODULE: REPORTES */}
                  {activeTab === 'reportes' && (
                    <div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, borderBottom: '1px solid var(--line)', paddingBottom: 12 }}>
                        <div>
                          <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>Métricas y Analíticas</h3>
                          <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--text-secondary)' }}>Visualización reactiva del comportamiento financiero.</p>
                        </div>
                        <button 
                          onClick={refreshBI}
                          disabled={updatingBI}
                          style={{
                            background: 'var(--ink)',
                            color: 'var(--paper)',
                            border: 'none',
                            padding: '8px 14px',
                            fontSize: 12,
                            fontWeight: 600,
                            cursor: 'pointer'
                          }}
                        >
                          {updatingBI ? 'Recalculando...' : 'Actualizar Reportes'}
                        </button>
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16, marginBottom: 24 }} className="bt-metrics-grid">
                        <div style={{ border: '1px solid var(--line)', padding: 16 }}>
                          <span style={{ fontSize: 11, color: 'var(--text-secondary)' }}>Uptime Sandbox</span>
                          <div style={{ fontSize: 24, fontWeight: 800, fontFamily: 'var(--font-mono)', marginTop: 4 }}>99.98%</div>
                        </div>
                        <div style={{ border: '1px solid var(--line)', padding: 16 }}>
                          <span style={{ fontSize: 11, color: 'var(--text-secondary)' }}>Latencia API</span>
                          <div style={{ fontSize: 24, fontWeight: 800, fontFamily: 'var(--font-mono)', marginTop: 4, color: 'var(--ok)' }}>124ms</div>
                        </div>
                        <div style={{ border: '1px solid var(--line)', padding: 16 }}>
                          <span style={{ fontSize: 11, color: 'var(--text-secondary)' }}>Ingreso Simulado</span>
                          <div style={{ fontSize: 24, fontWeight: 800, fontFamily: 'var(--font-mono)', marginTop: 4 }}>
                            ${biRevenue.reduce((a, b) => a + b, 0).toLocaleString()}
                          </div>
                        </div>
                      </div>

                      {/* SVG Vector Chart */}
                      <div style={{ border: '1px solid var(--ink)', padding: 20, background: 'var(--surface-2)', overflowX: 'auto' }}>
                        <h4 style={{ margin: '0 0 16px', fontSize: 13, fontWeight: 800, textTransform: 'uppercase', letterSpacing: '0.05em' }}>Volumen de Ventas Semanales</h4>
                        <div style={{ minWidth: 400 }}>
                          <svg viewBox="0 0 500 150" style={{ width: '100%', height: 150, overflow: 'visible' }}>
                            {/* Grid lines */}
                            <line x1="0" y1="120" x2="500" y2="120" stroke="var(--line)" strokeWidth="1" />
                            <line x1="0" y1="70" x2="500" y2="70" stroke="var(--line)" strokeWidth="1" strokeDasharray="4 4" />
                            <line x1="0" y1="20" x2="500" y2="20" stroke="var(--line)" strokeWidth="1" />
                            
                            {/* Polyline chart */}
                            <polyline
                              fill="none"
                              stroke="var(--red)"
                              strokeWidth="3"
                              points={
                                biRevenue.map((val, idx) => {
                                  const x = (idx * 500) / (biRevenue.length - 1);
                                  const y = 140 - (val * 110) / 7500;
                                  return `${x},${y}`;
                                }).join(' ')
                              }
                              style={{ transition: 'points 0.5s ease' }}
                            />
                            {/* Data points */}
                            {biRevenue.map((val, idx) => {
                              const x = (idx * 500) / (biRevenue.length - 1);
                              const y = 140 - (val * 110) / 7500;
                              return (
                                <g key={idx}>
                                  <rect x={x - 4} y={y - 4} width="8" height="8" fill="var(--ink)" stroke="var(--paper)" strokeWidth="1.5" />
                                  <text x={x} y={y - 10} fontSize="10" fontFamily="var(--font-mono)" textAnchor="middle" fill="var(--text-body)" fontWeight="700">
                                    ${val}
                                  </text>
                                </g>
                              );
                            })}
                          </svg>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 5. MODULE: PAGOS */}
                  {activeTab === 'pagos' && (
                    <div>
                      <div style={{ borderBottom: '1px solid var(--line)', paddingBottom: 12, marginBottom: 20 }}>
                        <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>Pasarela de Pagos</h3>
                        <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--text-secondary)' }}>Procesamiento integrado de tarjetas y cuentas por cobrar.</p>
                      </div>

                      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 20 }} className="bt-products-grid">
                        {/* Terminal Payment */}
                        <form onSubmit={executePayment} style={{ border: '1px solid var(--ink)', padding: 16 }}>
                          <h4 style={{ margin: '0 0 16px', fontSize: 14, fontWeight: 800 }}>Simulador de Cobro Rápido</h4>
                          <div style={{ marginBottom: 12 }}>
                            <label style={{ display: 'block', fontSize: 11, fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>Monto (USD)</label>
                            <div style={{ display: 'flex' }}>
                              <span style={{ border: '1px solid var(--border-input)', borderRight: 'none', background: 'var(--surface-2)', padding: '8px 12px', fontSize: 14, display: 'flex', alignItems: 'center' }}>$</span>
                              <input 
                                type="number" 
                                value={payAmount} 
                                onChange={(e) => setPayAmount(e.target.value)}
                                placeholder="50.00" 
                                style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border-input)', padding: 8, fontSize: 14 }}
                              />
                            </div>
                          </div>
                          <button 
                            type="submit" 
                            disabled={processingPayment}
                            style={{ width: '100%', background: 'var(--red)', color: 'var(--paper)', border: 'none', padding: '12px', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}
                          >
                            {processingPayment ? 'Comunicando con gateway...' : 'Procesar Pago Simulado'}
                          </button>
                        </form>

                        {/* Log Transactions */}
                        <div>
                          <div style={{ border: '1px solid var(--ink)', background: 'var(--surface-2)', padding: 12, fontWeight: 700, fontSize: 12, borderBottom: 'none' }}>
                            Historial de Sandbox Gateway
                          </div>
                          <div style={{ border: '1px solid var(--ink)', padding: 16, minHeight: 120, display: 'flex', flexDirection: 'column', gap: 10 }}>
                            {transactions.map(tx => (
                              <div key={tx.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13, borderBottom: '1px solid var(--line)', paddingBottom: 6 }}>
                                <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{tx.id}</span>
                                <span style={{ color: 'var(--text-secondary)', textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap', maxWidth: 150 }}>{tx.email}</span>
                                <span style={{ fontWeight: 800, color: 'var(--ok)' }}>{tx.amount}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* 6. MODULE: IA */}
                  {activeTab === 'ia' && (
                    <div>
                      <div style={{ borderBottom: '1px solid var(--line)', paddingBottom: 12, marginBottom: 20 }}>
                        <h3 style={{ margin: 0, fontSize: 18, fontWeight: 800 }}>IA Autopilot</h3>
                        <p style={{ margin: '4px 0 0', fontSize: 12, color: 'var(--text-secondary)' }}>Agente autónomo integrado en el ecosistema operativo.</p>
                      </div>

                      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                        {/* Box prompts */}
                        <form onSubmit={queryAI} style={{ display: 'flex', gap: 10 }}>
                          <input 
                            type="text" 
                            placeholder="Pregúntale a la IA (ej: ¿Cómo optimizo la retención?)" 
                            value={aiInput}
                            onChange={(e) => setAiInput(e.target.value)}
                            style={{ flexGrow: 1, border: '1px solid var(--border-input)', padding: '10px 12px', fontSize: 13 }}
                          />
                          <button 
                            type="submit" 
                            disabled={generatingAI || !aiInput.trim()}
                            style={{ background: 'var(--ink)', color: 'var(--paper)', border: 'none', padding: '0 20px', fontWeight: 600, cursor: 'pointer', fontSize: 13 }}
                          >
                            Analizar ◆
                          </button>
                        </form>

                        {/* Display */}
                        <div style={{ border: '1px solid var(--ink)', background: 'var(--surface-3)', padding: 16, minHeight: 120, fontFamily: 'var(--font-mono)', fontSize: 13, lineHeight: 1.6, color: 'var(--text-body)' }}>
                          {aiOutput ? (
                            <div style={{ whiteSpace: 'pre-wrap' }}>
                              {aiOutput}
                              {generatingAI && <span className="bt-cursor" style={{ color: 'var(--red)' }}>_</span>}
                            </div>
                          ) : (
                            <span style={{ color: 'var(--text-secondary)' }}>Ingresa una consulta sobre el flujo de tu negocio para activar el análisis predictivo.</span>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Navigation step footer */}
            <div style={{ display: 'flex', justifyContent: 'flex-start', borderTop: '1px solid var(--line)', paddingTop: 24, marginTop: 24 }}>
              <button 
                onClick={() => setStep(2)} 
                style={{
                  background: 'none',
                  border: '1px solid var(--line)',
                  padding: '12px 24px',
                  fontFamily: 'var(--font-mono)',
                  fontSize: 13,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8
                }}
              >
                <Icons.ArrowLeft /> Modificar Módulos
              </button>
            </div>
          </div>
        )}

        {/* STEP 5: Contact Lead Capture */}
        {step === 5 && (
          <div style={{ maxWidth: 600, margin: '0 auto', padding: '64px 24px' }}>
            <div style={{ textAlign: 'center', marginBottom: 32 }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
                <span style={{ color: 'var(--red)', fontSize: 8 }}>◆</span>
                <span style={{ fontSize: 'var(--text-label)', fontWeight: 500, letterSpacing: 'var(--tracking-label)', textTransform: 'uppercase', color: 'var(--text-secondary)' }}>Último Paso</span>
              </div>
              <h1 style={{ margin: '0 0 12px', fontSize: 'var(--text-h2)', fontWeight: 800, letterSpacing: 'var(--tracking-headline)' }}>Obtén tu Blueprint & Cotización</h1>
              <p style={{ margin: 0, fontSize: 15, color: 'var(--text-secondary)' }}>
                Completa tus datos de contacto. Generaremos el blueprint técnico estructurado y abriremos WhatsApp para afinar los detalles de tu proyecto.
              </p>
            </div>

            <form onSubmit={handleLeadSubmit} style={{ border: '2px solid var(--ink)', padding: 32, background: 'var(--paper)', display: 'flex', flexDirection: 'column', gap: 20 }}>
              {/* Summary details */}
              <div style={{ background: 'var(--surface-2)', border: '1px solid var(--line)', padding: 16, fontSize: 13, display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', color: 'var(--text-secondary)' }}>Resumen del Proyecto</span>
                <div><strong>Tipo de software:</strong> {selectedType}</div>
                <div><strong>Vertical del negocio:</strong> {selectedVertical}</div>
                <div><strong>Módulos activos:</strong> {(selectedModules || []).map(m => {
                  const opt = MODULE_OPTIONS.find(o => o.id === m);
                  return opt ? opt.label : m;
                }).join(', ')}</div>
              </div>

              {/* Field: Name */}
              <div>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Nombre Completo</label>
                <input 
                  type="text" 
                  value={leadForm.name}
                  onChange={(e) => setLeadForm({ ...leadForm, name: e.target.value })}
                  placeholder="Ej: Alejandro Estrada" 
                  style={{ 
                    width: '100%', 
                    boxSizing: 'border-box', 
                    border: formErrors.name ? '1px solid var(--red)' : '1px solid var(--border-input)', 
                    padding: 12, 
                    fontSize: 14 
                  }}
                />
                {formErrors.name && <span style={{ color: 'var(--red)', fontSize: 12, marginTop: 4, display: 'block' }}>{formErrors.name}</span>}
              </div>

              {/* Field: Email */}
              <div>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Correo Electrónico</label>
                <input 
                  type="email" 
                  value={leadForm.email}
                  onChange={(e) => setLeadForm({ ...leadForm, email: e.target.value })}
                  placeholder="ejemplo@empresa.com" 
                  style={{ 
                    width: '100%', 
                    boxSizing: 'border-box', 
                    border: formErrors.email ? '1px solid var(--red)' : '1px solid var(--border-input)', 
                    padding: 12, 
                    fontSize: 14 
                  }}
                />
                {formErrors.email && <span style={{ color: 'var(--red)', fontSize: 12, marginTop: 4, display: 'block' }}>{formErrors.email}</span>}
              </div>

              {/* Field: Phone */}
              <div>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Teléfono / WhatsApp</label>
                <input 
                  type="tel" 
                  value={leadForm.phone}
                  onChange={(e) => setLeadForm({ ...leadForm, phone: e.target.value })}
                  placeholder="Ej: +502 5543-9812" 
                  style={{ 
                    width: '100%', 
                    boxSizing: 'border-box', 
                    border: formErrors.phone ? '1px solid var(--red)' : '1px solid var(--border-input)', 
                    padding: 12, 
                    fontSize: 14 
                  }}
                />
                {formErrors.phone && <span style={{ color: 'var(--red)', fontSize: 12, marginTop: 4, display: 'block' }}>{formErrors.phone}</span>}
              </div>

              {/* Field: Budget */}
              <div>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>Presupuesto Estimado</label>
                <select 
                  value={leadForm.budget}
                  onChange={(e) => setLeadForm({ ...leadForm, budget: e.target.value })}
                  style={{ 
                    width: '100%', 
                    boxSizing: 'border-box', 
                    border: '1px solid var(--border-input)', 
                    padding: 12, 
                    fontSize: 14,
                    background: 'var(--paper)'
                  }}
                >
                  <option value="< $1,500 USD">&lt; $1,500 USD</option>
                  <option value="$1,500 - $3,000 USD">$1,500 - $3,000 USD</option>
                  <option value="$3,000 - $6,000 USD">$3,000 - $6,000 USD</option>
                  <option value="> $6,000 USD">&gt; $6,000 USD</option>
                </select>
              </div>

              <button 
                type="submit" 
                style={{
                  width: '100%',
                  background: 'var(--red)',
                  color: 'var(--paper)',
                  border: 'none',
                  padding: '16px',
                  fontWeight: 700,
                  fontSize: 14,
                  textTransform: 'uppercase',
                  letterSpacing: '0.05em',
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 8,
                  transition: 'background 0.2s ease',
                  marginTop: 8
                }}
                onMouseEnter={(e) => e.currentTarget.style.background = 'var(--red-press)'}
                onMouseLeave={(e) => e.currentTarget.style.background = 'var(--red)'}
              >
                Enviar a WhatsApp y Finalizar ◆
              </button>

              <span style={{ display: 'block', textAlign: 'center', fontSize: 11, color: 'var(--text-tertiary)' }}>
                Al presionar enviar, abrirás un chat directo de WhatsApp con BullTech.
              </span>
            </form>

            <div style={{ display: 'flex', justifyContent: 'flex-start', borderTop: '1px solid var(--line)', paddingTop: 24, marginTop: 24 }}>
              <button 
                onClick={() => setStep(4)} 
                style={{
                  background: 'none',
                  border: '1px solid var(--line)',
                  padding: '12px 24px',
                  fontFamily: 'var(--font-mono)',
                  fontSize: 13,
                  cursor: 'pointer',
                  display: 'inline-flex',
                  alignItems: 'center',
                  gap: 8
                }}
              >
                <Icons.ArrowLeft /> Volver al Sandbox
              </button>
            </div>
          </div>
        )}
      </div>
    );
  } catch (err) {
    return (
      <div style={{ padding: 24, fontFamily: 'monospace', color: 'red', border: '2px solid red' }}>
        <h2>Runtime Render Error</h2>
        <p>{err.message}</p>
        <pre>{err.stack}</pre>
      </div>
    );
  }
}

// Assign to window for Babel loading compatibility
Object.assign(window, { PrototypeGenerator });
