<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');
require_once 'ia-marketing-results.php';
require_once 'media/videos-ia.php';

$client_name = $client_info['name'] ?? '';
$business_name = $client_info['business_name'] ?? '';
$phone = $client_info['phone'] ?? '';
$whatsapp = $client_info['whatsapp'] ?? '';
$email = $client_info['email'] ?? '';
$website = $client_info['website'] ?? '';
$operating_cities = $client_info['operating_cities'] ?? '';
$logo_url = $client_info['logo_url'] ?? '';
$value_proposition = $ia_results['value_proposition'] ?? '';
$current_client_profiles = $ia_results['ideal_client_profiles'] ?? [];
$social_links = $client_info['social_links'] ?? [];

if (ob_get_level() > 0) { ob_end_clean(); }
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Análisis De Negocio FODA Con <?php echo htmlspecialchars($branding['iamarketing_name']); ?> Powered_by <?php echo htmlspecialchars($branding['powered_by']); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
</head>
<body data-page-title="Análisis De Negocio FODA"
      data-page-subtitle="Identifica Fortalezas, Oportunidades, Debilidades y Amenazas"
      data-page-icon="brain">

    <div id="toast-container" class="toast-container"></div>

    <?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'ia-menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
        </header>

        <div id="content-area" class="p-4 md:p-8">
            <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                <div class="lg:col-span-3">
                    <form id="foda-form" class="space-y-6">
                        <input type="hidden" name="value_proposition" value="<?php echo htmlspecialchars($value_proposition); ?>">
                        
                        <div class="bg-white p-8 rounded-xl shadow-md">
                            <div class="step-header">
                                <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                    <span class="step-number text-[var(--color-primary)]"> <i data-lucide="briefcase" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:</span>
                                    <span class="step-title ml-2">Información de tu Negocio</span>
                                </h2>
                            </div>
                            <div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <div class="space-y-6">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-8">
                                    <div class="form-question flex flex-col">
                                        <label for="person_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tu Nombre</label>
                                        <input type="text" id="person_name" name="person_name" placeholder="Ej: Juan Pérez" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($client_name); ?>">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label for="business_name" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Nombre de tu Negocio</label>
                                        <input type="text" id="business_name" name="business_name" placeholder="Ej: Café El Rincón" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]" value="<?php echo htmlspecialchars($business_name); ?>">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label for="location" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Ciudades Donde Operas</label>
                                         <input type="text" id="location" name="location" placeholder="Ej: Miami, Florida" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]" <?php if (!empty($operating_cities)) { echo 'value="' . htmlspecialchars($operating_cities) . '"'; } ?>>                                     </div>
                                    <div class="form-question flex flex-col">
                                        <label for="business_type" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Tipo de Negocio / Industria</label>
                                        <input type="text" id="business_type" name="business_type" placeholder="Ej: Cafetería De Especialidad" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                </div>
                                 <div class="form-question flex flex-col">
                                     <label for="target_client" class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Quién es tu Público Objetivo?</label>
                                     <input type="text" id="target_client" name="target_client" placeholder="Ej: Jóvenes Profesionales y Turistas" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                 </div>
                            </div>
                        </div>

                        <div class="bg-white p-8 rounded-xl shadow-md">
                            <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <span class="step-number text-[var(--color-primary)]"> <i data-lucide="zap" class="mr-3 text-[var(--color-secondary)]"></i> PASO 2:</span>
                                    <span class="step-title ml-2">Tus Fortalezas (Interno, Positivo)</span>
                            </h2>
                            </div><div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <div class="space-y-6">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-8">
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué es lo que tus clientes más elogian?</label>
                                        <input type="text" name="s_q1" placeholder="Ej: Nuestro Servicio Al Cliente Amigable" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué haces mejor que tu competencia?</label>
                                        <input type="text" name="s_q2" placeholder="Ej: La Calidad De Nuestros Ingredientes" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué activo valioso tienes?</label>
                                        <input type="text" name="s_q3" placeholder="Ej: Ubicación En Avenida Principal" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué ventaja única tiene tu negocio?</label>
                                        <input type="text" name="s_q4" placeholder="Ej: 15 Años De Experiencia En El Sector" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                </div>
                                <div class="form-question flex flex-col">
                                    <label for="strengths_extra" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Otra fortaleza importante:</label>
                                    <textarea id="strengths_extra" name="strengths_extra" rows="2" placeholder="Ej: Nuestro Branding Es Fuerte" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="bg-white p-8 rounded-xl shadow-md">
                            <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <span class="step-number text-[var(--color-primary)]"> <i data-lucide="cloud-rain" class="mr-3 text-[var(--color-secondary)]"></i> PASO 3:</span>
                                    <span class="step-title ml-2">Tus Debilidades (Interno, Negativo)</span>
                            </h2>
                            </div><div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <div class="space-y-6">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-8">
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿De qué suelen quejarse los clientes?</label>
                                        <input type="text" name="w_q1" placeholder="Ej: El Local Es Un Poco Pequeño" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué consideras que hace mejor tu competencia?</label>
                                        <input type="text" name="w_q2" placeholder="Ej: Tienen Mejores Precios" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué recurso importante te falta?</label>
                                        <input type="text" name="w_q3" placeholder="Ej: Presupuesto Limitado Para Marketing" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué te está impidiendo crecer?</label>
                                        <input type="text" name="w_q4" placeholder="Ej: Procesos Manuales Lentos" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                </div>
                                <div class="form-question flex flex-col">
                                    <label for="weaknesses_extra" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Otra debilidad importante:</label>
                                    <textarea id="weaknesses_extra" name="weaknesses_extra" rows="2" placeholder="Ej: No Contamos Con Una Página Web" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="bg-white p-8 rounded-xl shadow-md">
                            <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <span class="step-number text-[var(--color-primary)]"> <i data-lucide="sun" class="mr-3 text-[var(--color-secondary)]"></i> PASO 4:</span>
                                    <span class="step-title ml-2">Tus Oportunidades (Externo, Positivo)</span>
                            </h2>
                            </div><div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <div class="space-y-6">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-8">
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué tendencia de mercado puedes aprovechar?</label>
                                        <input type="text" name="o_q1" placeholder="Ej: Interés En Productos Ecológicos" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Hay algún grupo de clientes que no atiendes?</label>
                                        <input type="text" name="o_q2" placeholder="Ej: Turistas Que Visitan La Zona" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Podrías ofrecer un nuevo producto/servicio?</label>
                                        <input type="text" name="o_q3" placeholder="Ej: Catering Para Oficinas Cercanas" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Algún cambio en tu localidad te beneficia?</label>
                                        <input type="text" name="o_q4" placeholder="Ej: Nuevo Complejo De Oficinas Cerca" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                </div>
                                <div class="form-question flex flex-col">
                                    <label for="opportunities_extra" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Otra oportunidad importante:</label>
                                    <textarea id="opportunities_extra" name="opportunities_extra" rows="2" placeholder="Ej: Vender Nuestro Producto En Línea" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="bg-white p-8 rounded-xl shadow-md">
                            <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <span class="step-number text-[var(--color-primary)]"> <i data-lucide="shield" class="mr-3 text-[var(--color-secondary)]"></i> PASO 5:</span>
                                    <span class="step-title ml-2">Tus Amenazas (Externo, Negativo)</span>
                            </h2>
                            </div><div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <div class="space-y-6">
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-8">
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Quién es tu mayor competidor Directo o Indirecto?</label>
                                        <input type="text" name="t_q1" placeholder="Ej: Una Nueva Franquicia Abrió A Dos Cuadras" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué tendencia del mercado podría perjudicarte?</label>
                                        <input type="text" name="t_q2" placeholder="Ej: La Gente Prefiere Comprar Online" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿El aumento de costos te está afectando?</label>
                                        <input type="text" name="t_q3" placeholder="Ej: El Precio Del Café Ha Subido Un 20%" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                    <div class="form-question flex flex-col">
                                        <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué obstáculo externo consideras que enfrentas?</label>
                                        <input type="text" name="t_q4" placeholder="Ej: Nuevas Regulaciones Sanitarias" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]">
                                    </div>
                                </div>
                                <div class="form-question flex flex-col">
                                    <label for="threats_extra" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Otra amenaza importante:</label>
                                    <textarea id="threats_extra" name="threats_extra" rows="2" placeholder="Ej: Las Nuevas Generaciones No Toman Mucho Café" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="bg-white p-8 rounded-xl shadow-md">
                            <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <span class="step-number text-[var(--color-primary)]"> <i data-lucide="target" class="mr-3 text-[var(--color-secondary)]"></i> PASO 6:</span>
                                    <span class="step-title ml-2">El Objetivo Principal Para Tu Negocio</span>
                            </h2>
                            </div><div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <div class="space-y-6">
                                <div class="form-question flex flex-col">
                                    <label class="block font-bold capitalize text-gray-700 mb-2 text-lg">¿Qué es lo más importante que quieres lograr en los próximos 6-12 meses?</label>
                                    <textarea id="objective" name="objective" rows="3" placeholder="Ej: Aumentar Mis Ventas En Un 25% Y Convertirme En La Cafetería Preferida De La Zona" class="w-full p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-1 focus:ring-[var(--color-highlight)]"></textarea>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <div class="lg:col-span-2 space-y-8">
                    
                    <?php if (!empty($logo_url)): ?>
                        <div class="bg-white p-4 rounded-xl shadow-md">
                            <img src="<?php echo htmlspecialchars($logo_url); ?>" 
                                 alt="Logotipo de <?php echo htmlspecialchars($business_name); ?>" 
                                 class="block mx-auto object-contain h-24 max-w-[250px]">
                        </div>
                    <?php endif; ?>

                    <button id="open-swot-panel-btn" class="btn btn-primary w-full py-4 px-6 rounded-lg font-black text-lg uppercase gap-2 hover:scale-102 transition-transform shadow-lg">
                        <i data-lucide="save" class="w-5 h-5"></i> <span>Análisis FODA De Tu Negocio</span>
                    </button>
                    
                    <div class="w-full">
                        <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                            <div class="relative w-full pb-[56.25%]">
                                <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload fullscreen" preload="metadata">
                                    <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                                    TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                                </video>
                                <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                                    <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                                    <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                                    <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                                </div>
                            </div>
                            <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                                <span class="inline-flex items-center gap-2">
                                    <i data-lucide="play-circle" class="w-4 h-4"></i> Video Tutorial
                                </span>
                                <span class="inline-flex items-center gap-2">
                                    <i data-lucide="clock" class="w-4 h-4"></i> 2:30 min
                                </span>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white text-brand-dark p-6 md:p-8 rounded-xl shadow-md">
                        <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center justify-center md:justify-start">
                                <i data-lucide="book-open" class="mr-3 text-[var(--color-highlight)]"></i>
                                <span class="step-title">INSTRUCCIONES IMPORTANTES</span>
                            </h2>
                            <p class="step-subtitle text-center md:text-left uppercase text-gray-500 font-bold mt-2">REVISA ESTOS PUNTOS DETALLADAMENTE</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        <ul class="space-y-4 text-gray-700">
                            <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="file-text" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">SÉ HONESTO Y DETALLADO:</strong> Cuanta más información real y específica proporciones, más útil será el plan de acción de nuestra IA Marketing.</div></li>
                            <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="target" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">DEFINE UN OBJETIVO CLARO:</strong> El plan de IA Marketing se adaptará para ayudarte a alcanzar la meta que definas.</div></li>
                            <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="shield" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">PIENSA EN LO EXTERNO:</strong> Considera factores que no controlas, como la competencia, nuevas leyes o tendencias del mercado.</div></li>
                            <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="zap" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">IDENTIFICA TUS RECURSOS:</strong> Piensa en tus fortalezas: ¿tienes un equipo talentoso, una ubicación excelente o productos únicos?</div></li>
                            <li class="flex items-start gap-3"><span class="bg-[var(--color-highlight)] p-1 rounded text-[var(--color-primary)]"><i data-lucide="brain-circuit" class="w-4 h-4"></i></span><div><strong class="text-[var(--color-primary)] font-black uppercase">RECIBE TU ESTRATEGIA:</strong> Una vez que completes todos los campos, la herramienta procesará la información.</div></li>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="lg:col-span-5 bg-white p-6 md:p-8 rounded-xl shadow-md mt-6">
                <div class="step-header">
                    <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                        <span class="step-number text-[var(--color-primary)]"> <i data-lucide="rocket" class="mr-3 text-[var(--color-secondary)]"></i> PASO 7:</span>
                        <span class="step-title ml-2">GENERA TU PLAN ESTRATÉGICO</span>
                    </h2>
                    <p class="step-subtitle uppercase text-gray-500 font-bold mt-2">Obtén un análisis detallado y un plan de acción para tu negocio.</p>
                </div>
                <div class="border-b border-gray-200 pb-4 mb-6"></div>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 md:gap-8 items-center">
                    <div class="flex flex-col justify-center items-center bg-[var(--color-primary)] p-6 rounded-xl shadow-lg">
                        <i data-lucide="brain" class="w-24 h-24 md:w-32 md:h-32 text-white animate-pulse"></i>
                        <p class="mt-4 text-white font-black text-xl uppercase tracking-wide">
                            IA<span class="text-[var(--color-highlight)]">Marketing</span>™
                        </p>
                    </div>

                    <div class="md:col-span-2 text-center md:text-left">
                        <h3 class="text-2xl font-black text-gray-800 flex items-center justify-center md:justify-start mb-2 uppercase">
                            <i data-lucide="bell-electric" class="w-6 h-6 text-[var(--color-secondary)] mr-2 flex-shrink-0"></i>
                            Información Importante
                        </h3>
                        <p class="text-lg text-gray-700 mb-6">
                            Para que el análisis sea efectivo, <b>es importante</b> que los datos sobre tu negocio sean realistas. Con los detalles que proporciones, nuestra <b>inteligencia artificial</b> creará un <b>Análisis De Negocio FODA</b> para que identifiques tus fortalezas, oportunidades, debilidades y amenazas.
                        </p>
                        
                        <div class="flex justify-center md:justify-start">
                            <button id="generateBtn" type="submit" form="foda-form" class="btn btn-primary w-full sm:w-auto py-4 px-6 rounded-lg text-lg flex items-center justify-center uppercase shadow-xl hover:scale-105 transition-transform">
                                <i data-lucide="arrow-big-right-dash" class="w-6 h-6"></i>
                                <span id="btn-text">GENERAR ANÁLISIS FODA CON IA</span>
                                <div id="loader-container" class="hidden ml-3"></div>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div id="ai-response-container" class="mt-8 hidden">
                <div id="ai-response-content" class="ai-response-formatted"></div>
                <div id="action-buttons-container" class="mt-4 text-center">
                    <button id="save-swot-btn" class="btn btn-primary font-bold py-3 px-6 rounded-lg flex items-center justify-center mx-auto mt-4 gap-2 hover:scale-105 transition-transform uppercase">
                        <i data-lucide="save"></i> <span>Guardar Análisis FODA</span>
                    </button>
                </div>
            </div>
        </div>
    </main>
