Calculadora ROI Delegup

<?php


// Shortcode para calculadora ROI - SIN BACKTICKS
function delegup_calculadora_roi() {
    ob_start();
    ?>
    
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculadora de ROI - DelegUp</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gradient-to-br from-blue-50 via-white to-purple-50">
    <div class="min-h-screen p-6">
        <div class="max-w-6xl mx-auto">
            <!-- Header -->
            <div class="text-center mb-8">
                <h1 class="text-4xl font-bold text-gray-900 mb-2">Calculadora de ROI</h1>
                <p class="text-lg text-gray-600">Descubrí el retorno de inversión de transformar tu negocio</p>
                <p class="text-sm text-gray-500 mt-2">DelegUp - Soluciones de IA y Automatización</p>
            </div>

            <!-- Service Selection -->
            <div id="serviceSelection" class="grid md:grid-cols-3 gap-6 mb-8">
                <button onclick="selectService('ai-agent')" class="p-6 bg-white rounded-xl shadow-lg hover:shadow-xl transition-all border-2 border-transparent hover:border-blue-500 text-left">
                    <div class="text-4xl mb-4">⚡</div>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">Agente IA de Ventas</h3>
                    <p class="text-gray-600 text-sm">Automatización de atención, calificación y cierre de leads</p>
                </button>
                
                <button onclick="selectService('commercial')" class="p-6 bg-white rounded-xl shadow-lg hover:shadow-xl transition-all border-2 border-transparent hover:border-blue-500 text-left">
                    <div class="text-4xl mb-4">🎯</div>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">Estructuración Comercial</h3>
                    <p class="text-gray-600 text-sm">CRM, procesos, funnel, speeches y metodología de ventas</p>
                </button>
                
                <button onclick="selectService('transformation')" class="p-6 bg-white rounded-xl shadow-lg hover:shadow-xl transition-all border-2 border-transparent hover:border-blue-500 text-left">
                    <div class="text-4xl mb-4">📈</div>
                    <h3 class="text-xl font-bold text-gray-900 mb-2">Transformación Digital</h3>
                    <p class="text-gray-600 text-sm">Capacitación IA, mapeo de procesos y automatización integral</p>
                </button>
            </div>

            <!-- Industry Selection -->
            <div id="industrySelection" class="hidden bg-white rounded-xl shadow-lg p-8 mb-8">
                <h2 class="text-2xl font-bold text-gray-900 mb-6">¿Cuál es tu industria?</h2>
                <div class="grid md:grid-cols-4 gap-4 mb-6">
                    <button onclick="selectIndustry('real-estate')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Inmobiliaria</button>
                    <button onclick="selectIndustry('healthcare')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Salud / Clínicas</button>
                    <button onclick="selectIndustry('b2b-services')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Servicios B2B</button>
                    <button onclick="selectIndustry('distribution')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Distribución</button>
                    <button onclick="selectIndustry('education')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Educación</button>
                    <button onclick="selectIndustry('retail')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Retail</button>
                    <button onclick="selectIndustry('manufacturing')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Manufactura</button>
                    <button onclick="selectIndustry('professional')" class="p-4 border-2 border-gray-200 rounded-lg hover:border-blue-500 hover:bg-blue-50 transition-all text-center font-medium">Servicios Prof.</button>
                </div>
                <button onclick="resetService()" class="text-blue-600 hover:text-blue-700 font-medium">← Cambiar servicio</button>
            </div>

            <!-- Calculator Form -->
            <div id="calculatorSection" class="hidden grid lg:grid-cols-2 gap-8">
                <!-- Input Panel -->
                <div class="bg-white rounded-xl shadow-lg p-8">
                    <div class="mb-6">
                        <h2 id="serviceName" class="text-2xl font-bold text-gray-900 mb-2"></h2>
                        <p id="industryName" class="text-sm text-gray-600"></p>
                        <button onclick="resetIndustry()" class="mt-2 text-sm text-blue-600 hover:text-blue-700">Cambiar industria</button>
                    </div>

                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Facturación mensual promedio (USD)</label>
                            <input type="number" id="monthlyRevenue" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 50000">
                        </div>

                        <!-- AI Agent Fields -->
                        <div id="aiAgentFields" class="hidden space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Consultas/Leads mensuales actuales</label>
                                <input type="number" id="currentLeads" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 80">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Tasa de conversión actual (%)</label>
                                <input type="number" step="0.1" id="conversionRate" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 3">
                                <p class="text-xs text-gray-500 mt-1">Ej: inmobiliarias 2-5%, B2B 10-15%</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Ticket promedio de venta (USD)</label>
                                <input type="number" id="avgTicket" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">¿Cuántos leads perdés por no atender a tiempo?</label>
                                <input type="number" id="lostLeads" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 20">
                                <p class="text-xs text-gray-500 mt-1">Leads que no contestás o atendés tarde</p>
                            </div>
                            <div class="border-t pt-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Inversión inicial agente (USD)</label>
                                <input type="number" id="aiInvestment" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" value="1000">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Costo mensual (USD)</label>
                                <input type="number" id="aiMonthlyCost" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" value="300">
                            </div>
                        </div>

                        <!-- Commercial Fields -->
                        <div id="commercialFields" class="hidden space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Tamaño del equipo comercial</label>
                                <input type="number" id="salesTeamSize" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 3">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Tasa de cierre actual (%)</label>
                                <input type="number" step="0.1" id="closingRate" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 20">
                            </div>
                            <div class="border-t pt-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Inversión inicial (USD)</label>
                                <input type="number" id="commercialInvestment" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" value="3500">
                                <p class="text-xs text-gray-500 mt-1">Setup CRM + procesos + capacitación</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Costo mensual (USD)</label>
                                <input type="number" id="commercialMonthlyCost" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" value="200">
                                <p class="text-xs text-gray-500 mt-1">Licencias CRM</p>
                            </div>
                        </div>

                        <!-- Transformation Fields -->
                        <div id="transformationFields" class="hidden space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Procesos a automatizar</label>
                                <input type="number" id="processesToAutomate" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 8">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Horas semanales por proceso</label>
                                <input type="number" step="0.5" id="hoursPerProcess" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 4">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Empleados afectados</label>
                                <input type="number" id="affectedEmployees" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 10">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Salario promedio mensual (USD)</label>
                                <input type="number" id="averageSalary" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="ej: 1200">
                            </div>
                            <div class="border-t pt-4">
                                <label class="block text-sm font-medium text-gray-700 mb-1">Inversión inicial (USD)</label>
                                <input type="number" id="transformationInvestment" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" value="5000">
                                <p class="text-xs text-gray-500 mt-1">Capacitación + mapeo + implementación</p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Costo mensual (USD)</label>
                                <input type="number" id="transformationMonthlyCost" oninput="calculate()" class="w-full p-3 border border-gray-300 rounded-lg" value="350">
                                <p class="text-xs text-gray-500 mt-1">Herramientas de automatización</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Results Panel -->
                <div>
                    <!-- Placeholder -->
                    <div id="placeholder" class="bg-gray-50 rounded-xl shadow-lg p-8 border-2 border-dashed border-gray-300">
                        <div class="text-center py-12">
                            <div class="text-6xl mb-4">📊</div>
                            <h3 class="text-xl font-bold text-gray-700 mb-2">Completá los datos para ver tu ROI</h3>
                            <p class="text-gray-500 text-sm">Ingresá la información de tu negocio para calcular el retorno de inversión estimado</p>
                        </div>
                    </div>

                    <!-- Results -->
                    <div id="results" class="hidden space-y-6">
                        <!-- Main ROI Card -->
                        <div class="bg-gradient-to-br from-blue-600 to-purple-600 rounded-xl shadow-lg p-8 text-white">
                            <h3 class="text-2xl font-bold mb-6">Tu Retorno de Inversión</h3>
                            <div class="space-y-4">
                                <div class="bg-white/10 rounded-lg p-4 backdrop-blur">
                                    <div class="text-sm opacity-90 mb-1">Inversión Inicial</div>
                                    <div id="investment" class="text-3xl font-bold"></div>
                                </div>
                                <div class="bg-white/10 rounded-lg p-4 backdrop-blur">
                                    <div class="text-sm opacity-90 mb-1">Ganancia Mensual</div>
                                    <div id="monthlyGain" class="text-3xl font-bold text-green-300"></div>
                                </div>
                                <div class="bg-white/10 rounded-lg p-4 backdrop-blur">
                                    <div class="text-sm opacity-90 mb-1">Recupero en</div>
                                    <div id="payback" class="text-3xl font-bold"></div>
                                </div>
                                <div class="bg-white/10 rounded-lg p-4 backdrop-blur">
                                    <div class="text-sm opacity-90 mb-1">ROI Año 1</div>
                                    <div id="yearOneROI" class="text-3xl font-bold text-yellow-300"></div>
                                </div>
                            </div>
                        </div>

                        <!-- ROI Breakdown -->
                        <div class="bg-white rounded-xl shadow-lg p-6">
                            <h4 class="font-bold text-lg text-gray-900 mb-4">📊 Desglose del ROI</h4>
                            <div class="space-y-4">
                                <div class="border-l-4 border-green-500 pl-4 py-2">
                                    <div class="font-semibold text-gray-900">💰 Ingresos Directos Adicionales</div>
                                    <div id="directRevenue" class="text-sm text-gray-600 mt-1"></div>
                                </div>
                                <div class="border-l-4 border-blue-500 pl-4 py-2">
                                    <div class="font-semibold text-gray-900">⚙️ Ahorro y Optimización de Recursos</div>
                                    <div id="costSavings" class="text-sm text-gray-600 mt-1"></div>
                                </div>
                                <div class="border-l-4 border-purple-500 pl-4 py-2">
                                    <div class="font-semibold text-gray-900">⭐ Mejora en Experiencia del Cliente</div>
                                    <div id="customerExperience" class="text-sm text-gray-600 mt-1"></div>
                                </div>
                                <div class="border-l-4 border-orange-500 pl-4 py-2">
                                    <div class="font-semibold text-gray-900">📈 Capacidad y Productividad</div>
                                    <div id="productivity" class="text-sm text-gray-600 mt-1"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Case Study -->
                        <div id="caseStudy" class="bg-gradient-to-br from-green-50 to-emerald-50 rounded-xl shadow-lg p-6 border border-green-200">
                            <h4 class="font-bold text-lg text-gray-900 mb-3">✅ Caso de Éxito Similar</h4>
                            <div id="caseContent"></div>
                        </div>

                        <!-- CTA Options -->
                        <div class="bg-gray-900 rounded-xl shadow-lg p-6 text-white">
                            <h4 class="font-bold text-xl mb-3 text-center">¿Qué preferís hacer con este cálculo?</h4>
                            <p class="text-gray-300 mb-6 text-sm text-center">Elegí cómo querés continuar</p>
                            
                            <div class="space-y-3">
                                <!-- WhatsApp Direct -->
                                <a href="https://wa.me/5491154829440?text=Hola!%20Vi%20la%20calculadora%20de%20ROI%20y%20quiero%20agendar%20una%20consultoría" 
                                   target="_blank"
                                   class="block bg-green-600 hover:bg-green-700 text-white font-bold py-4 px-6 rounded-lg transition-all text-center">
                                    💬 Agendar ahora por WhatsApp
                                    <span class="block text-sm font-normal mt-1 opacity-90">Charlamos en 2 minutos</span>
                                </a>
                                
                                <!-- Email with Form -->
                                <button onclick="showEmailForm()" 
                                        class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-4 px-6 rounded-lg transition-all text-center">
                                    📧 Recibir propuesta detallada
                                    <span class="block text-sm font-normal mt-1 opacity-90">Te enviamos análisis completo + casos de éxito</span>
                                </button>
                                
                                <!-- PDF Download -->
                                <button onclick="showPdfForm()" 
                                        class="w-full bg-gray-700 hover:bg-gray-600 text-white font-bold py-4 px-6 rounded-lg transition-all text-center">
                                    📥 Descargar este cálculo (PDF)
                                    <span class="block text-sm font-normal mt-1 opacity-90">Guardalo para compartir con tu equipo</span>
                                </button>
                            </div>
                            
                            <p class="text-xs text-gray-400 mt-4 text-center">DelegUp - IA y Automatización | +54 9 11 5482-9440</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Email Form Modal -->
            <div id="emailFormModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
                <div class="bg-white rounded-xl shadow-2xl max-w-md w-full p-8">
                    <h3 class="text-2xl font-bold text-gray-900 mb-2">📧 Recibir Propuesta Detallada</h3>
                    <p class="text-gray-600 mb-6 text-sm">Te enviamos tu análisis de ROI + casos de éxito similares + propuesta personalizada</p>
                    
                    <form id="emailForm" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Nombre completo *</label>
                            <input type="text" id="leadName" required class="w-full p-3 border border-gray-300 rounded-lg" placeholder="Juan Pérez">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Email *</label>
                            <input type="email" id="leadEmail" required class="w-full p-3 border border-gray-300 rounded-lg" placeholder="juan@empresa.com">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Empresa *</label>
                            <input type="text" id="leadCompany" required class="w-full p-3 border border-gray-300 rounded-lg" placeholder="Mi Empresa SA">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Teléfono (opcional)</label>
                            <input type="tel" id="leadPhone" class="w-full p-3 border border-gray-300 rounded-lg" placeholder="+54 9 11 1234-5678">
                        </div>
                        
                        <div class="flex gap-3 pt-2">
                            <button type="button" onclick="closeEmailForm()" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-3 px-6 rounded-lg transition-all">
                                Cancelar
                            </button>
                            <button type="submit" class="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg transition-all">
                                Enviar →
                            </button>
                        </div>
                    </form>
                    
                    <div id="emailFormSuccess" class="hidden text-center py-8">
                        <div class="text-6xl mb-4">✅</div>
                        <h4 class="text-xl font-bold text-gray-900 mb-2">¡Listo!</h4>
                        <p class="text-gray-600 mb-4">Te enviamos el análisis detallado a <span id="confirmedEmail" class="font-semibold"></span></p>
                        <p class="text-sm text-gray-500 mb-4">Revisá tu casilla en los próximos minutos</p>
                        <button onclick="closeEmailForm()" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg">
                            Cerrar
                        </button>
                    </div>
                </div>
            </div>

            <!-- PDF Form Modal -->
            <div id="pdfFormModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
                <div class="bg-white rounded-xl shadow-2xl max-w-md w-full p-8">
                    <h3 class="text-2xl font-bold text-gray-900 mb-2">📥 Descargar Cálculo en PDF</h3>
                    <p class="text-gray-600 mb-6 text-sm">Ingresá tu email para recibir el PDF con tu análisis de ROI</p>
                    
                    <form id="pdfForm" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Email *</label>
                            <input type="email" id="pdfEmail" required class="w-full p-3 border border-gray-300 rounded-lg" placeholder="tu@email.com">
                        </div>
                        
                        <div class="flex gap-3 pt-2">
                            <button type="button" onclick="closePdfForm()" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-3 px-6 rounded-lg transition-all">
                                Cancelar
                            </button>
                            <button type="submit" class="flex-1 bg-gray-700 hover:bg-gray-600 text-white font-bold py-3 px-6 rounded-lg transition-all">
                                Descargar →
                            </button>
                        </div>
                    </form>
                    
                    <div id="pdfFormSuccess" class="hidden text-center py-8">
                        <div class="text-6xl mb-4">📄</div>
                        <h4 class="text-xl font-bold text-gray-900 mb-2">¡PDF en camino!</h4>
                        <p class="text-gray-600 mb-4">Te enviamos el PDF a <span id="confirmedPdfEmail" class="font-semibold"></span></p>
                        <p class="text-sm text-gray-500 mb-4">También podés guardarlo desde acá:</p>
                        <button onclick="downloadPdfNow()" class="bg-gray-700 hover:bg-gray-600 text-white font-bold py-2 px-6 rounded-lg mb-3">
                            💾 Descargar ahora
                        </button>
                        <button onclick="closePdfForm()" class="block w-full text-gray-600 hover:text-gray-800 font-medium">
                            Cerrar
                        </button>
                    </div>
                </div>
            </div>

            <!-- Methodology -->
            <div id="methodology" class="hidden mt-8 bg-blue-50 rounded-xl p-6 text-sm text-gray-700">
                <h5 class="font-bold mb-2 text-gray-900">📋 Metodología de Cálculo</h5>
                <p class="mb-2">Esta calculadora utiliza promedios conservadores basados en más de 30 implementaciones reales en PyMEs argentinas.</p>
                <ul class="space-y-1 list-disc list-inside text-xs">
                    <li>Todos los cálculos consideran escenarios conservadores</li>
                    <li>Los costos incluyen implementación, licencias y mantenimiento</li>
                    <li>Los casos de éxito son de clientes reales con métricas verificables</li>
                </ul>
            </div>
        </div>
    </div>

    <script>
        let currentService = '';
        let currentIndustry = '';
        let calculatedROI = null;

        const caseStudies = {
            'ai-agent': {
                'real-estate': {
                    company: 'Inmobiliaria regional (Buenos Aires)',
                    improvement: '340%',
                    metric: 'aumento en consultas atendidas',
                    time: '3 meses',
                    details: 'De 50 a 170 consultas mensuales sin contratar. Atención 24/7 recuperó leads nocturnos. Conversión mejoró 3.2% → 3.8%. ROI medido: ingresos adicionales vs costo mensual. Recupero en 45 días.'
                },
                'healthcare': {
                    company: 'Red de 3 clínicas médicas',
                    improvement: '85%',
                    metric: 'reducción en tiempo de respuesta',
                    time: '2 meses',
                    details: 'Atención 24/7 automatizada. 60% turnos agendados sin intervención. De 4hs promedio a 30 segundos. Satisfacción pacientes +45%. ROI medido: turnos adicionales vs costo IA.'
                },
                'b2b-services': {
                    company: 'Consultoría empresarial',
                    improvement: '250%',
                    metric: 'incremento en leads calificados',
                    time: '4 meses',
                    details: 'Agente califica y agenda demos. Comerciales solo cierran. De 40 a 140 leads calificados/mes. Conversión demo→cierre: 15% → 22%. ROI: ventas adicionales - costo IA.'
                }
            },
            'commercial': {
                'distribution': {
                    company: 'Distribuidor industrial B2B',
                    improvement: '180%',
                    metric: 'mejora en tasa de conversión',
                    time: '6 meses',
                    details: 'CRM + proceso estructurado. De 12% a 34% tasa cierre. Ciclo venta: 60 → 35 días. ROI medido: ingresos adicionales por mejor conversión vs inversión CRM. 3 vendedores facturaron como 5.'
                },
                'b2b-services': {
                    company: 'Agencia de marketing',
                    improvement: '420%',
                    metric: 'aumento en pipeline',
                    time: '5 meses',
                    details: 'Funnel estructurado + speeches. Pipeline $180k → $750k. Escalaron de 2 a 8 vendedores con mismo proceso. Conversión: 18% → 28%. ROI: nuevos ingresos vs inversión procesos.'
                },
                'professional': {
                    company: 'Estudio contable',
                    improvement: '90%',
                    metric: 'reducción en ciclo de venta',
                    time: '3 meses',
                    details: 'De 45 a 20 días promedio cierre. Proceso claro = conversión +65% (20% → 33%). ROI medido: más clientes/mes con mismo equipo vs costo implementación.'
                }
            },
            'transformation': {
                'manufacturing': {
                    company: 'PyME industrial (45 empleados)',
                    improvement: '35%',
                    metric: 'ahorro en costos operativos',
                    time: '8 meses',
                    details: 'Automatización de 12 procesos: inventario, compras, facturación. Capacitación IA a 40 empleados. 520hs/mes liberadas. ROI medido: ahorro en horas + reducción errores vs inversión.'
                },
                'retail': {
                    company: 'Cadena regional (8 sucursales)',
                    improvement: '120%',
                    metric: 'mejora en productividad',
                    time: '6 meses',
                    details: '15 procesos automatizados. Gerentes dedicaban 40% tiempo a reportes, ahora 10%. 60% más tiempo en estrategia. Facturación +18% con mismo personal. ROI: incremento ventas vs costo herramientas.'
                },
                'healthcare': {
                    company: 'Centro médico (12 profesionales)',
                    improvement: '50%',
                    metric: 'reducción en tareas administrativas',
                    time: '4 meses',
                    details: 'Staff médico recuperó 20hs/semana para pacientes. Automatización turnos, historia clínica, facturación. +35 pacientes/semana atendidos. ROI: ingresos adicionales vs costo automatización.'
                }
            }
        };

        function selectService(service) {
            currentService = service;
            document.getElementById('serviceSelection').classList.add('hidden');
            document.getElementById('industrySelection').classList.remove('hidden');
        }

        function selectIndustry(industry) {
            currentIndustry = industry;
            document.getElementById('industrySelection').classList.add('hidden');
            document.getElementById('calculatorSection').classList.remove('hidden');
            document.getElementById('methodology').classList.remove('hidden');
            
            const serviceNames = {
                'ai-agent': 'Agente IA de Ventas',
                'commercial': 'Estructuración Comercial',
                'transformation': 'Transformación Digital'
            };
            
            const industryNames = {
                'real-estate': 'Inmobiliaria',
                'healthcare': 'Salud / Clínicas',
                'b2b-services': 'Servicios B2B',
                'distribution': 'Distribución',
                'education': 'Educación',
                'retail': 'Retail',
                'manufacturing': 'Manufactura',
                'professional': 'Servicios Profesionales'
            };
            
            document.getElementById('serviceName').textContent = serviceNames[currentService];
            document.getElementById('industryName').textContent = industryNames[currentIndustry];
            
            // Show relevant fields
            document.getElementById('aiAgentFields').classList.add('hidden');
            document.getElementById('commercialFields').classList.add('hidden');
            document.getElementById('transformationFields').classList.add('hidden');
            
            if (currentService === 'ai-agent') {
                document.getElementById('aiAgentFields').classList.remove('hidden');
            } else if (currentService === 'commercial') {
                document.getElementById('commercialFields').classList.remove('hidden');
            } else if (currentService === 'transformation') {
                document.getElementById('transformationFields').classList.remove('hidden');
            }
        }

        function resetService() {
            document.getElementById('serviceSelection').classList.remove('hidden');
            document.getElementById('industrySelection').classList.add('hidden');
        }

        function resetIndustry() {
            document.getElementById('calculatorSection').classList.add('hidden');
            document.getElementById('industrySelection').classList.remove('hidden');
            document.getElementById('methodology').classList.add('hidden');
        }

        // Modal Functions
        function showEmailForm() {
            document.getElementById('emailFormModal').classList.remove('hidden');
            document.getElementById('emailForm').classList.remove('hidden');
            document.getElementById('emailFormSuccess').classList.add('hidden');
        }

        function closeEmailForm() {
            document.getElementById('emailFormModal').classList.add('hidden');
            document.getElementById('emailForm').reset();
        }

        function showPdfForm() {
            document.getElementById('pdfFormModal').classList.remove('hidden');
            document.getElementById('pdfForm').classList.remove('hidden');
            document.getElementById('pdfFormSuccess').classList.add('hidden');
        }

        function closePdfForm() {
            document.getElementById('pdfFormModal').classList.add('hidden');
            document.getElementById('pdfForm').reset();
        }

        // Email Form Submit
        document.getElementById('emailForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const leadData = {
                name: document.getElementById('leadName').value,
                email: document.getElementById('leadEmail').value,
                company: document.getElementById('leadCompany').value,
                phone: document.getElementById('leadPhone').value,
                service: currentService,
                industry: currentIndustry,
                roi_data: calculatedROI,
                source: 'calculadora-roi',
                type: 'propuesta-detallada'
            };

            console.log('Enviando lead:', leadData);
            
            try {
                const response = await fetch('/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: { 
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        action: 'save_lead',
                        type: 'calculadora-roi-propuesta',
                        name: leadData.name,
                        email: leadData.email,
                        company: leadData.company,
                        phone: leadData.phone,
                        service: leadData.service,
                        industry: leadData.industry,
                        roi_investment: leadData.roi_data?.investment || 0,
                        roi_monthly: leadData.roi_data?.monthlyGain || 0,
                        roi_payback: leadData.roi_data?.payback || 0,
                        roi_year_one: leadData.roi_data?.yearOneROI || 0,
                        source: 'calculadora-roi',
                        lead_data: JSON.stringify(leadData.roi_data || {})
                    })
                });
                
                const result = await response.json();
                console.log('Respuesta:', result);
                
                if (result.success) {
                    document.getElementById('confirmedEmail').textContent = leadData.email;
                    document.getElementById('emailForm').classList.add('hidden');
                    document.getElementById('emailFormSuccess').classList.remove('hidden');
                    
                    if (typeof gtag !== 'undefined') {
                        gtag('event', 'generate_lead', {
                            event_category: 'ROI Calculator',
                            event_label: currentService + ' - ' + currentIndustry,
                            value: calculatedROI?.investment
                        });
                    }
                } else {
                    alert('Hubo un error al enviar. Por favor intentá de nuevo o contactanos por WhatsApp.');
                }
            } catch (error) {
                alert('Hubo un error. Por favor intentá de nuevo o contactanos por WhatsApp: +54 9 11 5482-9440');
                console.error('Error:', error);
            }
        });

        // PDF Form Submit
        document.getElementById('pdfForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const email = document.getElementById('pdfEmail').value;
            
            const leadData = {
                email: email,
                service: currentService,
                industry: currentIndustry,
                roi_data: calculatedROI,
                source: 'calculadora-roi',
                type: 'descarga-pdf'
            };

            console.log('PDF lead:', leadData);
            
            try {
                const response = await fetch('/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: { 
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        action: 'save_lead',
                        type: 'calculadora-roi-pdf',
                        email: leadData.email,
                        service: leadData.service,
                        industry: leadData.industry,
                        roi_investment: leadData.roi_data?.investment || 0,
                        roi_monthly: leadData.roi_data?.monthlyGain || 0,
                        source: 'calculadora-roi',
                        lead_data: JSON.stringify(leadData.roi_data || {})
                    })
                });
                
                const result = await response.json();
                console.log('Respuesta:', result);
                
                if (result.success) {
                    document.getElementById('confirmedPdfEmail').textContent = email;
                    document.getElementById('pdfForm').classList.add('hidden');
                    document.getElementById('pdfFormSuccess').classList.remove('hidden');
                    
                    if (typeof gtag !== 'undefined') {
                        gtag('event', 'download_pdf', {
                            event_category: 'ROI Calculator',
                            event_label: currentService + ' - ' + currentIndustry
                        });
                    }
                } else {
                    alert('Hubo un error al enviar. Intentalo de nuevo o contactanos por WhatsApp.');
                }
            } catch (error) {
                alert('Hubo un error. Intentalo de nuevo o contactanos por WhatsApp: +54 9 11 5482-9440');
                console.error('Error:', error);
            }
        });

        function downloadPdfNow() {
            alert('Funcionalidad de PDF en desarrollo. Te enviamos el análisis por email!');
        }

        function calculate() {
            let hasData = false;
            let investment = 0;
            let monthlyCost = 0;
            let monthlyGain = 0;
            let breakdown = {
                directRevenue: '',
                costSavings: '',
                customerExperience: '',
                productivity: ''
            };

            if (currentService === 'ai-agent') {
                const leads = parseFloat(document.getElementById('currentLeads').value) || 0;
                const conversion = parseFloat(document.getElementById('conversionRate').value) || 0;
                const ticket = parseFloat(document.getElementById('avgTicket').value) || 0;
                const lostLeads = parseFloat(document.getElementById('lostLeads').value) || 0;
                const revenue = parseFloat(document.getElementById('monthlyRevenue').value) || 0;
                const customInvestment = parseFloat(document.getElementById('aiInvestment').value) || 1000;
                const customMonthlyCost = parseFloat(document.getElementById('aiMonthlyCost').value) || 300;
                
                if (leads && conversion && ticket && revenue) {
                    hasData = true;
                    
                    investment = customInvestment;
                    monthlyCost = customMonthlyCost;
                    
                    const currentSales = leads * (conversion / 100);
                    const realTicket = revenue / currentSales;
                    const ticketToUse = (ticket > realTicket * 5) ? realTicket : ticket;
                    const recoveredLeads = lostLeads || Math.round(leads * 0.15);
                    const totalLeadsHandled = leads + recoveredLeads;
                    const conversionImprovement = 1.10;
                    const newConversion = conversion * conversionImprovement;
                    const newSales = totalLeadsHandled * (newConversion / 100);
                    const additionalSales = newSales - currentSales;
                    const currentRevenue = currentSales * ticketToUse;
                    const newRevenue = newSales * ticketToUse;
                    const additionalRevenue = newRevenue - currentRevenue;
                    const timeSavings = 400;
                    
                    monthlyGain = additionalRevenue - monthlyCost + timeSavings;
                    
                    const ticketWarning = (ticket > realTicket * 5) ? 
                        ' NOTA: Tu ticket real parece ser $' + Math.round(realTicket).toLocaleString() + ' (facturación/ventas actuales). Usamos este valor para el cálculo.' : '';
                    
                    breakdown.directRevenue = '+' + additionalSales.toFixed(1) + ' ventas/mes adicionales (de ' + currentSales.toFixed(1) + ' a ' + newSales.toFixed(1) + '). Recuperás ' + recoveredLeads + ' leads que antes se perdían + mejorás conversión ' + conversion + '% → ' + newConversion.toFixed(1) + '%. Ticket promedio: $' + Math.round(ticketToUse).toLocaleString() + '. El humano cierra todas las ventas.' + ticketWarning;
                    breakdown.costSavings = 'Costo IA: $' + monthlyCost + '/mes. Ahorro vs contratar persona: ~$' + timeSavings + '/mes. Tu equipo solo atiende leads calificados y cierra.';
                    breakdown.customerExperience = 'Respuesta en segundos 24/7 vs horas/días de espera. Leads no se enfrían esperando. Seguimiento automatizado de cada oportunidad.';
                    breakdown.productivity = 'Equipo comercial 100% en cierre, no atendiendo consultas básicas. IA califica y agenda, humano cierra. Escalable sin contratar.';
                }
            } else if (currentService === 'commercial') {
                const revenue = parseFloat(document.getElementById('monthlyRevenue').value) || 0;
                const salesTeam = parseFloat(document.getElementById('salesTeamSize').value) || 0;
                const closingRate = parseFloat(document.getElementById('closingRate').value) || 0;
                const customInvestment = parseFloat(document.getElementById('commercialInvestment').value) || 3500;
                const customMonthlyCost = parseFloat(document.getElementById('commercialMonthlyCost').value) || 200;
                
                if (revenue && salesTeam && closingRate) {
                    hasData = true;
                    
                    investment = customInvestment;
                    monthlyCost = customMonthlyCost;
                    
                    let improvementFactor;
                    if (closingRate < 10) {
                        improvementFactor = 1.25;
                    } else if (closingRate < 20) {
                        improvementFactor = 1.18;
                    } else {
                        improvementFactor = 1.12;
                    }
                    
                    const newClosingRate = closingRate * improvementFactor;
                    const revenuePerSeller = revenue / salesTeam;
                    const additionalRevenue = revenuePerSeller * (improvementFactor - 1) * salesTeam;
                    const capacityGain = revenuePerSeller * 0.12 * salesTeam;
                    
                    monthlyGain = additionalRevenue + capacityGain - monthlyCost;
                    
                    breakdown.directRevenue = '+$' + Math.round(additionalRevenue).toLocaleString() + '/mes por mejor tasa de cierre (' + closingRate + '% → ' + newClosingRate.toFixed(1) + '%, mejora de ' + ((improvementFactor - 1) * 100).toFixed(0) + '%). Proceso estructurado + CRM + speeches mejoran conversión consistentemente.';
                    breakdown.costSavings = 'CRM mensual: $' + monthlyCost + '. Evitás perder ventas por falta de seguimiento. Menos tiempo perdido en leads no calificados.';
                    breakdown.customerExperience = 'Seguimiento consistente y profesional. Cada cliente recibe el mismo nivel de atención. Nada se cae por olvido o falta de proceso.';
                    breakdown.productivity = '+$' + Math.round(capacityGain).toLocaleString() + '/mes en capacidad adicional (~12%). Ciclo de venta más corto permite manejar más volumen sin crecer equipo.';
                }
            } else if (currentService === 'transformation') {
                const processes = parseFloat(document.getElementById('processesToAutomate').value) || 0;
                const hoursPerProcess = parseFloat(document.getElementById('hoursPerProcess').value) || 0;
                const affected = parseFloat(document.getElementById('affectedEmployees').value) || 0;
                const salary = parseFloat(document.getElementById('averageSalary').value) || 0;
                const customInvestment = parseFloat(document.getElementById('transformationInvestment').value) || 5000;
                const customMonthlyCost = parseFloat(document.getElementById('transformationMonthlyCost').value) || 350;
                
                if (processes && hoursPerProcess && affected && salary) {
                    hasData = true;
                    
                    investment = customInvestment;
                    monthlyCost = customMonthlyCost;
                    
                    const automationEfficiency = 0.65;
                    const hoursSaved = processes * hoursPerProcess * 4.3 * automationEfficiency;
                    const costPerHour = salary / 160;
                    const monthlySavings = hoursSaved * costPerHour * affected;
                    const productivityGain = monthlySavings * 0.15;
                    
                    monthlyGain = monthlySavings + productivityGain - monthlyCost;
                    
                    breakdown.directRevenue = 'Tiempo liberado permite: visitar más clientes, abrir territorios, ampliar productos. Empleados dedican tiempo a generar ingresos vs tareas operativas.';
                    breakdown.costSavings = '$' + Math.round(monthlySavings).toLocaleString() + '/mes en ~' + Math.round(hoursSaved) + 'hs efectivamente ahorradas (65% eficiencia) de ' + affected + ' empleados. Costo herramientas: $' + monthlyCost + '/mes. Calculado conservadoramente.';
                    breakdown.customerExperience = 'Procesos más rápidos = clientes más satisfechos. Menos errores = mejor servicio. Mayor capacidad de respuesta.';
                    breakdown.productivity = '+$' + Math.round(productivityGain).toLocaleString() + '/mes en productividad (15% conservador). Equipo enfocado en estrategia, no operaciones. Capacitación IA = ventaja competitiva.';
                }
            }

            if (hasData) {
                const payback = (investment / monthlyGain).toFixed(1);
                const yearOneROI = (((monthlyGain * 12 - investment) / investment) * 100).toFixed(0);
                
                calculatedROI = {
                    investment: investment,
                    monthlyGain: monthlyGain,
                    payback: payback,
                    yearOneROI: yearOneROI,
                    service: currentService,
                    industry: currentIndustry,
                    breakdown: breakdown
                };
                
                document.getElementById('investment').textContent = '$' + investment.toLocaleString();
                document.getElementById('monthlyGain').textContent = '+$' + Math.round(monthlyGain).toLocaleString();
                document.getElementById('payback').textContent = payback + ' meses';
                document.getElementById('yearOneROI').textContent = yearOneROI + '%';
                
                document.getElementById('directRevenue').textContent = breakdown.directRevenue;
                document.getElementById('costSavings').textContent = breakdown.costSavings;
                document.getElementById('customerExperience').textContent = breakdown.customerExperience;
                document.getElementById('productivity').textContent = breakdown.productivity;
                
                const caseStudy = caseStudies[currentService]?.[currentIndustry] || 
                                 Object.values(caseStudies[currentService] || {})[0];
                
                if (caseStudy) {
                    document.getElementById('caseContent').innerHTML = 
                        '<p class="text-sm text-gray-700 mb-2"><strong>' + caseStudy.company + '</strong></p>' +
                        '<div class="text-2xl font-bold text-green-600 mb-2">' + caseStudy.improvement + ' → ' + caseStudy.metric + '</div>' +
                        '<p class="text-sm text-gray-600 mb-2">' + caseStudy.details + '</p>' +
                        '<p class="text-sm text-gray-700">⏱️ Tiempo: ' + caseStudy.time + '</p>';
                }
                
                document.getElementById('placeholder').classList.add('hidden');
                document.getElementById('results').classList.remove('hidden');
            } else {
                document.getElementById('placeholder').classList.remove('hidden');
                document.getElementById('results').classList.add('hidden');
            }
        }
    </script>
</body>
</html>
    
<?php
    return ob_get_clean();
}
add_shortcode('calculadora_roi', 'delegup_calculadora_roi');