<?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>Optimizador De Perfil De Google Business Con IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Optimiza Tu Perfil Para Destacar En Búsquedas Y Mapas Locales">
    <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>
        .toggle-label { position: relative; display: inline-block; width: 50px; height: 28px; }
        .toggle-label input { opacity: 0; width: 0; height: 0; }
        .toggle-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 28px; }
        .toggle-slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
        input:checked + .toggle-slider { background-color: var(--color-primary); }
        input:checked + .toggle-slider:before { transform: translateX(22px); }

        .ai-response-formatted .ai-main-title { font-size: 2.25rem; font-weight: 900; color: var(--color-primary); text-align: center; margin-bottom: 0.5rem; }
        .ai-response-formatted .ai-intro-text { font-size: 1.125rem; text-align: center; color: #4a5568; margin-bottom: 2.5rem; max-width: 800px; margin-left: auto; margin-right: auto; }
        .ai-response-formatted .ai-action-card { background-color: #f7fafc; border: 1px solid #e2e8f0; border-left: 5px solid var(--color-secondary); border-radius: 0.75rem; padding: 1.5rem; margin-bottom: 1.5rem; }
        .ai-response-formatted .ai-action-title { font-size: 1.5rem; font-weight: 800; color: var(--color-primary); margin-bottom: 1rem; display: flex; align-items: center; }
        .ai-response-formatted .ai-action-title i { margin-right: 0.75rem; color: var(--color-secondary); }
        .ai-response-formatted .ai-action-why { margin-bottom: 1.5rem; line-height: 1.6; font-style: italic; color: #4a5568; background-color: #ffffff; padding: 1rem; border-radius: 0.5rem; border: 1px solid #e2e8f0; }
        .ai-response-formatted .ai-action-steps-title { font-weight: 700; color: var(--color-primary); margin-bottom: 0.75rem; text-transform: uppercase; font-size: 0.875rem; letter-spacing: 0.05em; }
        .ai-response-formatted .ai-action-steps { list-style: none; padding-left: 0; }
        .ai-response-formatted .ai-action-steps li { display: flex; align-items: flex-start; margin-bottom: 0.75rem; line-height: 1.6; }
        .ai-response-formatted .ai-action-steps i { color: var(--color-highlight); margin-right: 0.75rem; flex-shrink: 0; margin-top: 5px; }
    </style>
</head>
<body data-page-title="Optimizador De Perfil De Google Business"
      data-page-subtitle="Optimiza Tu Perfil Para Destacar En Búsquedas Y Mapas Locales"
      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">
            <section id="gbp-optimizer" class="dashboard-section">
                <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                    <div class="lg:col-span-3">
                        <div class="bg-white text-gray-800 rounded-xl shadow-md p-6 md:p-8">
                            <div class="step-header">
                                <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                    <i data-lucide="clipboard-list" class="mr-3 text-[var(--color-secondary)]"></i>
                                    <span class="text-[var(--color-secondary)] mr-2">PASO 1:</span> COMPLETA TU DIAGNÓSTICO
                                </h2>
                                <p class="step-subtitle uppercase">Responde para evaluar tu Perfil de Negocio en Google.</p>
                            </div>
                            <div class="border-b border-gray-200 pb-4 mb-6"></div>
                            <div id="checklist-container"></div>
                        </div>
                    </div>

                    <div class="lg:col-span-2 space-y-8">
                        <img src="img/VideoLeccion.png" alt="VideoLeccion - IAMarketing">
                        <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-[var(--color-primary)] text-white rounded-xl shadow-md p-6 border-2 border-[var(--color-highlight)] flex flex-col items-center justify-center">
                            <h3 class="text-2xl font-bold mb-4 text-center">Puntuación De Tu Perfil</h3>
                            <div id="score-display" class="text-7xl font-black text-[var(--color-highlight)] mb-2">0%</div>
                            <div class="w-full bg-gray-700 rounded-full h-4">
                                <div id="progress-bar" class="bg-[var(--color-highlight)] h-4 rounded-full" style="width: 0%; transition: width 0.5s;"></div>
                            </div>
                        </div>

                        <div class="bg-white text-[var(--color-primary)] 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="check-square"></i></span><div><strong class="text-[var(--color-primary)]">RESPONDE EL CUESTIONARIO:</strong> Evalúa cada punto de tu Perfil de Negocio de Google.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="bar-chart-2"></i></span><div><strong class="text-[var(--color-primary)]">MIRA TU PUNTUACIÓN:</strong> Descubre el nivel de optimización de tu perfil.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="list-checks"></i></span><div><strong class="text-[var(--color-primary)]">OBTÉN TAREAS PENDIENTES:</strong> Se generará una lista de acciones rápidas para mejorar.</div></li>
                                <li class="instructions-list-item"><span class="icon-wrapper"><i data-lucide="sparkles"></i></span><div><strong class="text-[var(--color-primary)]">GENERA LA ESTRATEGIA IA:</strong> Recibe un plan detallado para tus puntos débiles.</div></li>
                            </ul>
                        </div>
                    </div>
                
                    <div class="bg-white text-gray-800 rounded-xl shadow-md p-6 mt-8 lg:col-span-5">
                        <div class="step-header">
                            <h3 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <i data-lucide="list-checks" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">TAREAS:</span> TU PLAN DE ACCIÓN RÁPIDA
                            </h3>
                            <p class="step-subtitle uppercase">Una lista de acciones inmediatas basada en tu diagnóstico.</p>
                        </div>
                        <div class="border-b border-gray-200 pb-4 mb-6"></div>
                        <div id="task-list" class="space-y-4">
                            <p class="text-gray-500">Completa el diagnóstico para ver tus tareas pendientes aquí...</p>
                        </div>
                    </div>

                    <div id="ai-assistant-section" class="bg-white text-gray-800 rounded-xl shadow-md p-6 md:p-8 mt-8 lg:col-span-5">
                        <div class="step-header">
                            <h2 class="text-2xl font-black pb-0 mb-0 flex items-center uppercase">
                                <i data-lucide="bot" class="mr-3 text-[var(--color-secondary)]"></i>
                                <span class="text-[var(--color-secondary)] mr-2">PASO 2:</span> RECIBE TU ESTRATEGIA PERSONALIZADA
                            </h2>
                            <p class="step-subtitle uppercase">Basado en tu diagnóstico, la IA preparará un plan detallado para optimizar tu perfil.</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 destacar en Google My Business, <strong>es importante</strong> que tu perfil esté completo, optimizado y actualizado. Nuestra Inteligencia Artificial <strong>IA Marketing</strong> te guiará con un <strong>Plan De Optimización De Google Business</strong>, para que tu negocio aparezca en más búsquedas y mapas locales</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="get-ai-advice-btn" type="submit" 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 id="ai-response-container" class="mt-8 border-t border-gray-200 pt-6 hidden">
                            <div id="ai-response-content" class="ai-response-formatted"></div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

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

    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');
    });

    // --- NOTIFICACIONES TOAST 
    const urlParams = new URLSearchParams(window.location.search);
    const notificationType = urlParams.get('notification_type');
    const notificationMessage = urlParams.get('notification_message');

    if (notificationType && notificationMessage) {
        if (typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        } else {
            console.error("showToast function is not defined. Toast notification might not display.");
        }
    }
    
    // VIDEO PLAYER
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    
    playOverlay.addEventListener('click', () => {
        playOverlay.style.display = 'none';
        videoPlayer.play();
    });
    
     // MASCARA DEL TELEFONO
    const phoneInput = document.getElementById('contact_phone');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }
    
    const checklistData = [
        { id: 'nombre', question: '¿El nombre de tu negocio es exacto y no tiene palabras clave extra?', recommendation: 'Usa el nombre real y oficial de tu negocio. No añadas palabras como "el mejor" o nombres de ciudades.', category: 'Información Básica' },
        { id: 'categoria', question: '¿Tu perfil tiene la categoría de negocio correcta?', recommendation: 'Elige la categoría más específica posible. Esto le dice a Google qué tipo de clientes debe enviarte.', category: 'Información Básica' },
        { id: 'contacto', question: '¿Tu teléfono, dirección y página web están correctos y completos?', recommendation: 'Verifica que todos los datos de contacto estén actualizados para que los clientes puedan encontrarte.', category: 'Información Básica' },
        { id: 'horario', question: '¿Tu horario comercial está actualizado (incluyendo días festivos)?', recommendation: 'Define tu horario habitual y ajústalo en días festivos para no confundir a los clientes.', category: 'Información Básica' },
        { id: 'logo', question: '¿Has subido el logo de tu negocio en la foto de perfil?', recommendation: 'Sube un logo cuadrado y de buena calidad. Es la primera impresión de tu marca.', category: 'Fotos' },
        { id: 'portada', question: '¿Tienes una foto de portada atractiva que represente tu negocio?', recommendation: 'Elige una foto de portada panorámica que muestre lo mejor de tu local o servicio.', category: 'Fotos' },
        { id: 'fotos_extras', question: '¿Has añadido al menos 5 fotos más (de tu local, equipo o trabajos)?', recommendation: 'Añade fotos de calidad de tu equipo, productos o del trabajo que realizas para generar confianza.', category: 'Fotos' },
        { id: 'publicaciones', question: '¿Creas publicaciones (novedades u ofertas) regularmente?', recommendation: 'Publica al menos una vez cada 1-2 semanas para mantener tu perfil activo y mostrar que el negocio está abierto.', category: 'Actividad' },
        { id: 'reseñas', question: '¿Respondes a las nuevas reseñas de los clientes?', recommendation: 'Agradece las reseñas positivas y responde profesionalmente a las negativas. Demuestra que te importan tus clientes.', category: 'Reputación' },
        { id: 'servicios', question: '¿Has agregado una lista de tus productos o servicios?', recommendation: 'Detalla lo que ofreces en la sección "Servicios" o "Productos". Facilita que los clientes sepan qué vendes.', category: 'Oferta' },
    ];

    const checklistContainer = document.getElementById('checklist-container');
    const progressBar = document.getElementById('progress-bar');
    const scoreDisplay = document.getElementById('score-display');
    const taskList = document.getElementById('task-list');
    const getAiAdviceBtn = document.getElementById('get-ai-advice-btn');
    const aiResponseContainer = document.getElementById('ai-response-container');
    const aiResponseContent = document.getElementById('ai-response-content');

    function renderChecklist() {
        checklistContainer.innerHTML = checklistData.map(item => {
            const formattedQuestion = item.question.charAt(0).toUpperCase() + item.question.slice(1);
            return `
                <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center border-b border-gray-200 py-3 gap-3">
                    <p class="font-semibold text-lg text-[var(--color-primary)]">${formattedQuestion}</p>
                    <div class="flex items-center flex-shrink-0 space-x-3 self-end sm:self-center">
                        <span class="text-gray-500 text-sm">No</span>
                        <label class="toggle-label">
                            <input type="checkbox" name="${item.id}" class="toggle-switch">
                            <span class="toggle-slider"></span>
                        </label>
                        <span class="font-bold text-[var(--color-primary)] text-sm">Sí</span>
                    </div>
                </div>
            `;
        }).join('');
    }

    function updateProgressAndTasks() {
        const totalQuestions = checklistData.length;
        const yesAnswers = document.querySelectorAll('input.toggle-switch:checked').length;
        const percentage = totalQuestions > 0 ? Math.round((yesAnswers / totalQuestions) * 100) : 0;
        
        progressBar.style.width = `${percentage}%`;
        scoreDisplay.textContent = `${percentage}%`;

        const pendingItems = checklistData.filter(item => !document.querySelector(`input[name="${item.id}"]`).checked);

        if (pendingItems.length > 0) {
            taskList.innerHTML = pendingItems.map(item => `
                <div class="bg-gray-50 p-4 rounded-lg shadow-sm border-l-4 border-[var(--color-secondary)] flex items-start space-x-4">
                    <div class="flex-shrink-0 pt-1"><i data-lucide="alert-triangle" class="text-[var(--color-secondary)] w-5 h-5"></i></div>
                    <div class="flex-grow">
                        <span class="text-xs font-bold uppercase text-[var(--color-secondary)] tracking-wider">${item.category}</span>
                        <p class="text-gray-700 font-medium mt-1">${item.recommendation}</p>
                    </div>
                </div>
            `).join('');
        } else {
            taskList.innerHTML = `
                <div class="bg-green-100 p-4 rounded-lg border-l-4 border-green-500 flex items-center space-x-4">
                    <i data-lucide="award" class="text-green-600 w-6 h-6"></i>
                    <div>
                        <h4 class="font-bold text-green-800">¡Felicidades! Tu perfil está optimizado.</h4>
                        <p class="text-green-700">Has cubierto todos los puntos clave. ¡Sigue así!</p>
                    </div>
                </div>
            `;
        }
        lucide.createIcons();

        if (percentage < 100) {
            getAiAdviceBtn.disabled = false;
            getAiAdviceBtn.classList.remove('opacity-50', 'cursor-not-allowed');
        } else {
            getAiAdviceBtn.disabled = true;
            getAiAdviceBtn.classList.add('opacity-50', 'cursor-not-allowed');
        }
    }
    
    function setProcessingState(isProcessing) {
        const btnText = document.getElementById('btn-text');
        const loaderContainer = document.getElementById('loader-container');
        
        if (isProcessing) {
            loaderContainer.innerHTML = '<div class="w-6 h-6 border-4 border-t-transparent border-[var(--color-primary)] rounded-full animate-spin"></div>';
            loaderContainer.classList.remove('hidden');
            getAiAdviceBtn.disabled = true;
            getAiAdviceBtn.classList.add('opacity-50', 'cursor-not-allowed');
            aiResponseContainer.classList.add('hidden');
            aiResponseContent.innerHTML = '';
            
            const messages = ["Analizando tu perfil...", "Identificando oportunidades de SEO Local...", "Creando tu plan de acción...", "Optimizando estrategia..."];
            let messageIndex = 0;
            btnText.textContent = messages[messageIndex];
            
            window.loadingInterval = setInterval(() => {
                messageIndex = (messageIndex + 1) % messages.length;
                btnText.textContent = messages[messageIndex];
            }, 2500);

        } else {
            if (window.loadingInterval) clearInterval(window.loadingInterval);
            loaderContainer.classList.add('hidden');
            btnText.textContent = 'Generar Mi Estrategia';
            updateProgressAndTasks();
        }
    }
    
    function parseAndFormatAIResponse(rawText) {
        const blocks = rawText.split('---COMIENZO DEL PUNTO---').filter(b => b.trim() !== '');
        let html = '';
        const headerAndIntro = blocks.shift().split('\n');
        const mainTitle = headerAndIntro.shift() || '';
        const introText = headerAndIntro.join(' ').trim();
        if (mainTitle) html += `<h1 class="ai-main-title">${mainTitle}</h1>`;
        if (introText) html += `<p class="ai-intro-text">${introText}</p>`;
        blocks.forEach(block => {
            const titleMatch = block.match(/TÍTULO:(.*)/);
            const whyMatch = block.match(/PORQUÉ:(.*)/);
            const stepsMatch = block.match(/PASOS:([\s\S]*)/);
            const title = titleMatch ? titleMatch[1].trim() : 'Acción recomendada';
            const why = whyMatch ? whyMatch[1].trim() : 'No se proporcionó una razón.';
            const stepsText = stepsMatch ? stepsMatch[1].trim() : '';
            const steps = stepsText.split('*').map(s => s.trim()).filter(s => s);
            html += `
                <div class="ai-action-card">
                    <h3 class="ai-action-title"><i data-lucide="clipboard-check"></i>${title}</h3>
                    <p class="ai-action-why"><strong>Por qué es importante:</strong> ${why}</p>
                    <div>
                        <h4 class="ai-action-steps-title">Pasos para implementarlo:</h4>
                        <ul class="ai-action-steps">
                            ${steps.map(step => `<li><i data-lucide="arrow-right-circle"></i><span>${step}</span></li>`).join('')}
                        </ul>
                    </div>
                </div>`;
        });
        return html;
    }

    async function getAIAdvice() {
        const pendingTasks = checklistData
            .filter(item => !document.querySelector(`input[name="${item.id}"]`).checked)
            .map(item => `- **${item.category}:** ${item.recommendation}`);

        if (pendingTasks.length === 0) return;

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

        try {
            const payload = { pending_tasks: pendingTasks };
            
            const response = await fetch('api/api-optimizador-perfil-google-business.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (!response.ok) {
                // Aquí capturamos el error 502 y otros errores de red.
                const errorText = await response.text(); // Intentamos leer el cuerpo del error si lo hay.
                console.error('Error de red o servidor:', response.status, response.statusText, errorText);
                throw new Error(`No se pudo obtener una respuesta válida del servicio de IA. Inténtalo de nuevo.`);
            }

            const data = await response.json();
            
            if (data.error) {
                throw new Error(data.error);
            }
            if (data.generated_content) {
                const formattedHtml = parseAndFormatAIResponse(data.generated_content);
                aiResponseContent.innerHTML = formattedHtml;
                lucide.createIcons();
            } else {
                throw new Error("La respuesta de la IA no tuvo el formato esperado.");
            }

        } catch (error) {
            console.error("Error del Asistente IA (GBP):", 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 || 'Revisa la consola para más detalles.'}</p></div>`;
        } finally {
            setProcessingState(false);
            aiResponseContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }

    renderChecklist();
    updateProgressAndTasks();

    checklistContainer.addEventListener('input', (e) => {
        if (e.target.classList.contains('toggle-switch')) {
            updateProgressAndTasks();
        }
    });
    getAiAdviceBtn.addEventListener('click', getAIAdvice);
});
</script>
</body>
</html>