<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Template Name: Demo Dashboard
 * Description: Gamified demo dashboard with AI coaching
 * Version: 2.4
 */
$plugin_url = defined( 'AVISION_PLUGIN_URL' ) ? AVISION_PLUGIN_URL : '/wordpress/wp-content/plugins/avision-dashboard/';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Demo - Avision</title>
    <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=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo $plugin_url; ?>assets/css/demo-dashboard.css">
</head>
<body>
<div id="avision-dashboard-root">

    <div class="social-proof-ticker">
        <span data-i18n="social_proof">🔥 14 companies optimized their Google Business Profile this week. Latest: <strong>Smith Corp (Score: 80/100)</strong></span>
    </div>

    <nav class="top-nav">
        <div class="nav-left">
            <a href="<?php echo esc_url( function_exists( 'home_url' ) ? home_url( '/' ) : '/' ); ?>" class="logo logo-avision-img"><img src="https://avision.org/wp-content/uploads/2026/03/avision-logo-png-70x70-1.png" alt="Avision" class="avision-header-logo-img" width="70" height="70" /></a>
        </div>
        <div class="nav-right">
            <div class="header-flags">
                <img src="https://flagcdn.com/w40/us.png" alt="English" class="header-flag active" data-lang="en" onclick="AvisionDemo.updateLanguage('en')">
                <img src="https://flagcdn.com/w40/fr.png" alt="French" class="header-flag" data-lang="fr" onclick="AvisionDemo.updateLanguage('fr')">
                <img src="https://flagcdn.com/w40/es.png" alt="Spanish" class="header-flag" data-lang="es" onclick="AvisionDemo.updateLanguage('es')">
            </div>
        </div>
    </nav>

    <div class="opportunity-banner" data-i18n="opp_gap">
        CRITICAL: You are losing traffic to <span id="competitorDisplay">Your Competitor</span>
    </div>

    <header class="saas-header">
        <div class="header-content">
            <div class="certif-badge" data-i18n="certif_badge">🛡️ Google Maps Standards 2026</div>
            <div class="business-info">
                <h1 id="companyNameDisplay">Dashboard Demo</h1>
            </div>
            <div class="premium-badge" data-i18n="premium_badge">💎 Premium Partner</div>
        </div>
    </header>

    <div class="container">
        <div class="score-grid">
            <div class="score-card">
                <h4 data-i18n="score_title">Health Score</h4>
                <svg viewBox="0 0 100 100" class="circular-chart">
                    <circle class="circle-bg" cx="50" cy="50" r="45"></circle>
                    <circle class="circle" id="score-circle" cx="50" cy="50" r="45" 
                        style="stroke-dasharray: 283; stroke-dashoffset: 170; stroke: #ef4444; transform: rotate(-90deg); transform-origin: 50% 50%;"></circle>
                    <text x="50" y="50" class="percentage" id="score-text">42/100</text>
                    <text x="50" y="65" class="percentage" style="font-size:0.18em; fill:#ef4444;" id="score-status" data-i18n="score_status">Critical</text>
                </svg>
            </div>
            <div class="score-card">
                <h4 data-i18n="comp_title">Competitive Analysis</h4>
                <div class="stat-row">
                    <span class="stat-label" data-i18n="stat_pos">Your Real Position:</span>
                    <span class="stat-value bad" data-i18n="stat_pos_val">7th (Invisible)</span>
                </div>
                <div class="stat-row">
                    <span class="stat-label" data-i18n="stat_leader">Sector Leader:</span>
                    <span class="stat-value good"><span id="leaderName">Leader</span> <span data-i18n="leader_rank">(1st)</span></span>
                </div>
                <div class="stat-row">
                    <span class="stat-label" data-i18n="stat_potential">Growth Potential:</span>
                    <span class="stat-value good" data-i18n="stat_potential_val">+300% Calls & Directions</span>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="phase-header">
                <span class="unlock-icon">🔓</span>
                <div>
                    <div class="phase-title" data-i18n="phase_title">PHASE 1: CRITICAL ERROR REVEALED</div>
                    <div class="phase-subtitle" data-i18n="phase_subtitle">This was blocking 80% of your visibility.</div>
                </div>
            </div>
            <div class="ai-analysis-box">
                <strong data-i18n="ai_analysis_label">🤖 AI Analysis:</strong>
                <p data-i18n="ai_analysis_text">I filtered out erroneous listings. Here are the <strong>strategic categories</strong> used by REAL leaders:</p>
                <div class="tag-container">
                    <span class="tag" id="categoryTag">Category</span>
                    <span class="tag premium-blur">Secondary Category</span>
                    <span class="tag premium-blur">Tertiary Category</span>
                </div>
            </div>
            <div style="background:#fef2f2; border:1px dashed #fecaca; padding:15px; border-radius:8px; margin-bottom:25px; position:relative;">
                <div class="premium-blur">
                    <strong style="color:#dc2626;" data-i18n="blur_alert">3 Critical Keywords Detected (Hidden)</strong>
                    <p style="margin:5px 0 0 0; color:#9ca3af;">Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
                </div>
                <div class="lock-overlay">
                    <button class="lock-btn" onclick="AvisionDemo.openSales()"><span>🔒</span> <span data-i18n="btn_unlock">Unlock Analysis</span></button>
                </div>
            </div>

            <div class="level-card active" id="level-1">
                <div class="level-header" onclick="AvisionDemo.toggleLevel('level-1')">
                    <div style="display:flex; align-items:center;">
                        <span class="level-badge">LVL 1</span>
                        <span class="level-title" data-i18n="lvl1_title">1. Category Correction</span>
                    </div>
                    <div style="display:flex; align-items:center; gap:15px;">
                        <span style="color:#10b981; font-weight:700; font-size:1rem;">✓ Unlocked</span>
                        <span class="chevron rotate" id="chevron-level-1">▼</span>
                    </div>
                </div>
                <div class="accordion-wrapper open" id="level-1-content">
                    <div class="level-actions">
                        <p data-i18n="lvl1_desc">Set the following category as primary:</p>
                        <div class="tag" id="primaryCategoryTag" style="font-size:1.3rem; padding:12px 20px;">Loading...</div>
                        <div class="btn-group">
                            <a href="https://business.google.com/edit" target="_blank" class="btn-outline" data-i18n="btn_howto">💡 How to do it?</a>
                            <button class="btn-verify" id="btnVerify" onclick="AvisionDemo.fakeVerify(event)"><span class="btn-text" data-i18n="btn_verify">Verify Fix</span></button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div id="locked-levels-container"></div>
        
        <div style="position:relative; height:100px; margin-top:-50px;">
            <div class="iceberg-fade"></div>
            <div class="iceberg-text" data-i18n="iceberg_text">+ other hidden ranking criteria levels...</div>
        </div>

        <div class="testimonials-section">
            <h3 class="testi-title" data-i18n="testi_title">Latest Client Results</h3>
            <div class="testimonials-grid">
                <div class="testi-card">
                    <div class="testi-header"><div class="testi-avatar">🍕</div><div class="testi-name">Pizzeria Bella</div></div>
                    <div class="testi-text" data-i18n="testi_1">"I applied level 2. Result: +15 calls this weekend."</div>
                    <span class="testi-result">🚀 +15 Calls</span>
                </div>
                <div class="testi-card">
                    <div class="testi-header"><div class="testi-avatar">🔧</div><div class="testi-name">Garage Michel</div></div>
                    <div class="testi-text" data-i18n="testi_2">"My profile passed the dealership's. Agenda full."</div>
                    <span class="testi-result">📅 Full Calendar</span>
                </div>
                <div class="testi-card">
                    <div class="testi-header"><div class="testi-avatar">🦷</div><div class="testi-name">Dental Clinic H.</div></div>
                    <div class="testi-text" data-i18n="testi_3">"3 new patients per week thanks to unlocked keywords."</div>
                    <span class="testi-result">👩‍⚕️ +3 Patients/wk</span>
                </div>
            </div>
        </div>
    </div>

    <footer class="app-footer">
        <p>&copy; <span id="footerYear">2026</span> Avision. <span data-i18n="footer_rights">All rights reserved.</span></p>
    </footer>

    <div class="sales-modal-overlay" id="salesModal">
        <div class="sales-modal">
            <span class="close-sales" onclick="AvisionDemo.closeSales()">✕</span>
            <h2 data-i18n="modal_head">Activate your AVI Access — One-time $69</h2>
            <p style="color:#64748b;" data-i18n="modal_sub">Get your full audit, priority actions and AVI coach. No subscription, no recurring charge.</p>
            <div class="sales-timer" data-i18n="modal_timer_prefix">⚡ Launch price — regular price $99</div>
            <div class="sales-price"><span style="text-decoration:line-through; opacity:0.55;">$99</span> $69</div>
            <div class="sales-check-wrapper">
                <span>✅</span><span data-i18n="feat_1">✅ Full local visibility audit + GBP optimization report</span>
            </div>
            <div class="sales-check-wrapper">
                <span>✅</span><span data-i18n="feat_2">✅ AVI Intelligence chat — full access + Visibility score /100</span>
            </div>
            <div class="sales-check-wrapper">
                <span>✅</span><span data-i18n="feat_3">✅ AVI Academy — skill progression + Google Updates always up to date</span>
            </div>
            <label style="display:flex; gap:10px; margin:20px 0; cursor:pointer; font-size:0.95rem; color:#475569;">
                <input type="checkbox" id="confirmComp" onchange="AvisionDemo.toggleSalesBtn()">
                <span data-i18n="modal_check">I confirm I want to boost my local visibility on Google Maps.</span>
            </label>
            <button class="sales-cta" id="salesBtn" disabled onclick="if(window.AvisionStripeCheckoutUrl && window.AvisionStripeCheckoutUrl !== '') { window.location.href = window.AvisionStripeCheckoutUrl; } else { window.location.href = '/pricing/'; }" data-i18n="modal_cta">Get AVI Access — $69</button>
            <p style="margin-top:15px; font-size:0.85rem; color:#94a3b8;" data-i18n="modal_secure">🔒 Secure Stripe Payment</p>
        </div>
    </div>

    <div class="avi-chat-window" id="aviWindow">
        <div class="chat-header">
            <div style="font-weight:700;">Avi – AI Coach</div>
            <div style="cursor:pointer;" onclick="AvisionDemo.toggleChat()">✕</div>
        </div>
        <div class="chat-container">
            <div class="chat-messages" id="chatBody"></div>
            <div class="typing-indicator" id="typingIndicator">
                <div class="dot"></div><div class="dot"></div><div class="dot"></div>
            </div>
            <div class="chat-input-area">
                <input type="text" class="chat-input" id="chatInput" placeholder="Ask Avi..." onkeypress="AvisionDemo.handleEnter(event)">
                <button class="chat-send" onclick="AvisionDemo.sendMessage()">➤</button>
            </div>
        </div>
    </div>
    <div class="avi-widget-btn avi-widget-btn-image-only" id="avi-demo-widget-btn" onclick="AvisionDemo.toggleChat()" style="position:fixed;bottom:30px;right:30px;width:70px;height:70px;background:transparent;border:none;box-shadow:none;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:2000;">
        <div class="avi-badge" id="aviBadge">1</div>
        <img src="<?php echo esc_url( function_exists( 'avi_chat_icon_url' ) ? avi_chat_icon_url() : 'https://avision.org/wp-content/uploads/2026/03/avi-ss-fond-chat.png' ); ?>" alt="Avi" class="avi-chat-icon-img" width="65" height="65" style="display:block;width:65px;height:65px;object-fit:contain;margin:0;padding:0;pointer-events:none;" />
    </div>
