<?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>Mini Test De Diagnóstico Publicitario Con IAMarketing™ Powered By OrozCO</title>
    <meta name="description" content="Un Diagnóstico Rápido Para Descubre Dónde Estás Y Qué Mejorar">
    <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>
        .step-header h2 {
            flex-direction: column;
            align-items: flex-start;
            text-align: left;
        }
        .step-header .step-number {
            font-size: 1.25rem;
            font-weight: 900;
            margin-right: 0;
            margin-bottom: 0.25rem;
            display: flex;
            align-items: center;
            color: var(--color-secondary);
            flex-shrink: 0;
        }
        .step-header .step-number i {
            margin-right: 0.5rem;
            font-size: 1.5rem;
        }
        .step-header .step-title {
            font-size: 1.4rem;
            font-weight: 900;
            color: #1e293b;
            line-height: 1.2;
            text-transform: uppercase;
            text-align: left;
            width: 100%;
        }
        @media (min-width: 768px) {
            .step-header h2 {
                flex-direction: row;
                align-items: center;
                justify-content: flex-start;
                text-align: left;
            }
            .step-header .step-number {
                font-size: 1.5rem;
                margin-right: 0.5rem;
                margin-bottom: 0;
            }
            .step-header .step-number i {
                font-size: 1.8rem;
            }
            .step-header .step-title {
                font-size: 1.5rem;
                width: auto;
            }
        }
        .diagnostic-card {
            background-color: white;
            padding: 1.5rem;
            border-radius: 0.75rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            cursor: pointer;
            transition: all 0.2s ease-in-out;
            border: 2px solid transparent;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            height: 100%;
        }
        .diagnostic-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px rgba(0, 0, 0, 0.15);
        }
        .diagnostic-card.selected {
            background-color: var(--color-secondary);
            color: white;
            border-color: var(--color-highlight);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
            transform: scale(1.02);
        }
        .diagnostic-card.selected .card-title,
        .diagnostic-card.selected .card-desc {
            color: white;
        }
        .diagnostic-card .card-icon {
            width: 3rem;
            height: 3rem;
            color: var(--color-secondary);
            transition: color 0.2s ease-in-out;
        }
        .diagnostic-card.selected .card-icon {
            color: var(--color-highlight);
        }
        .diagnostic-card .card-title {
            font-size: 1.25rem;
            font-weight: 700;
            color: #1e293b;
            line-height: 1.2;
            transition: color 0.2s ease-in-out;
        }
        .diagnostic-card .card-desc {
            font-size: 1rem;
            color: #4b5563;
            transition: color 0.2s ease-in-out;
        }
        .action-plan-list .action-plan-item {
            display: flex;
            align-items: flex-start;
            gap: 1rem;
        }
        .action-plan-list .icon-container {
            flex-shrink: 0;
            width: 2.5rem;
            height: 2.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: var(--color-secondary);
            color: white;
            border-radius: 50%;
            font-weight: bold;
        }
        .action-plan-list .icon-container i {
            width: 1.5rem;
            height: 1.5rem;
        }
    </style>
</head>

