<?php include 'files/guardiankey.php'; ?>
<?php
// =================================================================
//        DATA BLOCK FOR FORM PRE-FILLING (Best Practice)
// =================================================================

// 1. Include the central business information file.
//    This creates the $client_info variable with all the data.
include __DIR__ . '/client-information.php';

// 2. Assign info to easy-to-use variables for this form.
//    Using English names for consistency with the database and array keys.
$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'] ?? '';
$value_proposition = $client_info['value_proposition'] ?? '';
$logo_url          = $client_info['logo_url'] ?? '';

// Social links come as an array, hence the '?? []' fallback.
$social_links      = $client_info['social_links'] ?? [];

// =================================================================
?>
<!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 IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Identifica Fortalezas, Oportunidades, Debilidades y Amenazas">
    <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>

    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="tools.css">
    <script src="files/header-manager.js"></script>
    
    <style>
        .form-question label {
            font-size: 1.125rem; /* text-lg */
        }
        .ai-response-formatted .strategy-card {
            background-color: #ffffff; border-radius: 0.75rem; padding: 1.5rem;
            margin-bottom: 1.5rem; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
            border-left-width: 5px; transition: all 0.3s ease-in-out;
        }
        .ai-response-formatted .strategy-card:hover {
            transform: translateY(-5px); box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
        }
        .ai-response-formatted .strategy-title {
            font-size: 1.5rem; font-weight: 800; color: var(--color-primary);
            display: flex; align-items: center; margin-bottom: 1rem;
        }
        .ai-response-formatted .strategy-title i { margin-right: 0.75rem; width: 2rem; height: 2rem; }
        .ai-response-formatted .strategy-card ul { list-style: none; padding: 0; margin-top: 1rem; }
        .ai-response-formatted .strategy-card li {
            position: relative; padding-left: 1.75rem; margin-bottom: 0.75rem;
            color: #374151; line-height: 1.6;
        }
        .ai-response-formatted .strategy-card li::before {
            content: '✔'; position: absolute; left: 0; color: var(--color-highlight);
            font-weight: bold; font-size: 1.25rem;
        }
        .strategy-offensive { border-color: #22c55e; } .strategy-reorientation { border-color: #3b82f6; }
        .strategy-defensive { border-color: #f97316; } .strategy-survival { border-color: #ef4444; }
    </style>
</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"> <i data-lucide="briefcase" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:</span>
                                    <span class="step-title">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-2 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-2 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-2 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-2 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 cliente ideal?</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-2 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"> <i data-lucide="zap" class="mr-3 text-[var(--color-secondary)]"></i> PASO 2:</span>
                                 <span class="step-title">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-2 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-2 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-2 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 equipo o tú?</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-2 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-2 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"> <i data-lucide="cloud-rain" class="mr-3 text-[var(--color-secondary)]"></i> PASO 3:</span>
                                 <span class="step-title">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-2 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é 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-2 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-2 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-2 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-2 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"> <i data-lucide="sun" class="mr-3 text-[var(--color-secondary)]"></i> PASO 4:</span>
                                 <span class="step-title">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-2 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-2 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-2 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-2 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-2 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"> <i data-lucide="shield" class="mr-3 text-[var(--color-secondary)]"></i> PASO 5:</span>
                                 <span class="step-title">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-2 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-2 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-2 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 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-2 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-2 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"> <i data-lucide="target" class="mr-3 text-[var(--color-secondary)]"></i> PASO 6:</span>
                                 <span class="step-title">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-2 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" 
                                 style="max-width: 250px;">
                        </div>
                    <?php endif; ?>

                    <div class="w-full">
                        <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                            <div class="relative w-full" style="padding-bottom: 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 De Introducción A La Plataforma SiteFlowCMS
                                </span>
                                <span class="inline-flex items-center gap-2">
                                    <i data-lucide="clock" class="w-4 h-4"></i> 2–3 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 uppercase 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">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="instructions-list-item"><span class="icon-wrapper"><i data-lucide="file-text"></i></span><div><strong class="text-brand-dark 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. Explica la situación actual de tu negocio tal cual es para obtener un diagnóstico preciso.</div></li>
                            <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="target"></i></span><div><strong class="text-brand-dark uppercase">DEFINE UN OBJETIVO CLARO:</strong> El plan de IA Marketing se adaptará para ayudarte a alcanzar la meta que definas. Un objetivo específico y medible (ej. "Aumentar ventas en un 25% en 6 meses") te dará un camino más directo y efectivo.</div></li>
                            <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="shield"></i></span><div><strong class="text-brand-dark uppercase">PIENSA EN LO EXTERNO:</strong> Considera factores que no controlas, como la competencia, nuevas leyes o tendencias del mercado. Esto ayuda a la herramienta a identificar amenazas y oportunidades que podrías estar pasando por alto.</div></li>
                            <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="zap"></i></span><div><strong class="text-brand-dark uppercase">IDENTIFICA TUS RECURSOS:</strong> Piensa en tus fortalezas: ¿tienes un equipo talentoso, una ubicación excelente o productos únicos? Conocer tus activos es clave para que la IA Marketing sugiera estrategias que aprovechen al máximo lo que ya tienes.</div></li>
                            <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="brain-circuit"></i></span><div><strong class="text-brand-dark uppercase">RECIBE TU ESTRATEGIA:</strong> Una vez que completes todos los campos, la herramienta procesará la información. El resultado será un diagnóstico completo y un plan de acción paso a paso, listo para que lo apliques y obtengas resultados reales.</div></li>
                        </ul>
                    </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"> <i data-lucide="rocket" class="mr-3 text-[var(--color-secondary)]"></i> PASO 7:</span>
                            <span class="step-title">GENERA TU PLAN ESTRATÉGICO</span>
                        </h2>
                        <p class="step-subtitle uppercase">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="flex flex-col md:flex-row items-center md:justify-between gap-4">
                        <p class="text-lg text-center md:text-left text-gray-700 md:flex-1 md:pr-4 mb-0">Para que el análisis sea efectivo, <strong>es importante</strong> que los datos sobre tu negocio sean realistas. Con los detalles que proporciones, nuestra Inteligencia Artificial <strong>IA Marketing</strong> creará un <strong>Análisis De Negocio FODA</strong> para que identifiques tus fortalezas, oportunidades, debilidades y amenazas.</p>
                        <div class="flex flex-col items-center">
                            <i data-lucide="brain" class="w-12 h-12 text-[var(--color-primary)] mb-2"></i>
                             <button id="generateBtn" type="submit" form="foda-form" class="w-full md:w-auto bg-[var(--color-highlight)] text-[var(--color-primary)] font-bold py-4 px-6 rounded-lg hover:scale-105 transition-transform shadow-lg text-lg flex items-center justify-center gap-2 uppercase">
                               <span id="btn-text">GENERAR CON IA MARKETING</span>
                               <i data-lucide="mouse-pointer-click" class="w-6 h-6 animate-bounce"></i>
                               <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>
        </div>
    </main>
</div>

<script type="module">
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();
    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');
    const getAiAdviceBtn = document.getElementById('generateBtn');
    const aiResponseContainer = document.getElementById('ai-response-container');
    const aiResponseContent = document.getElementById('ai-response-content');
    const form = document.getElementById('foda-form');
    const messages = ["Analizando tu negocio...", "Cruzando datos...", "Creando tu plan estratégico...", "Afinando los detalles..."];
    let loadingInterval = null;

    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) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }

    const setProcessingState = (isProcessing) => {
        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);

        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 = '';
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);
        } else {
            if (loadingInterval) clearInterval(loadingInterval);
            btnText.textContent = 'GENERAR CON IA MARKETING';
        }
    };

    const parseAndFormatAIResponse = (rawText) => {
        let html = '';
        const cleanText = rawText.replace(/\*\*/g, '');
        const sections = cleanText.split('---SECCION---');
        const headerSection = sections.shift() || '';
        const planSection = sections.shift() || '';
        const headerLines = headerSection.trim().split('\n');
        const mainTitle = headerLines.shift() || '';
        const intro = headerLines.join(' ').trim();
        if (mainTitle) html += `<h1 class="text-3xl font-black text-center text-brand-dark mb-4">${mainTitle}</h1>`;
        if (intro) html += `<p class="text-lg text-center text-gray-600 max-w-3xl mx-auto mb-10">${intro}</p>`;
        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)' }
        };
        if (planSection) {
            const planLines = planSection.trim().split('\n').filter(l => l.trim() !== '');
            const planTitle = planLines.shift() || '';
            if (planTitle) html += `<h2 class="text-2xl font-bold text-center text-brand-dark 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 => {
                const strategyKey = Object.keys(strategyMeta).find(key => line.startsWith(key));
                if (strategyKey) {
                    if (currentCardHtml) html += `<div class="strategy-card ${currentCardClass}"><h3 class="strategy-title"><i data-lucide="${currentCardIcon}"></i>${currentCardTitle}</h3><ul>${currentCardHtml}</ul></div>`;
                    currentCardClass = strategyMeta[strategyKey].class;
                    currentCardIcon = strategyMeta[strategyKey].icon;
                    currentCardTitle = strategyMeta[strategyKey].title;
                    currentCardHtml = '';
                } else if (line.includes('Acción')) {
                    currentCardHtml += `<li>${line.replace(/Acción \d+:/, '').trim()}</li>`;
                }
            });
            if (currentCardHtml) html += `<div class="strategy-card ${currentCardClass}"><h3 class="strategy-title"><i data-lucide="${currentCardIcon}"></i>${currentCardTitle}</h3><ul>${currentCardHtml}</ul></div>`;
            html += '</div>';
        }
        return html;
    };

    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 {
            const response = await fetch('api/api-analisis-de-negocios-foda.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await response.json();
            if (!response.ok || data.error) {
                throw new Error(data.error || `No se pudo obtener una respuesta válida del servicio de IA.`);
            }
            if (data.generated_content) {
                aiResponseContent.innerHTML = parseAndFormatAIResponse(data.generated_content);
                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-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><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' });
        }
    };
    
    // He eliminado el evento 'submit' del formulario y lo he asignado directamente al botón.
    getAiAdviceBtn.addEventListener('click', (e) => {
        e.preventDefault();
        getAIAdvice();
    });
});
</script>
</body>
</html>