</div>

<div id="swot-panel-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden" aria-hidden="true"></div>

<div id="swot-panel" class="fixed top-0 right-0 h-full w-full lg:w-1/2 bg-[var(--color-background)] z-50 transform translate-x-full transition-transform duration-300 ease-in-out shadow-2xl flex flex-col">
    
    <div class="flex-shrink-0 flex justify-between items-center p-4 border-b border-gray-200 bg-[var(--color-primary)] text-white shadow z-20">
        <h3 class="text-3xl font-black text-[var(--color-highlight)] flex items-center uppercase">
            <i data-lucide="save" class="w-8 h-8 mr-2 text-white"></i>
            TU ANÁLISIS FODA
        </h3>
        <button id="close-swot-panel-btn" class="text-white hover:text-[var(--color-highlight)] p-1 rounded-md transition-colors duration-200">
            <i data-lucide="x" class="w-8 h-8"></i>
        </button>
    </div>

    <div class="flex-grow overflow-y-auto p-6 relative">
        <div id="swot-panel-content" class="bg-white p-6 rounded-xl shadow-md transition duration-300 min-h-[200px]">
            <div class="flex flex-col items-center justify-center h-40 text-gray-400">
                <i data-lucide="loader-2" class="w-8 h-8 animate-spin mb-2"></i>
                <span class="text-sm font-bold uppercase">Cargando análisis...</span>
            </div>
        </div>
    </div>

    <div class="p-4 bg-gray-100 border-t border-gray-200 flex-shrink-0 z-10"> 
        <button type="button" onclick="document.getElementById('close-swot-panel-btn').click()" class="w-full btn btn-secondary uppercase flex items-center justify-center gap-2">
            <i data-lucide="x-circle" class="w-5 h-5"></i> CERRAR PANEL DE RESULTADOS
        </button>
    </div>