<body data-page-title="Mini Test De Diagnóstico Publicitario"
      data-page-subtitle="Un Diagnóstico Rápido Para Descubre Dónde Estás Y Qué Mejorar"
      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="diagnostic-test" class="dashboard-section">
                    <div class="grid grid-cols-1 lg:grid-cols-5 gap-8">
                        <div class="lg:col-span-3">
                            <form id="diagnostic-form" class="space-y-8 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="scan-search" class="mr-3 text-[var(--color-secondary)]"></i> PASO 1:
                                        </span>
                                        <span class="step-title"> Analiza Tu Situación Actual
                                        </span>
                                    </h2>
                                    <p class="step-subtitle uppercase">Marca las opciones que reflejan tu realidad para un diagnóstico preciso.</p>
                                </div>
                                <div class="border-b border-gray-200 pb-4 mb-6"></div>

                                <div class="space-y-8">
                                    <p class="text-center max-w-3xl mx-auto text-gray-700 text-lg">SELECCIONA TODAS LAS SITUACIONES QUE SE PAREZCAN A TU NEGOCIO ACTUALMENTE</p>
                                    <div class="grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-8" id="diagnostic-options">
                                        </div>
                                    <div class="mt-6">
                                        <label for="diag-other" class="block font-bold capitalize text-gray-700 mb-2 text-lg">Otro:</label>
                                        <input id="diag-other" name="otro" type="text" placeholder="Describe Brevemente Otra Situación..." class="w-full mt-2 p-3 bg-gray-50 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-highlight)]">
                                    </div>
                                </div>
                            </form>
                        </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-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="list-checks"></i></span>
            <div>
                <strong class="text-brand-dark uppercase">SÉ HONESTO EN TU EVALUACIÓN:</strong> La herramienta genera un diagnóstico preciso basado en la realidad de tu negocio.
            </div>
        </li>
        <li class="instructions-list-item">
            <span class="icon-wrapper"><i data-lucide="lightbulb"></i></span>
            <div>
                <strong class="text-brand-dark uppercase">OBTÉN CLARIDAD INMEDIATA:</strong> Al finalizar, la herramienta te mostrará una puntuación y un diagnóstico de tus áreas de oportunidad.
            </div>
        </li>
        <li class="instructions-list-item">
            <span class="icon-wrapper"><i data-lucide="rocket"></i></span>
            <div>
                <strong class="text-brand-dark uppercase">RECIBE UN PLAN DE ACCIÓN:</strong> El resultado es un plan paso a paso. Usa estas indicaciones para empezar a crecer.
            </div>
        </li>
        <li class="instructions-list-item">
            <span class="icon-wrapper"><i data-lucide="repeat"></i></span>
            <div>
                <strong class="text-brand-dark uppercase">MIDE TU PROGRESO:</strong> Implementa los pasos sugeridos. Te recomendamos volver a realizar este test en 1-2 meses.
            </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="brain" class="mr-3 text-[var(--color-secondary)]"></i> PASO 2:
                                    </span>
                                    <span class="step-title"> Obtén Tu Diagnóstico Estratégico
                                    </span>
                                </h2>
                                <p class="step-subtitle uppercase">Genera una evaluación de tu situación y un plan de acción.</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 obtener un análisis preciso, <strong>es importante</strong> que respondas a las preguntas con honestidad. Basado en tus respuestas, nuestra Inteligencia Artificial <strong>IA Marketing</strong> generará un <strong>Diagnóstico Rápido Y Estratégico</strong>, para que descubras tus áreas de oportunidad y sepas exactamente qué mejorar</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="diagnostic-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 id="result-container" class="lg:col-span-5 mt-8"></div>
                    </div>
                </section>
            </div>
        </main>
    </div>
    