</div>

<script>
var AvisionDemo = (function() {
    
    const translations = {
        'en': {
            'default_competitor_name': 'Your Competitor',
            'social_proof': '🔥 14 companies optimized their Google Business Profile this week. Latest: <strong>Smith Corp (Score: 80/100)</strong>',
            'opp_gap': 'CRITICAL: You are losing traffic to',
            'certif_badge': '🛡️ Google Maps Standards 2026',
            'premium_badge': '💎 Premium Partner',
            'score_title': 'Health Score',
            'score_status': 'Critical',
            'comp_title': 'Competitive Analysis',
            'stat_pos': 'Your Real Position:',
            'stat_pos_val': '7th (Invisible)',
            'stat_leader': 'Sector Leader:',
            'leader_rank': '(1st)',
            'stat_potential': 'Growth Potential:',
            'stat_potential_val': '+300% Calls & Directions',
            'phase_title': 'PHASE 1: CRITICAL ERROR REVEALED',
            'phase_subtitle': 'This was blocking 80% of your visibility.',
            'ai_analysis_label': '🤖 AI Analysis:',
            'ai_analysis_text': 'I filtered out erroneous listings. Here are the <strong>strategic categories</strong> used by REAL leaders:',
            'blur_alert': '3 Critical Keywords Detected (Hidden)',
            'btn_unlock': '🔓 Unlock Analysis',
            'lvl1_title': '1. Category Correction',
            'lvl1_desc': 'Set the following category as primary:',
            'btn_howto': '💡 How to do it?',
            'btn_verify': 'Verify Fix',
            'modal_head': 'Activate your 90-Day SEO Roadmap',
            'modal_sub': 'Get the precise action plan and automation tools to improve and secure your position.',
            'modal_timer': '⚡ Valid 24h for new accounts',
            'feat_1': 'Audit Report & 3-Month Schedule',
            'feat_2': '"Avi Auto-Pilot" Module (Yearly Management)',
            'feat_3': 'Strategic Keywords & Review Replies',
            'modal_check': 'I confirm I want to activate my rise on Google Maps.',
            'modal_cta': 'Launch Full Analysis',
            'modal_secure': '🔒 Secure Stripe Payment',
            'chat_welcome': 'Connecting to AVI...',
            'chat_proactive': 'I see you hesitating. Do you want to know how many clients you are currently losing? 🤔',
            'chat_restricted': '🔒 <strong>Sorry...</strong><br>I cannot analyze this specific data without the Premium license. Click on a lock to unlock.',
            'chat_score_expl': 'The Health Score is a grade out of 100 reflecting your Google visibility. Below 50, you are invisible to 8 out of 10 clients.',
            'chat_agency_expl': 'Let us do the math: A local SEO agency charges avg <strong>$500/mo</strong>. A consultant? <strong>$150/hr</strong>.<br>With me, it is <strong>$99 one-time</strong>. That is literally 10x cheaper for the same result. 😉',
            'chat_help_expl': 'I am here to guide you to the Top 3. What is your priority today?',
            'chat_levels_expl': 'These levels represent the pillars of local SEO: Reviews, Backlinks, Citations... I unlock them one by one to avoid overwhelming you.',
            'footer_rights': 'All rights reserved.',
            'iceberg_text': '+ other hidden ranking criteria levels...',
            'testi_title': 'Latest Client Results',
            'testi_1': '"I applied level 2. Result: +15 calls this weekend."',
            'testi_2': '"My profile passed the dealership. Agenda full."',
            'testi_3': '"3 new patients per week thanks to unlocked keywords."',
            'lvl_2': 'Description Optimization',
            'lvl_3': 'Photos (Pack 1)',
            'lvl_4': 'Website Boost',
            'lvl_5': 'Directory & GPS Presence',
            'lvl_6': 'Google Posts & News',
            'lvl_7': 'Security & Fake Reviews',
            'club_secu': 'Security Club',
            'chip_price': '💰 Price & ROI',
            'chip_score': '📉 My Score',
            'chip_levels': '🚀 What are Levels?',
            'chip_unlock': '🔓 How to unlock?'
        },
        'fr': {
            'default_competitor_name': 'Votre Concurrent',
            'social_proof': '🔥 14 entreprises ont optimise leur fiche Google Business Profile cette semaine. Derniere : <strong>Cabinet Dupont (Score: 80/100)</strong>',
            'opp_gap': 'CRITIQUE : Vous perdez du trafic face a',
            'certif_badge': '🛡️ Normes Google Maps 2026',
            'premium_badge': '💎 Partenaire Premium',
            'score_title': 'Score de Sante',
            'score_status': 'Critique',
            'comp_title': 'Analyse Concurrentielle',
            'stat_pos': 'Votre Position Reelle :',
            'stat_pos_val': '7eme (Invisible)',
            'stat_leader': 'Leader du Secteur :',
            'leader_rank': '(1er)',
            'stat_potential': 'Potentiel de Progression :',
            'stat_potential_val': '+300% Appels & Itineraires',
            'phase_title': 'PHASE 1 : L ERREUR CRITIQUE DEVOILEE',
            'phase_subtitle': 'C est ce qui bloquait 80% de votre visibilite.',
            'ai_analysis_label': '🤖 Analyse IA :',
            'ai_analysis_text': 'J ai filtre les fiches erronees. Voici <strong>les categories strategiques</strong> utilisees par les VRAIS leaders de votre secteur :',
            'blur_alert': '3 Mots-cles Critiques Detectes (Masque)',
            'btn_unlock': '🔓 Debloquer l analyse',
            'lvl1_title': '1. Correction des Categories',
            'lvl1_desc': 'Definissez la categorie suivante comme principale :',
            'btn_howto': '💡 Comment faire ?',
            'btn_verify': 'Verifier le correctif',
            'modal_head': 'Activez votre Roadmap SEO 90 Jours',
            'modal_sub': 'Obtenez le plan d action precis et les outils d automatisation pour ameliorer et securiser votre position.',
            'modal_timer': '⚡ Valide 24h pour les nouveaux comptes',
            'feat_1': 'Rapport d Audit & Planning sur 3 mois',
            'feat_2': 'Module "Avi Auto-Pilot" (Gestion a l annee)',
            'feat_3': 'Mots-cles Strategiques & Reponses aux Avis',
            'modal_check': 'Je confirme vouloir activer ma remontee sur Google Maps.',
            'modal_cta': 'Lancer l analyse complete',
            'modal_secure': '🔒 Paiement Securise Stripe',
            'chat_welcome': 'Connexion à AVI...',
            'chat_proactive': 'Je vois que vous hesitez. Voulez-vous savoir combien de clients vous perdez actuellement ? 🤔',
            'chat_restricted': '🔒 <strong>Desole...</strong><br>Je ne peux pas analyser cette donnee precise sans la licence Premium. Cliquez sur un cadenas pour debloquer.',
            'chat_score_expl': 'Le Score de Sante est une note sur 100 qui reflete la visibilite de votre fiche Google. En dessous de 50, vous etes invisible pour 8 clients sur 10.',
            'chat_agency_expl': 'Faisons le calcul : Une agence SEO locale facture en moyenne <strong>500 EUR/mois</strong>. Un consultant ? <strong>150 EUR de l heure</strong>.<br>Avec moi, c est <strong>99 EUR une seule fois</strong>. C est litteralement 10x moins cher pour le meme resultat. 😉',
            'chat_help_expl': 'Je suis la pour vous guider vers le Top 3. Quelle est votre priorite aujourd hui ?',
            'chat_levels_expl': 'Ces niveaux representent les piliers du SEO local : Avis, Backlinks, Citations... Je les debloque un par un pour ne pas vous surcharger.',
            'footer_rights': 'Tous droits reserves.',
            'iceberg_text': '+ d autres niveaux de criteres de ranking masques...',
            'testi_title': 'Derniers Resultats Clients',
            'testi_1': '"J ai applique le niveau 2. Resultat : +15 appels ce week-end."',
            'testi_2': '"Ma fiche est passee devant celle du concessionnaire. Agenda plein."',
            'testi_3': '"3 nouveaux patients par semaine grace aux mots-cles debloques."',
            'lvl_2': 'Optimisation Description',
            'lvl_3': 'Photos (Pack 1)',
            'lvl_4': 'Boost Site Web',
            'lvl_5': 'Presence Annuaires & GPS',
            'lvl_6': 'Google Posts & Actualites',
            'lvl_7': 'Securisation & Faux Avis',
            'club_secu': 'Club Securite',
            'chip_price': '💰 Prix & Rentabilite',
            'chip_score': '📉 Mon Score',
            'chip_levels': '🚀 C est quoi les Niveaux ?',
            'chip_unlock': '🔓 Comment debloquer ?'
        },
        'es': {
            'default_competitor_name': 'Tu Competidor',
            'social_proof': '🔥 14 empresas optimizaron su Perfil de Negocio Google esta semana. Ultima: <strong>Garcia SL (Puntuacion: 80/100)</strong>',
            'opp_gap': 'CRITICO: Estas perdiendo trafico frente a',
            'certif_badge': '🛡️ Normas Google Maps 2026',
            'premium_badge': '💎 Socio Premium',
            'score_title': 'Puntuacion de Salud',
            'score_status': 'Critico',
            'comp_title': 'Analisis Competitivo',
            'stat_pos': 'Tu Posicion Real:',
            'stat_pos_val': '7mo (Invisible)',
            'stat_leader': 'Lider del Sector:',
            'leader_rank': '(1ro)',
            'stat_potential': 'Potencial de Crecimiento:',
            'stat_potential_val': '+300% Llamadas y Rutas',
            'phase_title': 'FASE 1: ERROR CRITICO REVELADO',
            'phase_subtitle': 'Esto bloqueaba el 80% de tu visibilidad.',
            'ai_analysis_label': '🤖 Analisis IA:',
            'ai_analysis_text': 'He filtrado las fichas erroneas. Aqui estan las <strong>categorias estrategicas</strong> de los lideres:',
            'blur_alert': '3 Palabras Clave Criticas (Oculto)',
            'btn_unlock': '🔓 Desbloquear Analisis',
            'lvl1_title': '1. Correccion de Categorias',
            'lvl1_desc': 'Define la siguiente categoria como principal:',
            'btn_howto': '💡 Como hacerlo?',
            'btn_verify': 'Verificar Correccion',
            'modal_head': 'Activa tu Hoja de Ruta SEO 90 Dias',
            'modal_sub': 'Obten el plan de accion preciso y las herramientas de automatizacion para mejorar y asegurar tu posicion.',
            'modal_timer': '⚡ Valido 24h para cuentas nuevas',
            'feat_1': 'Informe de Auditoria y Planificacion 3 Meses',
            'feat_2': 'Modulo "Avi Auto-Pilot" (Gestion Anual)',
            'feat_3': 'Palabras Clave y Respuestas a Resenas',
            'modal_check': 'Confirmo que quiero activar mi ascenso en Google Maps.',
            'modal_cta': 'Lanzar Analisis Completo',
            'modal_secure': '🔒 Pago Seguro Stripe',
            'chat_welcome': 'Conectando a AVI...',
            'chat_proactive': 'Veo que dudas. Quieres saber cuantos clientes estas perdiendo actualmente? 🤔',
            'chat_restricted': '🔒 <strong>Lo siento...</strong><br>No puedo analizar este dato sin la licencia Premium. Haz clic en un candado para desbloquear.',
            'chat_score_expl': 'La Puntuacion de Salud es una nota sobre 100 que refleja tu visibilidad en Google. Por debajo de 50, eres invisible para 8 de cada 10 clientes.',
            'chat_agency_expl': 'Hagamos cuentas: Una agencia SEO cobra de media <strong>500 EUR/mes</strong>. Un consultor? <strong>150 EUR/hora</strong>.<br>Conmigo, son <strong>99 EUR una sola vez</strong>. Es literalmente 10 veces mas barato por el mismo resultado. 😉',
            'chat_help_expl': 'Estoy aqui para guiarte al Top 3. Cual es tu prioridad hoy?',
            'chat_levels_expl': 'Estos niveles representan los pilares del SEO local: Resenas, Backlinks, Citas... Los desbloqueo uno por uno para no abrumarte.',
            'footer_rights': 'Todos los derechos reservados.',
            'iceberg_text': '+ otros niveles de criterios de ranking ocultos...',
            'testi_title': 'Ultimos Resultados de Clientes',
            'testi_1': '"Aplique el nivel 2. Resultado: +15 llamadas este fin de semana."',
            'testi_2': '"Mi ficha paso a la del concesionario. Agenda llena."',
            'testi_3': '"3 nuevos pacientes por semana gracias a las palabras clave."',
            'lvl_2': 'Optimizacion Descripcion',
            'lvl_3': 'Fotos (Pack 1)',
            'lvl_4': 'Impulso Sitio Web',
            'lvl_5': 'Presencia en Directorios y GPS',
            'lvl_6': 'Google Posts y Actualidad',
            'lvl_7': 'Seguridad y Resenas Falsas',
            'club_secu': 'Club de Seguridad',
            'chip_price': '💰 Precio y ROI',
            'chip_score': '📉 Mi Puntuacion',
            'chip_levels': '🚀 Que son los Niveles?',
            'chip_unlock': '🔓 Como desbloquear?'
        }
    };

    let currentLang = 'en';
    let userInteracted = false;
    let config = { companyName: '', city: '', category: '', email: '' };

    function init() {
        loadUserData();
        updateLanguage(currentLang);
        renderLockedLevels();
        initChat();
        document.getElementById('footerYear').textContent = new Date().getFullYear();
        
        if (window.innerWidth > 900) {
            setTimeout(() => {
                const chatWin = document.getElementById('aviWindow');
                if (!chatWin.classList.contains('open')) toggleChat();
            }, 1500);
        }

        setTimeout(() => {
            if (!userInteracted) {
                const chatWin = document.getElementById('aviWindow');
                if (chatWin && !chatWin.classList.contains('open')) {
                    document.getElementById('aviBadge').classList.add('visible');
                }
            }
        }, 45000);
    }

    function loadUserData() {
        const params = new URLSearchParams(window.location.search);
        
        config.companyName = params.get('company') || localStorage.getItem('avision_company') || 'Dashboard Demo';
        config.city = params.get('city') || localStorage.getItem('avision_city') || '';
        config.category = params.get('category') || localStorage.getItem('avision_category') || 'Professional Services';
        config.email = params.get('email') || localStorage.getItem('avision_email') || '';
        
        const urlLang = params.get('lang');
        const storedLang = localStorage.getItem('avision_lang');
        currentLang = urlLang || storedLang || 'en';
        if (!['en', 'fr', 'es'].includes(currentLang)) currentLang = 'en';

        localStorage.setItem('avision_company', config.companyName);
        localStorage.setItem('avision_city', config.city);
        localStorage.setItem('avision_category', config.category);
        localStorage.setItem('avision_email', config.email);
        localStorage.setItem('avision_lang', currentLang);

        document.getElementById('companyNameDisplay').textContent = decodeURIComponent(config.companyName);
        document.title = 'Audit: ' + decodeURIComponent(config.companyName);
        
        const categoryTag = document.getElementById('categoryTag');
        if (categoryTag) categoryTag.textContent = decodeURIComponent(config.category);
        
        const primaryCategoryTag = document.getElementById('primaryCategoryTag');
        if (primaryCategoryTag) primaryCategoryTag.textContent = decodeURIComponent(config.category);

        const score = parseInt(params.get('score') || '42', 10);
        updateScore(score);
    }

    function updateScore(scoreInt) {
        const scoreTextEl = document.getElementById('score-text');
        if (scoreTextEl) scoreTextEl.textContent = scoreInt + '/100';

        const scoreCircle = document.getElementById('score-circle');
        if (scoreCircle) {
            const circumference = 2 * Math.PI * 45;
            const offset = circumference - ((scoreInt / 100) * circumference);
            scoreCircle.style.strokeDashoffset = offset;

            if (scoreInt < 50) scoreCircle.style.stroke = '#ef4444';
            else if (scoreInt < 80) scoreCircle.style.stroke = '#f59e0b';
            else scoreCircle.style.stroke = '#10b981';
        }

        const statusEl = document.getElementById('score-status');
        if (statusEl) {
            if (scoreInt < 50) { statusEl.textContent = translations[currentLang].score_status || 'Critical'; statusEl.style.fill = '#ef4444'; }
            else if (scoreInt < 80) { statusEl.textContent = 'Average'; statusEl.style.fill = '#f59e0b'; }
            else { statusEl.textContent = 'Excellent'; statusEl.style.fill = '#10b981'; }
        }
    }

    function updateLanguage(lang) {
        currentLang = lang;
        const t = translations[lang];
        
        document.querySelectorAll('[data-i18n]').forEach(el => {
            const key = el.getAttribute('data-i18n');
            if (t[key]) el.innerHTML = t[key];
        });

        document.querySelectorAll('.header-flag').forEach(flag => {
            flag.classList.remove('active');
            if (flag.dataset.lang === lang) flag.classList.add('active');
        });

        localStorage.setItem('avision_lang', lang);
        renderLockedLevels();
    }

    function renderLockedLevels() {
        const container = document.getElementById('locked-levels-container');
        if (!container) return;
        const t = translations[currentLang];
        
        const levels = [
            { id: 2, key: 'lvl_2', badge: 'LVL 2', style: '' },
            { id: 3, key: 'lvl_3', badge: 'LVL 3', style: 'gold-level', extra: t.club_secu },
            { id: 4, key: 'lvl_4', badge: 'BONUS', style: 'purple-level' },
            { id: 5, key: 'lvl_5', badge: 'LVL 5', style: '' },
            { id: 6, key: 'lvl_6', badge: 'LVL 6', style: '' },
            { id: 7, key: 'lvl_7', badge: 'LVL 7', style: '' }
        ];

        let html = '';
        levels.forEach(lvl => {
            const extraHtml = lvl.extra ? '<span class="club-label">' + lvl.extra + '</span>' : '';
            html += '<div class="level-card locked ' + lvl.style + '" onclick="AvisionDemo.openSales()">' +
                '<div class="level-header">' +
                    '<div style="display:flex; align-items:center;">' +
                        '<span class="level-badge">' + lvl.badge + '</span>' +
                        '<span class="level-title">' + t[lvl.key] + '</span>' +
                        extraHtml +
                    '</div>' +
                    '<div style="display:flex; align-items:center; gap:15px;">' +
                        '<span style="font-size:1.2rem;">🔒</span>' +
                    '</div>' +
                '</div>' +
            '</div>';
        });
        container.innerHTML = html;
    }

    function toggleLevel(levelId) {
        const content = document.getElementById(levelId + '-content');
        const chevron = document.getElementById('chevron-' + levelId);
        if (content.classList.contains('open')) {
            content.classList.remove('open');
            chevron.classList.remove('rotate');
        } else {
            content.classList.add('open');
            chevron.classList.add('rotate');
        }
    }

    function fakeVerify(event) {
        event.stopPropagation();
        const btn = document.getElementById('btnVerify');
        btn.innerHTML = '<div class="spinner"></div>';
        setTimeout(() => {
            btn.innerHTML = '<span class="btn-text">' + translations[currentLang].btn_verify + '</span>';
            openSales();
        }, 1200);
    }

    function openSales() {
        document.getElementById('salesModal').style.display = 'flex';
    }

    function closeSales() {
        document.getElementById('salesModal').style.display = 'none';
    }

    function toggleSalesBtn() {
        const chk = document.getElementById('confirmComp');
        const btn = document.getElementById('salesBtn');
        btn.disabled = !chk.checked;
    }

    function initChat() {
        setTimeout(renderQuickReplies, 500);
    }

    function callChatAPI(message, onReply) {
        const ajaxUrl = (typeof avisionSettings !== 'undefined' && avisionSettings.ajaxUrl) ? avisionSettings.ajaxUrl : (window.avisionSettings && window.avisionSettings.ajaxUrl) || '/wp-admin/admin-ajax.php';
        const formData = new FormData();
        formData.append('action', 'avision_api');
        formData.append('avision_action', 'send_chat_message');
        formData.append('message', message);
        formData.append('currentLevel', 1);
        formData.append('score', 0);
        if (typeof avisionSettings !== 'undefined' && avisionSettings.nonce) formData.append('nonce', avisionSettings.nonce);
        else if (window.avisionSettings && window.avisionSettings.nonce) formData.append('nonce', window.avisionSettings.nonce);
        fetch(ajaxUrl, { method: 'POST', body: formData })
            .then(r => r.json())
            .then(resp => {
                const data = resp && resp.data ? resp.data : resp;
                const reply = (resp && resp.success && data && data.reply) ? data.reply : (currentLang === 'fr' ? 'Connexion à AVI... Réessayez.' : 'Connecting to AVI... Try again.');
                if (typeof onReply === 'function') onReply(reply);
            })
            .catch(() => { if (typeof onReply === 'function') onReply(currentLang === 'fr' ? 'Connexion à AVI... Réessayez.' : 'Connecting to AVI... Try again.'); });
    }

    function toggleChat() {
        document.getElementById('aviWindow').classList.toggle('open');
        document.getElementById('aviBadge').classList.remove('visible');
        userInteracted = true;
    }

    function addMessage(sender, text) {
        const chatBody = document.getElementById('chatBody');
        const div = document.createElement('div');
        div.className = 'msg ' + sender;
        div.innerHTML = text;
        chatBody.appendChild(div);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function renderQuickReplies() {
        const chatBody = document.getElementById('chatBody');
        const t = translations[currentLang];
        
        const chipsContainer = document.createElement('div');
        chipsContainer.className = 'chat-chips';
        
        const chips = [
            { label: t.chip_price, action: 'price' },
            { label: t.chip_score, action: 'score' },
            { label: t.chip_levels, action: 'levels' },
            { label: t.chip_unlock, action: 'unlock' }
        ];

        chips.forEach(chip => {
            const btn = document.createElement('div');
            btn.className = 'chat-chip';
            btn.innerText = chip.label;
            btn.onclick = () => handleChipClick(chip.label, chip.action);
            chipsContainer.appendChild(btn);
        });

        chatBody.appendChild(chipsContainer);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function handleChipClick(label, action) {
        userInteracted = true;
        const chips = document.querySelector('.chat-chips');
        if (chips) chips.remove();
        addMessage('user', label);
        showTyping();
        if (action === 'unlock') {
            hideTyping();
            const t = translations[currentLang];
            addMessage('avi', t.chat_restricted);
            openSales();
            setTimeout(renderQuickReplies, 1000);
            return;
        }
        callChatAPI(label, (reply) => {
            hideTyping();
            addMessage('avi', reply);
            setTimeout(renderQuickReplies, 1000);
        });
    }

    function showTyping() {
        const indicator = document.getElementById('typingIndicator');
        indicator.classList.add('active');
        const chatBody = document.getElementById('chatBody');
        chatBody.appendChild(indicator);
        chatBody.scrollTop = chatBody.scrollHeight;
    }

    function hideTyping() {
        document.getElementById('typingIndicator').classList.remove('active');
    }

    function handleEnter(e) {
        if (e.key === 'Enter') sendMessage();
    }

    function sendMessage() {
        const input = document.getElementById('chatInput');
        const text = input.value.trim();
        if (!text) return;
        userInteracted = true;
        addMessage('user', text);
        input.value = '';
        const chips = document.querySelector('.chat-chips');
        if (chips) chips.remove();
        showTyping();
        callChatAPI(text, (reply) => {
            hideTyping();
            addMessage('avi', reply);
            setTimeout(renderQuickReplies, 1000);
        });
    }

    return {
        init: init,
        updateLanguage: updateLanguage,
        toggleLevel: toggleLevel,
        fakeVerify: fakeVerify,
        openSales: openSales,
        closeSales: closeSales,
        toggleSalesBtn: toggleSalesBtn,
        toggleChat: toggleChat,
        handleEnter: handleEnter,
        sendMessage: sendMessage,
        handleChipClick: handleChipClick
    };
})();

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', AvisionDemo.init);
} else {
    AvisionDemo.init();
}
</script>
<?php
$_demo_stripe_url = '';
if ( function_exists( 'avi_create_stripe_checkout_session' ) ) {
	$_demo_uid = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0;
	$_demo_stripe_url = avi_create_stripe_checkout_session( $_demo_uid, 'ltd_solo', 'usd' );
	if ( is_string( $_demo_stripe_url ) && ( $_demo_stripe_url === '' || strpos( $_demo_stripe_url, '#' ) === 0 ) ) {
		$_demo_stripe_url = home_url( '/pricing/' );
	}
}
?>
<script>window.AvisionStripeCheckoutUrl = <?php echo wp_json_encode( $_demo_stripe_url ); ?>;</script>
</body>
</html>