</div>

<div id="confirmation-modal" 
     class="fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center hidden z-[100]"
     onclick="if(event.target === this) closeModal()">
    
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-sm m-4 transform transition-all duration-300 scale-95 opacity-0 text-center">
        
        <div class="modal-header-container rounded-t-xl pt-6">
            <h3 id="modal-title" class="text-4xl font-black uppercase text-[var(--color-highlight)] leading-none">CONFIRMAR</h3>
        </div>

        <div class="p-8">
            <div class="flex justify-center mb-6">
                <i id="modal-icon" data-lucide="alert-triangle" class="w-16 h-16 text-[var(--color-secondary)]"></i>
            </div>
            
            <p id="modal-message" class="text-[var(--color-primary)] mb-6 uppercase text-lg font-bold leading-tight">
                ¿ESTÁS SEGURO DE ESTA ACCIÓN?
            </p>

            <div class="flex flex-col sm:flex-row justify-center space-y-2 sm:space-y-0 sm:space-x-4 mt-8">
                <button type="button" class="btn btn-secondary font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2" id="modal-cancel-btn">
                    <i data-lucide="x-circle" class="w-5 h-5"></i> CANCELAR
                </button>
                
                <button type="button" class="btn btn-primary font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all duration-200" id="modal-confirm-btn">
                    CONFIRMAR
                </button>
            </div>
        </div>
    </div>
