/**
 * Avision Dashboard - Main Entry Point (Version 9.0)
 * Standalone PHP / WordPress Compatible
 * Network Proxy Shield : interception du flux JSON (pending-posts / admin-ajax) pour remplacer le texte fantôme par le VIP.
 */

(function() {
    if (typeof window === 'undefined' || !window.fetch) return;
    var orig = window.fetch;
    window.fetch = function() {
            var args = Array.prototype.slice.call(arguments);
            var url = (typeof args[0] === 'string') ? args[0] : (args[0] && args[0].url ? args[0].url : '');
            if (url.indexOf('/guardian/pending-posts') !== -1 || url.indexOf('admin-ajax') !== -1) {
                return orig.apply(this, args).then(function(response) {
                    var clone = response.clone();
                    return clone.json().then(function(data) {
                        var vip = "🌟 Ravi de vous voir ici ! Découvrez AVI SEO Local Consultant à London.\n\nNous sommes là pour vous avec le sourire — notre équipe Marketing vous accueille toute l'année. Chaque avis compte pour nous !\n\nÀ très bientôt ! #AvisClients #Recommandation #Marketing";
                        function shield(obj) {
                            if (!obj || typeof obj !== 'object') return;
                            for (var key in obj) {
                                if (Object.prototype.hasOwnProperty.call(obj, key)) {
                                    if (typeof obj[key] === 'string' && (obj[key].indexOf('Bonjour') !== -1 || obj[key].length < 20)) {
                                        obj[key] = vip;
                                    } else if (typeof obj[key] === 'object') {
                                        shield(obj[key]);
                                    }
                                }
                            }
                        }
                        if (data) shield(data);
                        return new Response(JSON.stringify(data), { status: response.status, statusText: response.statusText, headers: response.headers });
                    }).catch(function() { return response; });
                });
            }
            return orig.apply(this, args);
        };
})();

(function() {
    if (typeof window === 'undefined' || !window.XMLHttpRequest) return;
    var open = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
        var xhr = this;
        this.addEventListener('load', function() {
            try {
                if (xhr.responseText && xhr.responseText.indexOf('Bonjour London') !== -1) {
                    if (typeof console !== 'undefined' && console.log) {
                        console.log('🛡️ AVI Shield: XHR Ghost detected and neutralized.');
                    }
                    setTimeout(function() {
                        if (typeof window.__avisionPermanentVipGuard === 'function') {
                            window.__avisionPermanentVipGuard();
                        }
                    }, 200);
                }
            } catch (e) { /* ignore */ }
        });
        return open.apply(this, arguments);
    };
})();

