<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simulación de Chat WhatsApp</title>
    <!-- Carga de Tailwind CSS para utilidades generales -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
    <style>
        /* General body styles */
        body {
            font-family: 'Inter', sans-serif;
            background-color: #e0e0e0; /* Light gray background */
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            overflow: hidden; /* Prevent body scroll */
        }

        /* Main chat container, now full screen */
        .chat-container {
            background-color: #f0f0f0; /* Chat background */
            width: 100vw; /* Occupy 100% of viewport width */
            height: 100vh; /* Occupy 100% of viewport height */
            display: flex;
            flex-direction: column;
            border-radius: 0; /* Remove rounded borders for full screen */
            box-shadow: none; /* Remove shadow for full screen */
            overflow: hidden; /* Ensure content does not overflow */
            position: relative; /* For positioning internal elements */
        }

        /* Chat header style */
        .header {
            background-color: #075e54; /* WhatsApp green color */
            color: white;
            padding: 1rem;
            display: flex;
            align-items: center;
            gap: 0.75rem; /* Space between elements */
            border-top-left-radius: 0; /* Remove rounded borders */
            border-top-right-radius: 0; /* Remove rounded borders */
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            z-index: 10; /* Ensure it is above the chatbox */
        }

        .header img {
            width: 3rem; /* Profile image size */
            height: 3rem;
            border-radius: 50%; /* Circular */
            object-fit: cover;
            border: 2px solid white; /* White border around the image */
        }

        .header strong {
            font-size: 1.125rem; /* Larger text for name */
            font-weight: 600;
        }

        .status {
            font-size: 0.875rem; /* Smaller text for status */
            color: rgba(255, 255, 255, 0.8);
        }

        /* Chat message container */
        #chatbox {
            flex-grow: 1; /* Occupy all available space */
            padding: 1rem;
            overflow-y: auto; /* Allow message scrolling */
            /* Simulated chat background, you can replace it with a real WhatsApp background image */
            background-image: url('https://placehold.co/400x800/E0E0E0/FFFFFF?text=Fondo+Chat');
            background-size: cover;
            background-position: center;
            display: flex;
            flex-direction: column;
            gap: 0.5rem; /* Space between chat bubbles */
        }

        /* Chat bubble style */
        .chat {
            background-color: #DCF8C6; /* Light green for incoming messages */
            padding: 0.6rem 0.8rem;
            border-radius: 0.5rem; /* Rounded borders */
            max-width: 85%; /* Maximum bubble width */
            align-self: flex-start; /* Align messages to the left */
            word-wrap: break-word; /* Break long words */
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08); /* Subtle shadow */
            font-size: 0.95rem;
            line-height: 1.3;
        }

        /* "Typing..." indicator style */
        #typing {
            background-color: #fff; /* White background */
            padding: 0.6rem 0.8rem;
            border-radius: 0.5rem;
            max-width: fit-content;
            align-self: flex-start; /* Align to the left like a normal message */
            margin-top: 0.5rem;
            margin-bottom: 0.5rem;
            color: #666;
            font-style: italic;
            font-size: 0.85rem; /* Slightly smaller than normal text */
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);
            display: none; /* Hidden by default */
        }

        /* Style for images inside bubbles */
        .chat img {
            border-radius: 0.5rem;
            max-width: 100%; /* Ensure image does not overflow */
            height: auto;
            margin-top: 0.5rem; /* Top space for the image */
            cursor: pointer; /* Indicates it's clickable */
        }

        /* Container for buttons, now inside a chat bubble if necessary */
        .button-box {
            display: flex;
            flex-direction: column; /* Stacked buttons */
            gap: 0.75rem; /* Space between buttons */
            /* These styles are now handled by the chat bubble containing them */
            padding: 0;
            background-color: transparent;
            border-bottom-left-radius: 0;
            border-bottom-right-radius: 0;
        }

        .button {
            padding: 0.75rem 1rem;
            border-radius: 0.75rem; /* More rounded borders */
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease;
            text-align: center;
            border: none;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .button:hover {
            transform: translateY(-2px); /* Hover effect */
        }

        .whatsapp {
            background-color: #25D366; /* WhatsApp green */
            color: white;
        }

        .whatsapp:hover {
            background-color: #1DA851;
        }

        .facebook {
            background-color: #1877F2; /* Facebook blue */
            color: white;
        }

        .facebook:hover {
            background-color: #145CB3;
        }

        /* Style for audio elements, to look like a chat bubble */
        .audio-message {
            background-color: #DCF8C6; /* Same green as chat bubbles */
            padding: 0.6rem 0.8rem;
            border-radius: 0.5rem;
            max-width: 85%;
            align-self: flex-start;
            word-wrap: break-word;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);
            font-size: 0.95rem;
            line-height: 1.3;
            display: flex; /* For aligning audio controls */
            align-items: center;
            gap: 0.5rem;
        }

        /* Style for simulated audio */
        .audio-placeholder {
            background-color: #DCF8C6;
            padding: 0.6rem 0.8rem;
            border-radius: 0.5rem;
            max-width: fit-content; /* Adjusts to content */
            align-self: flex-start;
            word-wrap: break-word;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);
            font-size: 0.95rem;
            line-height: 1.3;
            color: #333;
            font-style: italic;
        }

        /* Media queries to ensure it's always full screen */
        @media (min-width: 601px) {
            .chat-container {
                max-width: 100vw;
                height: 100vh;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <!-- Chat header -->
        <div class="header">
            <img src="https://placehold.co/50x50/075E54/FFFFFF?text=N" alt="Nestor" onerror="this.onerror=null;this.src='https://placehold.co/50x50/075E54/FFFFFF?text=N';" />
            <div>
                <strong id="header-title">Nestor | OrozDesign</strong><br /> <!-- Added ID for dynamic update -->
                <span class="status">en línea</span>
            </div>
        </div>

        <!-- Chat messages container -->
        <div id="chatbox"></div>
        <!-- "Typing..." indicator -->
        <div id="typing" class="typing" style="display: none;">Escribiendo...</div>
    </div>

    <!-- JavaScript for chat logic -->
    <script>
        console.log("Chat simulation script loaded and running.");

        const chatbox = document.getElementById("chatbox");
        const typing = document.getElementById("typing");
        const headerTitle = document.getElementById("header-title"); // Reference to the header title

        // Function to get URL parameters
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            const results = regex.exec(location.search);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }

        // Get keyword from URL (e.g., ?keyword=diseño+grafico)
        const userSearchKeyword = getUrlParameter('keyword') || getUrlParameter('q') || ''; // You can use 'q' or 'keyword'
        // Get state/region from URL (e.g., ?state=Washington)
        const userState = getUrlParameter('state') || '';

        let dynamicHeaderSuffix = '';

        if (userSearchKeyword) {
            // Capitalize the first letter of each word for the header
            dynamicHeaderSuffix = userSearchKeyword.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
            headerTitle.textContent = `Nestor | ${dynamicHeaderSuffix}`;
        } else if (userState) {
            // If no keyword, but there is a state, use the state in the header
            dynamicHeaderSuffix = userState.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
            headerTitle.textContent = `Nestor | OrozDesign - ${dynamicHeaderSuffix}`;
        }


        // Definition of the main conversation
        // The {keyword} placeholder will be dynamically replaced
        const conversationSteps = [
            { type: 'message', content: `¡Hola! 👋 ¿Sabías que la primera impresión de tu negocio es crucial? Especialmente cuando buscan sobre ${userSearchKeyword || 'tu área de interés'}${userState ? ` en ${userState}` : ''}.`, delay: 2000 },
            { type: 'message', content: "Muchos clientes deciden confiar en ti solo por cómo se ve tu marca.", delay: 3000 },
            { type: 'message', content: "Por eso, en OrozDesign, creamos logotipos profesionales que realmente conectan con tu público. ✨", delay: 3500 },
            { type: 'message', content: "Imagina tener un logo que transmita confianza y profesionalismo desde el primer vistazo.", delay: 3000 },
            { type: 'message', content: "Con nuestro paquete, obtienes:", delay: 2000 },
            { type: 'message', content: "✅ Diseño de logotipo impactante", delay: 1500 },
            { type: 'message', content: "✅ 1,000 tarjetas de presentación listas para imprimir", delay: 1500 },
            { type: 'message', content: "✅ Archivos editables para usar donde quieras", delay: 1500 },
            { type: 'message', content: "Mira algunos ejemplos de logos que hemos diseñado para negocios como el tuyo:", delay: 3000 },
            { type: 'image', src: 'https://placehold.co/300x200/FF0000/FFFFFF?text=Logo+Ejemplo+1', alt: '', delay: 2500 },
            { type: 'image', src: 'https://placehold.co/300x200/00FF00/FFFFFF?text=Logo+Ejemplo+2', alt: '', delay: 2500 },
            { type: 'image', src: 'https://placehold.co/300x200/0000FF/FFFFFF?text=Logo+Ejemplo+3', alt: '', delay: 2500 },
            // Personal reflection question
            { type: 'message', content: "¿Qué imagen quieres proyectar con tu marca? 🤔 Piénsalo, tu logo es la primera conversación.", delay: 3500 },
            { type: 'message', content: "¿Te gustaría saber cómo un logo así puede transformar tu negocio y cuál es la inversión?", delay: 3000 },
            {
                type: 'clickable-image', // New type for clickable image
                src: 'https://placehold.co/300x200/FFA500/FFFFFF?text=Descubre+el+Precio',
                alt: '',
                delay: 2000,
                action: 'triggerPriceRevealSequence' // Calls the new price reveal sequence
            }
        ];

        // New sequence to reveal price and audio confirmation
        const priceRevealSequence = [
            { type: 'message', content: "¡Excelente! Aquí te detallo la inversión para que tu negocio destaque:", delay: 2000 }, // New message before price
            { type: 'message', content: "<s>Precio regular: $350 USD</s>", isHTML: true, delay: 2000 },
            { type: 'message', content: "<strong>🔥 HOY: $250 USD – ¡Sin mensualidades!</strong>", isHTML: true, delay: 2500 },
            { type: 'audio-simulated', delay: 3000, audioSrc: "https://www.w3schools.com/html/horse.mp3", audioDuration: 10000 }, // Audio simulation
            // Message that appears AFTER audio and BEFORE clickable image
            { type: 'message', content: "Escucha el audio primero y toca la imagen si has comprendido... 👇", delay: 2000 },
            {
                type: 'clickable-image', // This will be the new interaction
                // You can use a real GIF here if you have one, for example: 'your-animated-gif.gif'
                src: 'https://placehold.co/300x200/075e54/FFFFFF?text=Toca+para+continuar+GIF', // Placeholder image suggesting GIF
                alt: '',
                delay: 1000, // Shorter delay for this action prompt
                action: 'continueAfterAudioConfirmation' // New function to proceed
            },
            { type: 'message', content: "¿Listo para darle a tu negocio la imagen que se merece?", delay: 3000 },
            {
                type: 'buttons',
                delay: 2000,
                buttons: [
                    { className: 'whatsapp', html: '✅ Sí, quiero mi logotipo profesional', action: () => window.location.href='https://wa.me/14252434579?text=Hola Nestor, quiero un logotipo profesional para mi negocio' },
                    { className: 'facebook', html: '❌ No, prefiero seguir en Facebook', action: 'triggerLastChanceSequence' }
                ]
            }
        ];

        // "Last chance" sequence
        const lastChanceSteps = [
            { type: 'message', content: "😅 ¡Espera! No todos los días tienes esta oportunidad...", delay: 2000 },
            { type: 'message', content: `🤔 Tu negocio merece destacar en ${userSearchKeyword || 'tu sector'}${userState ? ` en ${userState}` : ''}. ¿Estás seguro de que quieres perder esto?`, delay: 2500 },
            { type: 'message', content: "🎯 ¡Haz la diferencia hoy mismo y asegura tu oferta!", delay: 2000 },
            { type: 'image', src: 'https://placehold.co/300x200/FF0000/FFFFFF?text=Ultima+Oportunidad', alt: '', delay: 2500 },
            { type: 'message', content: "<strong>😥 ¿Estás seguro que quieres salir?</strong>", isHTML: true, delay: 2000 },
            { type: 'message', content: "Esta oferta especial fue creada solo para ti.<br> Si sales ahora, podrías perderla para siempre.", isHTML: true, delay: 2500 },
            {
                type: 'buttons',
                delay: 2000,
                buttons: [
                    { className: 'whatsapp', html: '💬 Hablar con una persona', action: () => window.location.href='https://wa.me/14252434579?text=Hola, quiero hablar con alguien sobre la oferta del logotipo' },
                    { style: { backgroundColor: '#dc3545', color: 'white' }, html: '❌ Sí, volver a Facebook', action: () => window.location.href='https://facebook.com' }
                ]
            }
        ];

        let currentSequence = []; // Stores the current sequence of steps
        let currentStepIndex = 0; // Index of the current step in the sequence

        /**
         * Adds a text message to the chatbox.
         * @param {string} content - The message content (can be HTML).
         * @param {boolean} isHTML - Indicates if the content should be interpreted as HTML.
         */
        function agregarMensaje(content, isHTML = false) {
            const p = document.createElement("p");
            p.className = "chat"; // Apply chat bubble class
            // Replace the {keyword} placeholder with the actual keyword
            const finalContent = content.replace(/{keyword}/g, userSearchKeyword);
            if (isHTML) {
                p.innerHTML = finalContent;
            } else {
                p.textContent = finalContent;
            }
            chatbox.appendChild(p);
            // Scroll chatbox to the end to see the new message
            chatbox.scrollTop = chatbox.scrollHeight;
        }

        /**
         * Starts a sequence of messages or elements.
         * @param {Array<Object>} sequence - The sequence of steps to display.
         */
        function startSequence(sequence) {
            currentSequence = sequence;
            currentStepIndex = 0;
            mostrarElementosConRetraso();
        }

        // Global functions for button actions
        function triggerPriceRevealSequence() {
            startSequence(priceRevealSequence);
        }

        function triggerLastChanceSequence() {
            startSequence(lastChanceSteps);
        }

        function restartChat() {
            chatbox.innerHTML = ''; // Clear chatbox
            startSequence(conversationSteps); // Restart main conversation
        }

        /**
         * New function to continue the sequence after audio confirmation.
         * Simply advances to the next step in the current sequence.
         */
        function continueAfterAudioConfirmation() {
            currentStepIndex++; // Advance to the next step
            mostrarElementosConRetraso(); // Continue displaying the sequence
        }

        /**
         * Displays the elements of the current sequence with a delay, simulating typing.
         */
        function mostrarElementosConRetraso() {
            // If there are no more steps in the current sequence, hide the typing indicator and exit.
            if (currentStepIndex >= currentSequence.length) {
                typing.style.display = "none";
                return;
            }

            const elementoActual = currentSequence[currentStepIndex];
            // Use the element's specific delay or a default value of 3 seconds.
            const delay = elementoActual.delay || 3000;

            // Show "typing" indicator before processing the element
            typing.style.display = "block";
            chatbox.scrollTop = chatbox.scrollHeight; // Scroll to see the indicator

            // If the type is 'audio-simulated', handle "Recording Audio..." here
            if (elementoActual.type === 'audio-simulated') {
                typing.textContent = "Grabando Audio..."; // Change the indicator text
                // The setTimeout for audio will handle hiding the typing and advancing
                setTimeout(() => {
                    typing.style.display = "none"; // Hide the "Recording Audio..." indicator
                    typing.textContent = "Escribiendo..."; // Reset indicator text for next messages

                    const audioBubble = document.createElement("div");
                    audioBubble.className = "audio-message"; // Apply chat bubble styles
                    const audio = document.createElement("audio");
                    audio.controls = true; // Show audio controls
                    audio.autoplay = true; // Autoplay audio
                    audio.src = elementoActual.audioSrc;
                    // Error handling for audio
                    audio.onerror = function() {
                        console.error("Error loading audio:", this.src);
                        const errorMsg = document.createElement("span");
                        errorMsg.textContent = " (Error al cargar el audio)";
                        errorMsg.style.color = "red";
                        audioBubble.appendChild(errorMsg);
                    };
                    audioBubble.appendChild(audio);
                    chatbox.appendChild(audioBubble);
                    chatbox.scrollTop = chatbox.scrollHeight;

                    // After displaying the audio, advance to the next step (the "listen to audio..." message)
                    currentStepIndex++;
                    mostrarElementosConRetraso(); // Call the function to process the next step immediately
                }, delay); // Use the element's delay for the "recording" simulation
                return; // Important: This return stops the main loop progression
                        // until the internal setTimeout has completed and called `mostrarElementosConRetraso` again.
            }

            // For all other types (message, image, clickable-image, buttons)
            setTimeout(() => {
                typing.style.display = "none"; // Hide the generic "Typing..." indicator

                if (elementoActual.type === 'message') {
                    agregarMensaje(elementoActual.content, elementoActual.isHTML);
                } else if (elementoActual.type === 'image') {
                    const imgBubble = document.createElement('p');
                    imgBubble.className = 'chat';
                    const img = document.createElement('img');
                    img.src = elementoActual.src;
                    img.alt = elementoActual.alt;
                    img.onerror = function() { this.onerror=null; this.src='https://placehold.co/300x200/FF0000/FFFFFF?text=Error+Carga'; };
                    imgBubble.appendChild(img);
                    chatbox.appendChild(imgBubble);
                    chatbox.scrollTop = chatbox.scrollHeight;
                } else if (elementoActual.type === 'clickable-image') {
                    const imgBubble = document.createElement('p');
                    imgBubble.className = 'chat';
                    const img = document.createElement('img');
                    img.src = elementoActual.src;
                    img.alt = elementoActual.alt;
                    img.style.cursor = "pointer";
                    img.onerror = function() { this.onerror=null; this.src='https://placehold.co/300x200/FFA500/FFFFFF?text=Error+Carga'; };
                    img.onclick = window[elementoActual.action];
                    imgBubble.appendChild(img);
                    chatbox.appendChild(imgBubble);
                    chatbox.scrollTop = chatbox.scrollHeight;
                    return; // Stop automatic progression until the user clicks
                } else if (elementoActual.type === 'buttons') {
                    const buttonsBubble = document.createElement('p');
                    buttonsBubble.className = 'chat';
                    buttonsBubble.style.padding = '0';
                    buttonsBubble.style.backgroundColor = 'transparent';
                    buttonsBubble.style.boxShadow = 'none';
                    buttonsBubble.style.alignSelf = 'flex-start';

                    const btnBox = document.createElement("div");
                    btnBox.className = "button-box w-full";
                    btnBox.style.padding = '0';
                    btnBox.style.backgroundColor = 'transparent';

                    buttonsBubble.appendChild(btnBox);
                    chatbox.appendChild(buttonsBubble);
                    chatbox.scrollTop = chatbox.scrollHeight;

                    const totalButtons = elementoActual.buttons.length;
                    let buttonsRendered = 0;

                    elementoActual.buttons.forEach((buttonData, index) => {
                        setTimeout(() => {
                            const button = document.createElement("button");
                            button.className = `button ${buttonData.className || ''}`;
                            if (buttonData.style) {
                                for (const prop in buttonData.style) {
                                    button.style[prop] = buttonData.style[prop];
                                }
                            }
                            button.innerHTML = buttonData.html;
                            if (typeof buttonData.action === 'string') {
                                if (buttonData.action.startsWith('window.location.href')) {
                                    button.onclick = () => eval(buttonData.action);
                                } else {
                                    button.onclick = window[buttonData.action];
                                }
                            } else if (typeof buttonData.action === 'function') {
                                button.onclick = buttonData.action;
                            }
                            btnBox.appendChild(button);
                            chatbox.scrollTop = chatbox.scrollHeight;

                            buttonsRendered++;
                            if (buttonsRendered === totalButtons) {
                                currentStepIndex++;
                                mostrarElementosConRetraso();
                            }
                        }, index * 2000);
                    });
                    return;
                }

                // If the element is not 'audio-simulated' or 'buttons' or 'clickable-image', proceed to the next step
                currentStepIndex++;
                mostrarElementosConRetraso();
            }, delay); // Delay for the current element
        }

        // Start conversation when DOM is fully loaded
        document.addEventListener("DOMContentLoaded", function () {
            chatbox.innerHTML = ''; // Clear chatbox once on page load
            startSequence(conversationSteps); // Start main conversation sequence
        });
    </script>
</body>
</html>