<script type="module">
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
    
    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');
    });

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

    if (notificationType && notificationMessage && typeof showToast === 'function') {
        showToast(notificationMessage, notificationType);
    }
    
    const playOverlay = document.getElementById('playOverlay');
    const videoPlayer = document.getElementById('videoPlayer');
    
    if(playOverlay && videoPlayer) {
        playOverlay.addEventListener('click', () => {
            playOverlay.style.display = 'none';
            videoPlayer.play();
        });
    }
    
    const phoneInput = document.getElementById('contact_phone');
    if (phoneInput) {
        IMask(phoneInput, { mask: '(000) 000-0000' });
    }
    
    const optionsContainer = document.getElementById('diagnostic-options');
    const diagnosticPoints = [
        { id: 'diag-1', label: 'Dependo Únicamente De Recomendaciones', desc: 'Mis clientes llegan solo si alguien habla de mí. Si no, no tengo nuevos clientes.', icon: 'users' },
        { id: 'diag-2', label: 'Publico En Redes, Pero No Veo Resultados', desc: 'Subo contenido, pero nadie comenta ni me contacta. Me siento invisible.', icon: 'camera' },
        { id: 'diag-3', label: 'He Hecho Anuncios, Pero No Sé Si Funcionan', desc: 'He gastado dinero, pero no entiendo si es una inversión o solo un gasto.', icon: 'wallet' },
        { id: 'diag-4', label: 'No Estoy Haciendo Nada Para Atraer Clientes', desc: 'No tengo una estrategia activa, solo espero que los clientes lleguen solos.', icon: 'target' },
        { id: 'diag-5', label: 'Pago A Alguien, Pero No Veo Resultados', desc: 'He contratado ayuda, pero no tengo claridad sobre lo que hacen ni veo más clientes.', icon: 'user-x' },
        { id: 'diag-6', label: 'Veo Videos En YouTube, Pero Me Confundo', desc: 'Busco información, pero todo es confuso, técnico o se contradice.', icon: 'youtube' },
        { id: 'diag-7', label: 'Compro Leads, Pero Muchos No Me Contratan', desc: 'Pago por contactos, pero pocos responden o se interesan realmente en mi servicio.', icon: 'database' },
        { id: 'diag-8', label: 'Quiero Aprender A Crecer Por Mi Cuenta', desc: 'No quiero depender más de otros para conseguir clientes para mi negocio.', icon: 'graduation-cap' }
    ];

    diagnosticPoints.forEach(point => {
        const card = document.createElement('div');
        card.className = 'diagnostic-card';
        card.dataset.id = point.id;
        card.innerHTML = `
            <i data-lucide="${point.icon}" class="card-icon"></i>
            <div class="flex-1">
                <p class="card-title">${point.label}</p>
                <p class="card-desc">${point.desc}</p>
            </div>
            <input type="checkbox" name="${point.label}" id="${point.id}" class="hidden">
        `;
        optionsContainer.appendChild(card);
    });
    
    lucide.createIcons();

    const cards = document.querySelectorAll('.diagnostic-card');
    cards.forEach(card => {
        card.addEventListener('click', () => {
            card.classList.toggle('selected');
            const checkbox = card.querySelector('input[type="checkbox"]');
            checkbox.checked = !checkbox.checked;
        });
    });

    const form = document.getElementById('diagnostic-form');
    const generateBtn = document.getElementById('generateBtn');
    const btnText = document.getElementById('btn-text');
    const loaderContainer = document.getElementById('loader-container');
    const resultContainer = document.getElementById('result-container');

    function setProcessingState(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>';
            loaderContainer.classList.remove('hidden');
            generateBtn.disabled = true;
            generateBtn.classList.add('opacity-50', 'cursor-not-allowed');
            resultContainer.innerHTML = '';
            resultContainer.style.opacity = '0';
            const messages = ["Analizando tus respuestas...", "Generando diagnóstico...", "Creando un plan de acción...", "Casi está listo..."];
            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');
            generateBtn.disabled = false;
            generateBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            btnText.textContent = 'Generar Otro Diagnóstico';
        }
    }

    form.addEventListener('submit', async function(event) {
        event.preventDefault();
        
        const selectedOptions = [];
        form.querySelectorAll('input[type=checkbox]:checked').forEach(checkbox => {
            selectedOptions.push(checkbox.name);
        });

        const otherInput = document.getElementById('diag-other').value;
        if (otherInput.trim()) {
            selectedOptions.push(`Otro: ${otherInput}`);
        }

        if (selectedOptions.length === 0) {
            showToast('Por favor, selecciona al menos una opción para continuar.', 'warning');
            return;
        }

        setProcessingState(true);

        try {
            const response = await fetch('api/api-mini-test-de-diagnostico.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ situations: selectedOptions })
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || `Error del servidor: ${response.status}.`);
            }
            const data = await response.json();
            if(data.error) throw new Error(data.error);

            displayResult(data);
            showToast('¡Diagnóstico generado con éxito!', 'success');

        } catch (error) {
            console.error("Error:", error);
            let errorMessage = 'Hubo un problema al generar tu diagnóstico. Por favor, intenta de nuevo.';
            try {
                const errorDetails = JSON.parse(error.message.substring(error.message.indexOf('{')));
                if (errorDetails.error) {
                    errorMessage = errorDetails.error;
                }
            } catch (e) { /* ignore */ }
            
            resultContainer.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><p><strong>Error:</strong> ${errorMessage}</p></div>`;
            resultContainer.style.opacity = '1';
            showToast(errorMessage, 'error');
        } finally {
            setProcessingState(false);
        }
    });

    function displayResult(data) {
        const resultContainer = document.getElementById('result-container');
        const planDeAccionHtml = data.plan_de_accion.map((step, index) => `
            <li class="action-plan-item">
                <span class="icon-container">${index + 1}</span>
                <p class="text-gray-800 text-lg leading-relaxed">${step.replace(/\*\*(.*?)\*\*/g, '<strong class="text-gray-800">$1</strong>')}</p>
            </li>
        `).join('');

        resultContainer.innerHTML = `
            <div class="ai-response p-6 md:p-8 rounded-xl shadow-md space-y-8 animate-slideInUp">
                <div class="text-center">
                    <h2 class="text-2xl font-bold text-gray-800">Tu Puntuación De Preparación</h2>
                    <p class="text-7xl font-bold text-[var(--color-secondary)] mt-2">${data.puntuacion}/10</p>
                </div>
                
                <div class="border-t border-gray-200 pt-6">
                    <h3 class="text-2xl font-bold text-gray-800 flex items-center"><i data-lucide="file-text" class="mr-3 text-[var(--color-secondary)]"></i>Diagnóstico General</h3>
                    <p class="text-gray-700 mt-2 text-lg">${data.diagnostico_general}</p>
                </div>
                
                <div class="border-t border-gray-200 pt-6">
                    <h3 class="text-2xl font-bold text-gray-800 flex items-center"><i data-lucide="rocket" class="mr-3 text-[var(--color-highlight)]"></i>Tu Plan De Acción Personalizado</h3>
                    <ul class="action-plan-list mt-6 space-y-6">
                        ${planDeAccionHtml}
                    </ul>
                </div>
            </div>
        `;
        lucide.createIcons();
        setTimeout(() => { 
            resultContainer.style.opacity = '1'; 
            resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }, 100);
    }
});
</script>
</body>
</html>