(function() {
    'use strict';

    // Translation dictionaries
    const translations = {
        en: {
            certif_badge: "🛡️ Google Maps Standards 2026",
            premium_badge: "💎 Premium Partner",
            save_audit: "💾 Save my Audit",
            save_desc: "Enter your email to receive your unique access link and 72h safety alerts.",
            send_btn: "Send",
            score_title: "Visibility Score",
            status_critical: "⚠️ CRITICAL STATUS",
            analysis_title: "Competitive Analysis",
            phase1_title: "PHASE 1: THE CRITICAL ERROR REVEALED",
            phase1_desc: "This is what was blocking 80% of your visibility.",
            lvl1_title: "Category Correction",
            lvl2_title: "Description Optimization",
            lvl3_title: "Photos (Pack 1)",
            lvl4_title: "Website Boost",
            timer_label: "Unlocks in:",
            method_title: "📘 The \"Natural Growth\" Method (90 Days)",
            modal_title: "🔔 Get Notified",
            modal_desc: "We will send you an email when the 72h analysis is complete.",
            modal_btn: "Notify Me",
            modal_cancel: "Cancel",
            modal_close: "Close"
        },
        fr: {
            certif_badge: "🛡️ Normes Google Maps 2026",
            premium_badge: "💎 Partenaire Premium",
            save_audit: "💾 Sauvegarder mon Audit",
            save_desc: "Entrez votre email pour recevoir votre lien d'accès unique et les alertes de sécurité 72h.",
            send_btn: "Envoyer",
            score_title: "Score de Visibilité",
            status_critical: "⚠️ STATUT CRITIQUE",
            analysis_title: "Analyse Concurrentielle",
            phase1_title: "PHASE 1 : L'ERREUR CRITIQUE DÉVOILÉE",
            phase1_desc: "C'est ce qui bloquait 80% de votre visibilité.",
            lvl1_title: "Correction de Catégorie",
            lvl2_title: "Optimisation Description",
            lvl3_title: "Photos (Pack 1)",
            lvl4_title: "Boost Site Web",
            timer_label: "Débloqué dans :",
            method_title: "📘 La Méthode \"Croissance Naturelle\" (90 Jours)",
            modal_title: "🔔 Être Notifié",
            modal_desc: "Nous vous enverrons un email lorsque l'analyse de 72h sera terminée.",
            modal_btn: "Me Notifier",
            modal_cancel: "Annuler",
            modal_close: "Fermer"
        },
        es: {
            certif_badge: "🛡️ Normas Google Maps 2026",
            premium_badge: "💎 Socio Premium",
            save_audit: "💾 Guardar mi Auditoría",
            save_desc: "Ingresa tu email para recibir tu enlace de acceso único y alertas de seguridad 72h.",
            send_btn: "Enviar",
            score_title: "Puntuación de Visibilidad",
            status_critical: "⚠️ ESTADO CRÍTICO",
            analysis_title: "Análisis Competitivo",
            phase1_title: "FASE 1: EL ERROR CRÍTICO REVELADO",
            phase1_desc: "Esto es lo que bloqueaba el 80% de tu visibilidad.",
            lvl1_title: "Corrección de Categoría",
            lvl2_title: "Optimización de Descripción",
            lvl3_title: "Fotos (Pack 1)",
            lvl4_title: "Impulso del Sitio Web",
            timer_label: "Se desbloquea en:",
            method_title: "📘 El Método \"Crecimiento Natural\" (90 Días)",
            modal_title: "🔔 Ser Notificado",
            modal_desc: "Te enviaremos un email cuando el análisis de 72h esté completo.",
            modal_btn: "Notificarme",
            modal_cancel: "Cancelar",
            modal_close: "Cerrar"
        }
    };

    // State management
    const AvisionState = {
        data: {
            lang: 'en',
            lvl1Done: false,
            progress: {}
        },
        loadServerData: function(progress) {
            if (progress && typeof progress === 'object') {
                this.data.progress = progress;
                if (progress[1] === 'completed') {
                    this.data.lvl1Done = true;
                }
            }
        },
        updateLvl1: function(done) {
            this.data.lvl1Done = done;
        }
    };

    // UI Renderer
    const UIRenderer = {
        updateLanguage: function(lang) {
            const dict = translations[lang] || translations['en'];
            document.querySelectorAll('[data-i18n]').forEach(function(el) {
                const key = el.getAttribute('data-i18n');
                if (dict[key]) {
                    el.textContent = dict[key];
                }
            });
            
            document.querySelectorAll('.header-flag').forEach(function(flag) {
                flag.classList.remove('active');
                if (flag.getAttribute('data-lang') === lang) {
                    flag.classList.add('active');
                }
            });
            
            localStorage.setItem('avision_lang', lang);
        },
        
        toggleAccordion: function(id) {
            const content = document.getElementById(id + '-content');
            const chevron = document.getElementById('chevron-' + id);
            
            if (content) {
                content.classList.toggle('open');
            }
            if (chevron) {
                chevron.classList.toggle('rotate');
            }
        },
        
        addChatMessage: function(type, message) {
            const chatBody = document.getElementById('chatBody');
            if (!chatBody) return;
            
            const msgDiv = document.createElement('div');
            msgDiv.className = 'msg ' + type;
            // Convert markdown **bold** and *italic* to HTML
            const rendered = message
                .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
                .replace(/\*([^*]+)\*/g, '<em>$1</em>');
            msgDiv.innerHTML = rendered;
            chatBody.appendChild(msgDiv);
            chatBody.scrollTop = chatBody.scrollHeight;
        },
        
        clearChat: function() {
            const chatBody = document.getElementById('chatBody');
            if (chatBody) {
                chatBody.innerHTML = '';
            }
        },
        
        showFeedback: function(id, message) {
            const el = document.getElementById(id);
            if (el) {
                el.textContent = message;
                el.style.display = 'block';
            }
        }
    };

    // API Client
    const APIClient = {
        post: function(action, data) {
            const formData = new FormData();
            formData.append('action', action);
            
            if (typeof avisionSettings !== 'undefined' && avisionSettings.nonce) {
                formData.append('nonce', avisionSettings.nonce);
            }
            
            for (var key in data) {
                if (data.hasOwnProperty(key)) {
                    formData.append(key, data[key]);
                }
            }
            
            var ajaxUrl = '/api.php';
            if (typeof avisionSettings !== 'undefined' && avisionSettings.ajaxUrl) {
                ajaxUrl = avisionSettings.ajaxUrl;
            }
            
            return fetch(ajaxUrl, {
                method: 'POST',
                body: formData
            }).then(function(response) {
                return response.json();
            });
        }
    };

    /** Texte VIP de remplacement (VIP Hijacker) lorsque le volet affiche un contenu fantôme. */
    var VIP_HIJACK_TEXT = "🌟 Ravi de vous voir ici ! Découvrez AVI SEO Local Consultant à London.\n\nNous sommes là pour vous avec le sourire — notre équipe Marketing vous accueille toute l'année. Chaque avis compte pour nous !\n\nÀ très bientôt ! #AvisClients #Recommandation #Marketing";
    var VIP_IMAGE_URL = "https://images.unsplash.com/photo-1497366216548-37526070297c?w=800&q=80";

    /** Super-Hijacker : intervalle de garde (toutes les 100ms) quand .action-panel-validation est visible. Vide l'élément si texte fantôme (window.avision_ghost_text) détecté. */
    function permanentVipGuard() {
        var ghostPhrase = (typeof window.avision_ghost_text === 'string') ? window.avision_ghost_text : 'Bonjour London';
        var panel = document.querySelector('.action-panel-validation');
        if (!panel || panel.offsetParent === null) return;
        var textarea = document.getElementById('validation-post-textarea');
        if (textarea) {
            var val = (textarea.value || '').trim();
            var lower = val.toLowerCase();
            if (lower.indexOf(ghostPhrase.toLowerCase()) !== -1 || lower.indexOf('bonjour') !== -1 || val.length < 10) {
                textarea.value = VIP_HIJACK_TEXT;
            }
        }
        var imgs = panel.querySelectorAll('img[src]');
        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var src = (img.getAttribute('src') || '').toLowerCase();
            var alt = (img.getAttribute('alt') || '').toLowerCase();
            if (src.indexOf('piscine') !== -1 || alt.indexOf('piscine') !== -1 || src.indexOf('pool') !== -1 || alt.indexOf('pool') !== -1 || alt.indexOf('maison') !== -1) {
                img.setAttribute('src', VIP_IMAGE_URL);
            }
        }
    }

    window.__avisionPermanentVipGuard = permanentVipGuard;
    var vipGuardInterval = setInterval(permanentVipGuard, 100);

    /** Purge localStorage chat si l'historique contient un message obsolète ("Catégorie Principale" / "Ravi de te revoir"). */
    function purgeObsoleteChatHistory() {
        try {
            var saved = localStorage.getItem('avision_chat_history');
            if (!saved) return;
            var list = JSON.parse(saved);
            if (!Array.isArray(list)) return;
            var obsolete = list.some(function(msg) {
                var t = (msg && (msg.text || msg.message || ''));
                return t.indexOf('Catégorie Principale') !== -1 || t.indexOf('Ravi de te revoir') !== -1;
            });
            if (obsolete) {
                localStorage.removeItem('avision_chat_history');
            }
        } catch (e) { /* ignore */ }
    }

    // Main Dashboard Object
    window.AvisionDashboard = {
        
        init: function() {
            try {
                window.avision_ghost_text = 'Bonjour London';
                console.log('Avision System: Starting...');
                var root = document.getElementById('avision-dashboard-root');
                purgeObsoleteChatHistory();
                if (root) {
                    var progress = root.getAttribute('data-progress');
                    if (progress) {
                        try {
                            AvisionState.loadServerData(JSON.parse(progress));
                        } catch (e) {
                            console.warn('Could not parse progress data');
                        }
                    }
                    
                    var lang = root.getAttribute('data-lang') || localStorage.getItem('avision_lang') || 'en';
                    this.switchLanguage(lang);
                    
                    if (AvisionState.data.lvl1Done) {
                        this.applyLvl1SuccessUI();
                    }
                }
                
                var spotlight = document.getElementById('spotlightOverlay');
                if (spotlight) {
                    spotlight.classList.remove('is-active');
                }
                
                console.log('Avision System: READY.');
            } catch (e) {
                console.error("Avision Critical Error:", e);
            }
        },

        switchLanguage: function(lang) {
            AvisionState.data.lang = lang;
            UIRenderer.updateLanguage(lang);
            UIRenderer.clearChat();
            // Ne jamais pré-remplir une phrase d'accueil : le frontend attend la réponse API ou affiche un loader
        },

        toggleNotifModal: function() {
            var modal = document.getElementById('notifModal');
            if (modal) {
                modal.classList.toggle('is-visible');
            }
        },

        toggleLevel: function(id) {
            UIRenderer.toggleAccordion(id);
        },

        toggleHowTo: function(id) {
            var box = document.getElementById('howToBox-' + id);
            if (box) {
                box.style.display = box.style.display === 'none' ? 'block' : 'none';
            }
        },

        verifyLevel1: function(e) {
            if (e) e.stopPropagation();
            if (AvisionState.data.lvl1Done) return;
            
            var btn = document.getElementById('btnVerify1');
            if (btn) {
                btn.innerHTML = '⏳ ...';
                btn.disabled = true;
            }

            var self = this;
            APIClient.post('verify_level_progress', { level: 1 })
                .then(function(res) {
                    if (res && res.success) {
                        AvisionState.updateLvl1(true);
                        self.applyLvl1SuccessUI();
                        self.createConfetti();
                        UIRenderer.updateLanguage(AvisionState.data.lang);
                        UIRenderer.showFeedback('verifyFeedback', 'Success!');
                    } else if (btn) {
                        btn.disabled = false;
                        btn.innerHTML = 'Retry';
                    }
                })
                .catch(function() {
                    if (btn) {
                        btn.disabled = false;
                        btn.innerHTML = 'Retry';
                    }
                });
        },

        applyLvl1SuccessUI: function() {
            var level1 = document.getElementById('level1');
            var btn = document.getElementById('btnVerify1');
            var badge = document.getElementById('lvl1StatusBadge');
            var successBox = document.getElementById('lvl1SuccessBox');
            
            if (level1) {
                level1.classList.remove('active');
                level1.classList.add('done');
            }
            if (btn) {
                btn.disabled = true;
                btn.style.background = '#10b981';
                btn.textContent = 'Verified';
            }
            if (successBox) {
                successBox.style.display = 'block';
            }
            if (badge) {
                badge.textContent = 'DONE';
                badge.style.background = '#10b981';
            }
        },

        toggleChat: function() {
            var chatWindow = document.getElementById('aviWindow');
            if (chatWindow) {
                if (chatWindow.style.display === 'none' || chatWindow.style.display === '') {
                    chatWindow.style.display = 'flex';
                } else {
                    chatWindow.style.display = 'none';
                }
            }
        },

        sendMessage: function() {
            var input = document.getElementById('chatInput');
            if (!input) return;
            
            var txt = input.value.trim();
            if (!txt) return;
            
            UIRenderer.addChatMessage('user', txt);
            input.value = '';
            
            var self = this;
            var chatBody = document.getElementById('chatBody');
            var loaderId = 'avi-loader-' + Date.now();
            if (chatBody) {
                var loader = document.createElement('div');
                loader.id = loaderId;
                loader.className = 'msg avi';
                loader.setAttribute('data-loader', '1');
                loader.textContent = '...';
                chatBody.appendChild(loader);
                chatBody.scrollTop = chatBody.scrollHeight;
            }
            
            self.callChatAPI(txt, loaderId);
        },
        
        callChatAPI: function(message, loaderId) {
            var self = this;
            var root = document.getElementById('avision-dashboard-root');
            var level = root && root.getAttribute('data-progress') ? (function() {
                try {
                    var p = JSON.parse(root.getAttribute('data-progress'));
                    if (p && p[1] === 'completed') return 2;
                    return 1;
                } catch (e) { return 1; }
            })() : 1;
            var score = (root && root.getAttribute('data-score')) ? parseInt(root.getAttribute('data-score'), 10) : 0;
            if (isNaN(score)) score = 0;
            var ajaxUrl = (typeof avisionSettings !== 'undefined' && avisionSettings.ajaxUrl) ? avisionSettings.ajaxUrl : (window.avisionSettings && window.avisionSettings.ajaxUrl) || '/api.php';
            var formData = new FormData();
            formData.append('action', 'avision_api');
            formData.append('avision_action', 'send_chat_message');
            formData.append('message', message);
            formData.append('currentLevel', level);
            formData.append('score', score);
            if (typeof avisionSettings !== 'undefined' && avisionSettings.nonce) {
                formData.append('nonce', avisionSettings.nonce);
            }
            fetch(ajaxUrl, { method: 'POST', body: formData })
                .then(function(r) { return r.json(); })
                .then(function(resp) {
                    var loader = document.getElementById(loaderId);
                    if (loader && loader.parentNode) loader.parentNode.removeChild(loader);
                    var data = resp && resp.data ? resp.data : resp;
                    if (resp && resp.success && data && data.reply) {
                        UIRenderer.addChatMessage('avi', data.reply);
                        if (data.meta_level_title) {
                            var titleEl = document.getElementById('aviLevelTitle');
                            if (titleEl) titleEl.textContent = data.meta_level_title;
                        }
                    } else {
                        UIRenderer.addChatMessage('avi', (data && data.error) ? data.error : (AvisionState.data.lang === 'fr' ? 'AVI se repose un instant. Réessayez dans quelques secondes.' : 'AVI is resting. Please try again in a few seconds.'));
                    }
                })
                .catch(function() {
                    var loader = document.getElementById(loaderId);
                    if (loader && loader.parentNode) loader.parentNode.removeChild(loader);
                    UIRenderer.addChatMessage('avi', AvisionState.data.lang === 'fr' ? 'AVI se repose un instant. Réessayez dans quelques secondes.' : 'AVI is resting. Please try again in a few seconds.');
                });
        },
        
        handleEnter: function(e) {
            if (e.key === 'Enter') {
                this.sendMessage();
            }
        },
        
        saveAudit: function() {
            var emailInput = document.getElementById('userEmailInput');
            var company = document.getElementById('companyNameDisplay');
            
            if (!emailInput) return;
            
            var email = emailInput.value.trim();
            if (!email || !this.isValidEmail(email)) {
                alert('Please enter a valid email');
                return;
            }
            
            var companyName = company ? company.textContent.trim() : 'Your Business';
            
            APIClient.post('save_audit_email', { email: email, company: companyName })
                .then(function(res) {
                    if (res && res.success) {
                        var inputRow = document.getElementById('emailInputRow');
                        var securedRow = document.getElementById('securedAccountRow');
                        var emailDisplay = document.getElementById('userEmailDisplay');
                        
                        if (inputRow) inputRow.style.display = 'none';
                        if (securedRow) securedRow.style.display = 'flex';
                        if (emailDisplay) emailDisplay.textContent = email;
                        
                        localStorage.setItem('avision_email', email);
                    }
                });
        },
        
        isValidEmail: function(email) {
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
        },
        
        subscribeAlert: function() {
            var emailInput = document.getElementById('notifEmail');
            if (!emailInput) return;
            
            var email = emailInput.value.trim();
            if (email && this.isValidEmail(email)) {
                localStorage.setItem('avision_notification_email', email);
                
                var form = document.getElementById('notifForm');
                var success = document.getElementById('notifSuccess');
                var bell = document.getElementById('notifBell');
                
                if (form) form.style.display = 'none';
                if (success) success.style.display = 'block';
                if (bell) bell.classList.add('active');
            }
        },
        
        handleLockedClick: function(e) {
            console.log('Level is locked');
        },
        
        copyWebmasterEmail: function() {
            var textarea = document.getElementById('emailTemplate');
            if (textarea) {
                textarea.select();
                document.execCommand('copy');
                alert('Email copied to clipboard!');
            }
        },

        createConfetti: function() {
            var colors = ['#3b82f6', '#10b981', '#f59e0b', '#8b5cf6'];
            for (var i = 0; i < 50; i++) {
                var confetti = document.createElement('div');
                confetti.style.cssText = 'position:fixed;width:10px;height:10px;background:' + 
                    colors[Math.floor(Math.random() * colors.length)] + 
                    ';left:' + Math.random() * 100 + 'vw;top:-10px;z-index:9999;border-radius:50%;';
                confetti.style.animation = 'confettiFall 3s ease-out forwards';
                document.body.appendChild(confetti);
                setTimeout(function() { confetti.remove(); }, 3000);
            }
        },

        toggleSwitch: function(el) {
            var options = el.querySelectorAll('.toggle-option');
            options.forEach(function(opt) {
                opt.classList.toggle('active');
            });
        }
    };

    // Add confetti animation styles
    var style = document.createElement('style');
    style.textContent = '@keyframes confettiFall { to { transform: translateY(100vh) rotate(720deg); opacity: 0; } }';
    document.head.appendChild(style);

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            window.AvisionDashboard.init();
        });
    } else {
        window.AvisionDashboard.init();
    }

})();