</div>

<script type="module">
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();
    
    // MENU MOBILE
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');

    mobileMenuButton.addEventListener('click', () => {
        sidebar.classList.toggle('-translate-x-full');
        sidebarOverlay.classList.toggle('hidden');
    });

    sidebarOverlay.addEventListener('click', () => {
        sidebar.classList.add('-translate-x-full');
        sidebarOverlay.classList.add('hidden');
    });
    if (playOverlay && videoPlayer) {
        videoPlayer.controls = false;
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.controls = true;
            videoPlayer.play().catch(e => {
                if (typeof showToast === 'function') {
                    showToast("Error al reproducir video: " + e.message, "error");
                }
            });
        });
        videoPlayer.addEventListener('ended', () => {
            playOverlay.style.display = 'flex';
            videoPlayer.controls = false;
        });
    }

    // --- ELEMENTOS FODA ---
    const form = document.getElementById('foda-form');
    const getAiAdviceBtn = document.getElementById('generateBtn');
    const aiResponseContainer = document.getElementById('ai-response-container');
    const aiResponseContent = document.getElementById('ai-response-content');
    const saveSwotBtn = document.getElementById('save-swot-btn');

    // --- PANEL LATERAL FODA ---
    const openSwotPanelBtn = document.getElementById('open-swot-panel-btn');
    const closeSwotPanelBtn = document.getElementById('close-swot-panel-btn');
    const swotPanelOverlay = document.getElementById('swot-panel-overlay');
    const swotPanel = document.getElementById('swot-panel');
    const swotPanelContent = document.getElementById('swot-panel-content');
    
    // --- MODAL DE CONFIRMACIÓN (Global) ---
    const modal = document.getElementById('confirmation-modal');
    const modalBox = modal.querySelector('div:first-of-type');
    const modalIcon = document.getElementById('modal-icon');
    const modalTitle = document.getElementById('modal-title');
    const modalMessage = document.getElementById('modal-message');
    const modalCancelBtn = document.getElementById('modal-cancel-btn');
    const modalConfirmBtn = document.getElementById('modal-confirm-btn');
    let onConfirmCallback = null;
    
    // --- DATOS GLOBALES ---
    let swotGuardadoActual = <?php echo json_encode($current_swot_analysis ?? null); ?>;
    let swotGeneradoReciente = null;

    // --- LÓGICA DEL MODAL DE CONFIRMACIÓN ---
    function openModal({ title, message, icon, confirmText, confirmClass, onConfirm }) {
        modalTitle.textContent = title;
        modalMessage.innerHTML = message;
        modalIcon.setAttribute('data-lucide', icon);
        lucide.createIcons({ nodes: [modalIcon] });

        modalConfirmBtn.textContent = confirmText || 'CONFIRMAR';
        // Reiniciar clases base
        modalConfirmBtn.className = 'btn font-black py-2.5 px-4 rounded-lg uppercase w-full sm:w-auto flex items-center justify-center gap-2 shadow-md transition-all duration-200';
        
        if (confirmClass === 'danger') {
            modalConfirmBtn.classList.add('btn-primary'); 
        } else if (confirmClass === 'primary') {
             modalConfirmBtn.classList.add('btn-secondary');
        } else {
             modalConfirmBtn.classList.add('btn-primary');
        }

        onConfirmCallback = onConfirm; 

        modal.classList.remove('hidden');
        setTimeout(() => modalBox.classList.remove('scale-95', 'opacity-0'), 50);
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        modalBox.classList.add('scale-95', 'opacity-0');
        setTimeout(() => {
            modal.classList.add('hidden');
            document.body.style.overflow = '';
        }, 300);
        onConfirmCallback = null;
    }

    modalCancelBtn.addEventListener('click', closeModal);
    modalConfirmBtn.addEventListener('click', () => {
        if (typeof onConfirmCallback === 'function') {
            onConfirmCallback();
        }
        closeModal();
    });

    // --- LÓGICA DEL PANEL LATERAL FODA ---
    function openSwotPanel() {
        swotPanel.classList.remove('translate-x-full');
        swotPanelOverlay.classList.remove('hidden');
        // Usamos la variable global para dibujar el contenido
        drawSwotPanelContent(swotGuardadoActual); 
    }

    function closeSwotPanel() {
        swotPanel.classList.add('translate-x-full');
        swotPanelOverlay.classList.add('hidden');
    }

    if(openSwotPanelBtn) openSwotPanelBtn.addEventListener('click', openSwotPanel);
    if(closeSwotPanelBtn) closeSwotPanelBtn.addEventListener('click', closeSwotPanel);
    if(swotPanelOverlay) swotPanelOverlay.addEventListener('click', closeSwotPanel);

    // --- [FUNCIÓN MODIFICADA] ---
    function drawSwotPanelContent(swotContent) {
        if (swotContent && swotContent.trim() !== '') {
            // 1. Parsear el contenido para la vista atractiva
            const formattedHtml = parseAndFormatAIResponse(swotContent);
            
            swotPanelContent.innerHTML = `
                <div class="space-y-3">
                    <div class="flex justify-end space-x-2 mb-4 pr-3">
                        <button id="panel-swot-btn-eliminar" class="btn btn-primary text-white text-xs py-2 px-3">
                            <i data-lucide="trash-2" class="w-4 h-4"></i> ELIMINAR
                        </button>
                    </div>

                    <div id="swot-display-container" class="ai-response-formatted p-4 border rounded-lg">
                        ${formattedHtml}
                    </div>
                </div>
            `;
            // Re-renderizar iconos en el panel
            lucide.createIcons();
            assignSwotPanelButtonEvents();
        } else {
            swotPanelContent.innerHTML = `
                <div class="text-center p-4 border border-dashed rounded-lg">
                    <i data-lucide="info" class="w-12 h-12 text-gray-400 mx-auto mb-3"></i>
                    <p class="text-gray-500">
                        Aún no tienes un Análisis FODA guardado. ¡Genera uno para empezar!
                    </p>
                </div>
            `;
            lucide.createIcons();
        }
    }

    // --- [FUNCIÓN MODIFICADA] ---
    // Solo asigna el evento de eliminación (no hay edición)
    function assignSwotPanelButtonEvents() {
        const btnEliminar = document.getElementById('panel-swot-btn-eliminar');
        
        if (btnEliminar) {
            btnEliminar.addEventListener('click', () => {
                openModal({
                    title: 'CONFIRMAR ELIMINACIÓN',
                    message: '¿Estás seguro de que quieres eliminar tu Análisis FODA? <br> Esta acción no se puede deshacer.',
                    icon: 'alert-triangle',
                    confirmText: 'SÍ, ELIMINAR',
                    confirmClass: 'danger',
                    onConfirm: async () => {
                        await deleteSwotFromDB();
                        // Al eliminar, actualizamos el panel para mostrar el estado vacío
                        drawSwotPanelContent(swotGuardadoActual); 
                    }
                });
            });
        }
    }
    
    // --- LÓGICA DE PERSISTENCIA CRUD (SWOT) ---
    const swotEndpoints = {
        create: 'api-db/ia-swot-analysis-create.php',
        update: 'api-db/ia-swot-analysis-update.php',
        delete: 'api-db/ia-swot-analysis-delete.php'
    };

    async function updateSwotInDB(swotContent) {
        setProcessingState(true, 'Actualizando...');
        try {
            const response = await fetch(swotEndpoints.update, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ swot_content: swotContent })
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                swotGuardadoActual = swotContent; // Actualiza la variable global
            } else {
                throw new Error(result.message || 'Error desconocido al actualizar FODA');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al actualizar FODA: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    async function createSwotInDB(swotContent) {
        setProcessingState(true, 'Guardando...');
        try {
            const response = await fetch(swotEndpoints.create, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ swot_content: swotContent })
            });
            const result = await response.json();
            
            if (response.ok) {
                if (result.success) {
                    if (typeof showToast === 'function') showToast(result.message, 'success');
                    swotGuardadoActual = swotContent; // Actualiza la variable global
                    openSwotPanel(); // Mostrar el resultado en el panel
                } else {
                    // Manejo del error 409 (Conflicto) de la API
                    if (response.status === 409) {
                        throw new Error('A SWOT analysis already exists'); 
                    }
                    throw new Error(result.message || 'Error desconocido al crear FODA');
                }
            } else {
                throw new Error(result.message || 'Error desconocido del servidor (' + response.status + ')');
            }

        } catch (error) {
            throw error; // Propagar el error para el manejo de sobrescritura
        } finally {
            setProcessingState(false);
        }
    }
    
    async function deleteSwotFromDB() {
        setProcessingState(true, 'Eliminando...');
        try {
            const response = await fetch(swotEndpoints.delete, {
                method: 'POST', 
                headers: { 'Content-Type': 'application/json' }
            });
            const result = await response.json();
            
            if (response.ok && result.success) {
                if (typeof showToast === 'function') showToast(result.message, 'success');
                swotGuardadoActual = ''; // Limpia la variable global
            } else {
                throw new Error(result.message || 'Error desconocido al eliminar FODA');
            }
        } catch (error) {
            if (typeof showToast === 'function') showToast(`Error al eliminar FODA: ${error.message}`, 'error');
        } finally {
            setProcessingState(false);
        }
    }
    
    // Evento del botón de GUARDAR de la respuesta de la IA
    document.addEventListener('click', (e) => {
        // Usar .closest por si se hace clic en el icono dentro del botón
        const btn = e.target.closest('#save-swot-btn');
        if (btn) {
            if (!swotGeneradoReciente) {
                if (typeof showToast === 'function') showToast("Debes generar un análisis FODA primero.", "error");
                return;
            }

            const saveAction = async () => {
                try {
                    await createSwotInDB(swotGeneradoReciente);
                } catch (error) {
                    if (error.message.includes('A SWOT analysis already exists')) {
                        // Si ya existe, pedir confirmación para sobrescribir
                        openModal({
                            title: 'CONFIRMAR SOBRESCRIBIR',
                            message: 'Ya tienes un Análisis FODA guardado. ¿Deseas reemplazarlo con la versión actual?',
                            icon: 'refresh-cw',
                            confirmText: 'SÍ, REEMPLAZAR',
                            confirmClass: 'danger',
                            onConfirm: () => {
                                updateSwotInDB(swotGeneradoReciente);
                                openSwotPanel();
                            }
                        });
                    } else {
                        if (typeof showToast === 'function') showToast(`Error al guardar: ${error.message}`, "error");
                    }
                }
            };

            saveAction();
        }
    });


    // --- LÓGICA DE GENERACIÓN DE IA (Mantenida) ---
    const messages = ["Analizando tu negocio...", "Cruzando datos...", "Creando tu plan estratégico...", "Afinando los detalles..."];
    let loadingInterval = null;

    const setProcessingState = (isProcessing, customMessage = null) => {
        const btnText = document.getElementById('btn-text');
        const loaderContainer = document.getElementById('loader-container');
        
        loaderContainer.classList.toggle('hidden', !isProcessing);
        getAiAdviceBtn.disabled = isProcessing;
        getAiAdviceBtn.classList.toggle('opacity-50', isProcessing);
        getAiAdviceBtn.classList.toggle('cursor-not-allowed', isProcessing);
        
        // Ocultar el botón de guardar durante la carga
        if (document.getElementById('save-swot-btn')) {
            document.getElementById('save-swot-btn').classList.toggle('hidden', isProcessing);
        }

        if (isProcessing) {
            loaderContainer.innerHTML = '<div class="w-6 h-6 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin"></div>';
            aiResponseContainer.classList.add('hidden');
            aiResponseContent.innerHTML = '';
            
            if (customMessage) {
                btnText.textContent = customMessage;
                if (window.loadingInterval) clearInterval(window.loadingInterval);
                return;
            }

            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

        } else {
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            btnText.textContent = 'GENERAR CON IA MARKETING';
            // Mostrar el botón de guardar al terminar
            if (document.getElementById('save-swot-btn')) {
                 document.getElementById('save-swot-btn').classList.remove('hidden');
            }
        }
    };
    
    // --- [FUNCIÓN CLAVE] ---
    const parseAndFormatAIResponse = (rawText) => {
        let html = '';
        // Elimina los asteriscos de negrita (**) que pueden venir de la IA
        const cleanText = rawText.replace(/\*\*/g, '');
        
        // Divide el texto en las secciones que definiste en el prompt
        const sections = cleanText.split('---SECCION---');
        
        // --- Sección 1: Cabecera (Título e Intro) ---
        const headerSection = sections.shift() || '';
        const headerLines = headerSection.trim().split('\n');
        const mainTitle = headerLines.shift() || '';
        const intro = headerLines.join(' ').trim(); // Une el resto de líneas como párrafo
        
        if (mainTitle) html += `<h1 class="text-3xl font-black text-center uppercase text-brand-dark mb-4">${mainTitle}</h1>`;
        if (intro) html += `<p class="text-md text-center text-gray-600 max-w-3xl mx-auto mb-10">${intro}</p>`;
        
        // --- Metadatos para las tarjetas ---
        const strategyMeta = {
            "A.": { icon: 'rocket', class: 'strategy-offensive', title: 'ESTRATEGIAS OFENSIVAS (FORTALEZAS + OPORTUNIDADES)' },
            "B.": { icon: 'compass', class: 'strategy-reorientation', title: 'ESTRATEGIAS DE REORIENTACIÓN (DEBILIDADES + OPORTUNIDADES)' },
            "C.": { icon: 'shield', class: 'strategy-defensive', title: 'ESTRATEGIAS DEFENSIVAS (FORTALEZAS + AMENAZAS)' },
            "D.": { icon: 'anchor', class: 'strategy-survival', title: 'ESTRATEGIAS DE SUPERVIVENCIA (DEBILIDADES + AMENAZAS)' }
        };
        
        // --- Sección 2: Plan de Acción (Las Tarjetas) ---
        const planSection = sections.shift() || '';
        if (planSection) {
            const planLines = planSection.trim().split('\n').filter(l => l.trim() !== '');
            const planTitle = planLines.shift() || '';
            
            if (planTitle) html += `<h2 class="text-4xl font-black text-center text-brand-secondary mb-8">${planTitle}</h2>`;
            
            html += '<div class="grid grid-cols-1 md:grid-cols-2 gap-8">';
            
            let currentCardHtml = '', currentCardClass = '', currentCardIcon = '', currentCardTitle = '';
            
            planLines.forEach(line => {
                // Detecta si la línea es un nuevo título de estrategia (A., B., C., D.)
                const strategyKey = Object.keys(strategyMeta).find(key => line.startsWith(key));
                
                if (strategyKey) {
                    // Si es un título nuevo, cierra la tarjeta anterior (si existe)
                    if (currentCardHtml) {
                        html += `<div class="strategy-card ${currentCardClass}"><div class="strategy-title"><i data-lucide="${currentCardIcon}"></i><h3>${currentCardTitle}</h3></div><ul>${currentCardHtml}</ul></div>`;
                    }
                    // Inicia una nueva tarjeta
                    currentCardClass = strategyMeta[strategyKey].class;
                    currentCardIcon = strategyMeta[strategyKey].icon;
                    currentCardTitle = strategyMeta[strategyKey].title;
                    currentCardHtml = ''; // Resetea el contenido
                } else if (line.includes('Acción')) {
                    // Si es una línea de acción, la añade como <li>
                    currentCardHtml += `<li>${line.replace(/Acción \d+:/, '').trim()}</li>`;
                }
            });
            
            // Cierra la última tarjeta
            if (currentCardHtml) {
                html += `<div class="strategy-card ${currentCardClass}"><div class="strategy-title"><i data-lucide="${currentCardIcon}"></i><h3>${currentCardTitle}</h3></div><ul>${currentCardHtml}</ul></div>`;
            }
            
            html += '</div>';
        }
        return html;
    };
    
    // Lógica principal para llamar a la IA
    const getAIAdvice = async () => {
        const formData = new FormData(document.getElementById('foda-form'));
        const payload = {
            person_name: formData.get('person_name'),
            business_name: formData.get('business_name'),
            location: formData.get('location'),
            business_type: formData.get('business_type'),
            target_client: formData.get('target_client'),
            value_proposition: formData.get('value_proposition'),
            strengths_questions: [formData.get('s_q1'), formData.get('s_q2'), formData.get('s_q3'), formData.get('s_q4')].filter(Boolean),
            strengths_extra: formData.get('strengths_extra'),
            weaknesses_questions: [formData.get('w_q1'), formData.get('w_q2'), formData.get('w_q3'), formData.get('w_q4')].filter(Boolean),
            weaknesses_extra: formData.get('weaknesses_extra'),
            opportunities_questions: [formData.get('o_q1'), formData.get('o_q2'), formData.get('o_q3'), formData.get('o_q4')].filter(Boolean),
            opportunities_extra: formData.get('opportunities_extra'),
            threats_questions: [formData.get('t_q1'), formData.get('t_q2'), formData.get('t_q3'), formData.get('t_q4')].filter(Boolean),
            threats_extra: formData.get('threats_extra'),
            objective: formData.get('objective'),
        };

        if (!payload.business_name || !payload.objective) {
            showToast("Por favor, completa al menos el nombre de tu negocio y tu objetivo principal.", "error");
            return;
        }

        setProcessingState(true);
        aiResponseContainer.classList.remove('hidden');

        try {
            // Se asume que el endpoint API de FODA también se renombró a /api-swot-analysis.php
            const response = await fetch('api/api-swot-analysis.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await response.json();
            
            if (!response.ok || data.error) {
                // [MANEJO DE ERROR MEJORADO]
                let errorMsg = data.error || `No se pudo obtener una respuesta válida del servicio de IA.`;
                // Si el error viene de la depuración de la API (502)
                if(data.api_response_body && data.api_response_body.error) {
                    errorMsg = `Error de Google API: ${data.api_response_body.error.message}`;
                } else if (data.curl_error) {
                    errorMsg = `Error de cURL: ${data.curl_error}`;
                }
                throw new Error(errorMsg);
            }
            if (data.generated_content) {
                aiResponseContent.innerHTML = parseAndFormatAIResponse(data.generated_content);
                swotGeneradoReciente = data.generated_content; // Guardar el resultado reciente
                lucide.createIcons();
            } else {
                throw new Error("La respuesta de la IA no tuvo el formato esperado.");
            }
            showToast("Estrategia generada con éxito.", "success");
        } catch (error) {
            aiResponseContent.innerHTML = `<div class="bg-[var(--color-secondary)] text-center p-4 text-white rounded-lg border border-[var(--color-secondary)]"><p><strong>Error:</strong> No se pudo generar la estrategia.</p><p class="mt-2 text-sm">${error.message || 'Error desconocido'}</p></div>`;
            showToast(`Error: ${error.message || 'Error desconocido'}`, "error");
        } finally {
            setProcessingState(false);
            aiResponseContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    };
    
    // Asignación del evento
    getAiAdviceBtn.addEventListener('click', (e) => {
        e.preventDefault();
        getAIAdvice();
    });
});
</script>
<script src="files/toast.js"></script>
</body>
</html>