
// Configurazione automatica per: WWW.MIOSITO.IT
window.LIVECHAT_DOMAIN_CONFIG = {
    domain: 'www.miosito.it',
    domainId: 'www.miosito.it',
    clientId: 1,
    apiBase: 'https://www.chatservice.it',
    socketUrl: 'https://www.chatservice.it',
    hasOnlineAgents: false,
    chatTitle: 'Assistenza Mio Sito',
    welcomeMessage: 'Ciao! Benvenuto su Mio Sito. Come possiamo aiutarti?',
    offlineMessage: 'I nostri operatori non sono al momento disponibili. Lascia un messaggio e ti ricontatteremo!',
    triggerText: 'Hai bisogno di aiuto?',
    triggerDelay: 30000,
    primaryColor: '#28a745',
    secondaryColor: '#6c757d',
    textColor: '#ffffff',
    borderRadius: 12,
    widgetPosition: 'bottom-right',
    widgetSize: 'medium',
    soundNotifications: true,
    customCSS: ``,
    generated: '2025-11-11T13:23:48.513Z',
    version: '1.0.0'
};

console.log('🟢 Live Chat Widget caricato per:', 'www.miosito.it');

// =====================================================
// LIVE CHAT WIDGET MULTI-TENANT - JavaScript Puro
// =====================================================
// Versione: 1.0.1 - Con Tracking Visitatori e Chat Proattive
// Compatibile: Desktop + Mobile, No iframe, SEO-friendly
// =====================================================

(function() {
    'use strict';
    
    // Configurazione base widget
    const WIDGET_CONFIG = {
        // Questi valori verranno sovrascritti dalle configurazioni del cliente
        apiBase: window.location.origin,
        socketUrl: window.location.origin,
        domain: window.location.hostname,
        version: '1.0.1'
    };
    
    // Variabili globali widget
    let widgetSettings = null;
    let socket = null;
    let visitorId = null;
    let sessionId = null;
    let currentChatId = null;
    let isWidgetLoaded = false;
    let isAgentsOnline = false;
    let triggerTimeout = null;
    let visitorData = {};
    let heartbeatInterval = null;
    let lastPageUrl = window.location.href;
    
    // Inizializzazione widget
    function initWidget() {
        if (isWidgetLoaded) return;
        
        console.log('🚀 Inizializzazione Live Chat Widget v' + WIDGET_CONFIG.version);
        
        // Genera ID univoci
        generateVisitorIds();
        
        // Carica configurazioni dal server
        loadWidgetConfiguration()
            .then(config => {
                widgetSettings = config;
                
                // Rileva e salva informazioni visitatore
                collectVisitorData();
                
                // Registra visitatore sul server
                registerVisitor();
                
                // Crea interfaccia widget
                createWidgetInterface();
                
                // Inizializza connessione Socket.IO
                initializeSocket();
                
                // Avvia trigger automatico se agenti online
                setupTrigger();
                
                // NUOVO: Setup tracking visitatore
                setupVisitorTracking();
                
                isWidgetLoaded = true;
                console.log('✅ Widget caricato con successo');
            })
            .catch(error => {
                console.error('❌ Errore caricamento widget:', error);
                // Carica widget in modalità fallback
                loadFallbackWidget();
            });
    }
    
    // Genera ID univoci per visitatore e sessione
    function generateVisitorIds() {
        // Visitor ID persistente (localStorage)
        visitorId = getStorageItem('livechat_visitor_id');
        if (!visitorId) {
            visitorId = 'visitor_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            setStorageItem('livechat_visitor_id', visitorId);
        }
        
        // Session ID per questa visita
        sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 6);
        setStorageItem('livechat_session_id', sessionId);
    }
    
    // Carica configurazioni widget dal server
    async function loadWidgetConfiguration() {
        try {
            const response = await fetch(`${WIDGET_CONFIG.apiBase}/api/widget/config/${WIDGET_CONFIG.domain}`);
            if (!response.ok) throw new Error(`HTTP ${response.status}`);
            
            const config = await response.json();
            console.log('📋 Configurazioni widget caricate:', config);
            return config;
        } catch (error) {
            console.error('Errore caricamento configurazioni:', error);
            throw error;
        }
    }
    
    // Raccoglie dati visitatore per analytics
    function collectVisitorData() {
        const nav = navigator;
        const screen = window.screen;
        const location = window.location;
        
        visitorData = {
            // Informazioni base
            domain: WIDGET_CONFIG.domain,
            visitorId: visitorId,
            sessionId: sessionId,
            
            // Pagina e navigazione
            currentPage: location.href,
            referrer: document.referrer || 'direct',
            title: document.title,
            
            // Browser e device
            userAgent: nav.userAgent,
            language: nav.language || nav.userLanguage,
            platform: nav.platform,
            cookieEnabled: nav.cookieEnabled,
            
            // Schermo e dispositivo
            screenResolution: `${screen.width}x${screen.height}`,
            windowSize: `${window.innerWidth}x${window.innerHeight}`,
            colorDepth: screen.colorDepth,
            deviceType: detectDeviceType(),
            
            // Timezone
            timezoneOffset: new Date().getTimezoneOffset(),
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            
            // UTM e marketing
            utmSource: getUrlParameter('utm_source'),
            utmMedium: getUrlParameter('utm_medium'),
            utmCampaign: getUrlParameter('utm_campaign'),
            utmTerm: getUrlParameter('utm_term'),
            utmContent: getUrlParameter('utm_content'),
            
            // Timestamp
            timestamp: new Date().toISOString()
        };
    }
    
    // Rileva tipo dispositivo
    function detectDeviceType() {
        const userAgent = navigator.userAgent.toLowerCase();
        const screenWidth = window.screen.width;
        
        if (/tablet|ipad|playbook|silk/.test(userAgent)) {
            return 'tablet';
        }
        if (/mobile|iphone|ipod|android|blackberry|opera|mini|windows\sce|palm|smartphone|iemobile/.test(userAgent)) {
            return 'mobile';
        }
        if (screenWidth < 768) {
            return 'mobile';
        }
        if (screenWidth < 1024) {
            return 'tablet';
        }
        return 'desktop';
    }
    
    // Ottiene parametri URL
    function getUrlParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }
    
    // Registra visitatore sul server con geolocalizzazione
    async function registerVisitor() {
        try {
            // Prima ottieni geolocalizzazione
            const geoData = await getGeolocation();
            
            // Merge dati geo con dati visitatore
            const completeData = {
                ...visitorData,
                ...geoData
            };
            
            // Invia al server
            const response = await fetch(`${WIDGET_CONFIG.apiBase}/api/widget/visitor/register`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(completeData)
            });
            
            if (response.ok) {
                const result = await response.json();
                console.log('✅ Visitatore registrato:', result);
                
                // Salva numero visitatore assegnato dal server
                if (result.visitorNumber) {
                    setStorageItem('livechat_visitor_number', result.visitorNumber);
                }
            }
        } catch (error) {
            console.error('Errore registrazione visitatore:', error);
        }
    }
    
    // Geolocalizzazione tramite IP - VERSIONE HTTPS CORRETTA
    async function getGeolocation() {
        try {
            // Prova prima freeipapi.com (completamente gratuito e HTTPS)
            const response = await fetch('https://freeipapi.com/api/json/');
            if (!response.ok) throw new Error('FreeIPAPI failed');
            
            const data = await response.json();
            if (data && data.countryName) {
                return {
                    ip: data.ipAddress,
                    country: data.countryName,
                    countryCode: data.countryCode,
                    region: data.regionName,
                    city: data.cityName,
                    latitude: data.latitude,
                    longitude: data.longitude,
                    timezone: data.timeZone,
                    isp: data.ispName
                };
            }
        } catch (error) {
            console.log('FreeIPAPI non disponibile, provo backup:', error);
        }
        
        try {
            // Backup: ipapi.co (gratuito, HTTPS, fino a 1000 req/giorno)
            const response = await fetch('https://ipapi.co/json/');
            if (!response.ok) throw new Error('IPAPI.co failed');
            
            const data = await response.json();
            if (data && data.country_name) {
                return {
                    ip: data.ip,
                    country: data.country_name,
                    countryCode: data.country_code,
                    region: data.region,
                    city: data.city,
                    latitude: data.latitude,
                    longitude: data.longitude,
                    timezone: data.timezone,
                    isp: data.org
                };
            }
        } catch (error) {
            console.log('IPAPI.co non disponibile:', error);
        }
        
        // Fallback: nessuna geolocalizzazione
        return {
            ip: 'unknown',
            country: 'Unknown',
            city: 'Unknown'
        };
    }
    
    // NUOVO: Setup tracking visitatore
    function setupVisitorTracking() {
        console.log('📍 Setup tracking visitatore');
        
        // Heartbeat ogni 30 secondi per mantenere visitatore online
        heartbeatInterval = setInterval(() => {
            if (socket && socket.connected) {
                socket.emit('visitor_heartbeat', {
                    visitorId: visitorId,
                    currentPage: window.location.href,
                    timestamp: new Date().toISOString()
                });
            }
        }, 30000);
        
        // Tracking cambio pagina
        setupPageChangeTracking();
        
        // Tracking mouse movement per engagement
        setupEngagementTracking();
    }
    
    // NUOVO: Setup tracking cambio pagina
    function setupPageChangeTracking() {
        // Listener per popstate (torna indietro/avanti)
        window.addEventListener('popstate', function() {
            setTimeout(checkPageChange, 100);
        });
        
        // Monkey patch per pushState e replaceState (SPA)
        const originalPushState = history.pushState;
        const originalReplaceState = history.replaceState;
        
        history.pushState = function() {
            originalPushState.apply(history, arguments);
            setTimeout(checkPageChange, 100);
        };
        
        history.replaceState = function() {
            originalReplaceState.apply(history, arguments);
            setTimeout(checkPageChange, 100);
        };
        
        // Controllo periodico per SPA che non usano history API
        setInterval(checkPageChange, 5000);
    }
    
    // NUOVO: Controlla se la pagina è cambiata
    function checkPageChange() {
        const currentUrl = window.location.href;
        if (currentUrl !== lastPageUrl) {
            console.log('📄 Cambio pagina rilevato:', currentUrl);
            
            lastPageUrl = currentUrl;
            
            // Aggiorna dati visitatore
            visitorData.currentPage = currentUrl;
            visitorData.title = document.title;
            
            // Notifica server via Socket.IO
            if (socket && socket.connected) {
                socket.emit('visitor_page_change', {
                    visitorId: visitorId,
                    newPage: currentUrl,
                    title: document.title,
                    timestamp: new Date().toISOString()
                });
            }
        }
    }
    
    // NUOVO: Setup tracking engagement
    function setupEngagementTracking() {
        let lastActivity = Date.now();
        
        // Tracks mouse, keyboard, scroll activity
        const activityEvents = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
        
        activityEvents.forEach(event => {
            document.addEventListener(event, function() {
                lastActivity = Date.now();
            }, true);
        });
        
        // Controlla inattività ogni 30 secondi
        setInterval(() => {
            const inactiveTime = Date.now() - lastActivity;
            const isInactive = inactiveTime > 60000; // 1 minuto di inattività
            
            // Puoi aggiungere logica per gestire visitatori inattivi
            if (isInactive && socket && socket.connected) {
                socket.emit('visitor_inactive', {
                    visitorId: visitorId,
                    inactiveTime: inactiveTime
                });
            }
        }, 30000);
    }
    
    // Crea interfaccia widget
    function createWidgetInterface() {
        // Rimuovi widget esistente se presente
        const existingWidget = document.getElementById('livechat-widget');
        if (existingWidget) {
            existingWidget.remove();
        }
        
        // Crea CSS dinamico
        injectWidgetStyles();
        
        // Crea HTML widget
        const widgetHtml = createWidgetHTML();
        
        // Inserisci widget nel DOM
        const widgetContainer = document.createElement('div');
        widgetContainer.innerHTML = widgetHtml;
        document.body.appendChild(widgetContainer.firstElementChild);
        
        // Setup event listeners
        setupWidgetEvents();
        
        console.log('🎨 Interfaccia widget creata');
    }
    
    // Inietta stili CSS personalizzati
    function injectWidgetStyles() {
        const styleId = 'livechat-widget-styles';
        let styleElement = document.getElementById(styleId);
        
        if (styleElement) {
            styleElement.remove();
        }
        
        styleElement = document.createElement('style');
        styleElement.id = styleId;
        styleElement.textContent = generateWidgetCSS();
        document.head.appendChild(styleElement);
    }
    
    // Genera CSS personalizzato basato su configurazioni
    function generateWidgetCSS() {
        const settings = widgetSettings || {};
        const primaryColor = settings.primary_color || '#007bff';
        const secondaryColor = settings.secondary_color || '#6c757d';
        const textColor = settings.text_color || '#ffffff';
        const borderRadius = settings.border_radius || 8;
        const position = settings.widget_position || 'bottom-right';
        const size = settings.widget_size || 'medium';
        
        // Calcola dimensioni basate su size
        const sizes = {
            small: { button: '50px', window: '300px' },
            medium: { button: '60px', window: '350px' },
            large: { button: '70px', window: '400px' }
        };
        const currentSize = sizes[size] || sizes.medium;
        
        // Calcola posizione
        const positions = {
            'bottom-right': 'bottom: 20px; right: 20px;',
            'bottom-left': 'bottom: 20px; left: 20px;',
            'bottom-center': 'bottom: 20px; left: 50%; transform: translateX(-50%);'
        };
        const positionCSS = positions[position] || positions['bottom-right'];
        
        return `
            #livechat-widget {
                position: fixed;
                ${positionCSS}
                z-index: 999999;
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                font-size: 14px;
                line-height: 1.4;
            }
            
            .livechat-button {
                width: ${currentSize.button};
                height: ${currentSize.button};
                border-radius: 50%;
                background: linear-gradient(135deg, ${primaryColor} 0%, ${adjustColor(primaryColor, -20)} 100%);
                border: none;
                cursor: pointer;
                box-shadow: 0 4px 20px rgba(0,0,0,0.15);
                display: flex;
                align-items: center;
                justify-content: center;
                color: ${textColor};
                font-size: ${size === 'large' ? '28px' : size === 'small' ? '20px' : '24px'};
                transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                position: relative;
                overflow: hidden;
            }
            
            .livechat-button:hover {
                transform: scale(1.1);
                box-shadow: 0 6px 25px rgba(0,0,0,0.2);
            }
            
            .livechat-button:active {
                transform: scale(0.95);
            }
            
            .livechat-button.has-notification::after {
                content: '';
                position: absolute;
                top: -2px;
                right: -2px;
                width: 12px;
                height: 12px;
                background: #ff4757;
                border-radius: 50%;
                border: 2px solid white;
                animation: pulse 2s infinite;
            }
            
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.2); }
                100% { transform: scale(1); }
            }
            
            .livechat-window {
                position: absolute;
                bottom: calc(${currentSize.button} + 15px);
                right: 0;
                width: ${currentSize.window};
                height: 500px;
                background: white;
                border-radius: ${borderRadius}px;
                box-shadow: 0 10px 40px rgba(0,0,0,0.15);
                display: none;
                flex-direction: column;
                overflow: hidden;
                animation: slideIn 0.3s ease-out;
            }
            
            @keyframes slideIn {
                from {
                    opacity: 0;
                    transform: translateY(20px) scale(0.95);
                }
                to {
                    opacity: 1;
                    transform: translateY(0) scale(1);
                }
            }
            
            .livechat-header {
                background: linear-gradient(135deg, ${primaryColor} 0%, ${adjustColor(primaryColor, -15)} 100%);
                color: ${textColor};
                padding: 15px 20px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-radius: ${borderRadius}px ${borderRadius}px 0 0;
            }
            
            .livechat-header-info h3 {
                margin: 0 0 5px 0;
                font-size: 16px;
                font-weight: 600;
            }
            
            .livechat-header-info p {
                margin: 0;
                font-size: 12px;
                opacity: 0.9;
            }
            
            .livechat-close {
                background: none;
                border: none;
                color: ${textColor};
                font-size: 20px;
                cursor: pointer;
                padding: 0;
                width: 24px;
                height: 24px;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                transition: background 0.2s;
            }
            
            .livechat-close:hover {
                background: rgba(255,255,255,0.2);
            }
            
            .livechat-messages {
                flex: 1;
                padding: 20px;
                overflow-y: auto;
                background: #f8f9fa;
                display: flex;
                flex-direction: column;
                gap: 15px;
            }
            
            .livechat-message {
                max-width: 80%;
                word-wrap: break-word;
            }
            
            .livechat-message.visitor {
                align-self: flex-end;
            }
            
            .livechat-message.agent {
                align-self: flex-start;
            }
            
            .livechat-message.system {
                align-self: center;
                max-width: 90%;
                text-align: center;
                font-style: italic;
                color: #666;
                font-size: 12px;
            }
            
            .livechat-message-bubble {
                padding: 10px 14px;
                border-radius: 18px;
                font-size: 14px;
                line-height: 1.4;
            }
            
            .livechat-message.visitor .livechat-message-bubble {
                background: ${primaryColor};
                color: ${textColor};
                border-bottom-right-radius: 4px;
            }
            
            .livechat-message.agent .livechat-message-bubble {
                background: #e9ecef;
                color: #333;
                border-bottom-left-radius: 4px;
            }
            
            .livechat-message-time {
                font-size: 11px;
                color: #999;
                margin-top: 5px;
            }
            
            .livechat-message.visitor .livechat-message-time {
                text-align: right;
            }
            
            .livechat-typing {
                padding: 10px 20px;
                font-style: italic;
                color: #666;
                font-size: 13px;
                display: none;
            }
            
            .livechat-input-area {
                padding: 15px 20px;
                border-top: 1px solid #e9ecef;
                background: white;
            }
            
            .livechat-input-container {
                display: flex;
                gap: 10px;
                align-items: flex-end;
            }
            
            .livechat-input {
                flex: 1;
                border: 1px solid #ddd;
                border-radius: 20px;
                padding: 10px 15px;
                resize: none;
                max-height: 100px;
                min-height: 40px;
                font-family: inherit;
                font-size: 14px;
                outline: none;
                transition: border-color 0.2s;
            }
            
            .livechat-input:focus {
                border-color: ${primaryColor};
            }
            
            .livechat-send {
                background: ${primaryColor};
                color: ${textColor};
                border: none;
                border-radius: 50%;
                width: 40px;
                height: 40px;
                cursor: pointer;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: all 0.2s;
                font-size: 16px;
            }
            
            .livechat-send:hover {
                background: ${adjustColor(primaryColor, -15)};
                transform: scale(1.05);
            }
            
            .livechat-send:disabled {
                background: #ccc;
                cursor: not-allowed;
                transform: none;
            }
            
            .livechat-offline-form {
                padding: 20px;
                display: none;
                flex-direction: column;
                gap: 15px;
            }
            
            .livechat-form-group {
                display: flex;
                flex-direction: column;
                gap: 5px;
            }
            
            .livechat-form-label {
                font-weight: 600;
                color: #333;
                font-size: 13px;
            }
            
            .livechat-form-input,
            .livechat-form-textarea {
                border: 1px solid #ddd;
                border-radius: 6px;
                padding: 10px 12px;
                font-family: inherit;
                font-size: 14px;
                outline: none;
                transition: border-color 0.2s;
            }
            
            .livechat-form-input:focus,
            .livechat-form-textarea:focus {
                border-color: ${primaryColor};
            }
            
            .livechat-form-textarea {
                min-height: 80px;
                resize: vertical;
            }
            
            .livechat-form-submit {
                background: ${primaryColor};
                color: ${textColor};
                border: none;
                border-radius: 6px;
                padding: 12px 20px;
                font-weight: 600;
                cursor: pointer;
                transition: background 0.2s;
            }
            
            .livechat-form-submit:hover {
                background: ${adjustColor(primaryColor, -15)};
            }
            
            .livechat-status-indicator {
                position: absolute;
                top: -5px;
                right: -5px;
                width: 16px;
                height: 16px;
                border-radius: 50%;
                border: 2px solid white;
                background: #28a745;
            }
            
            .livechat-status-indicator.offline {
                background: #dc3545;
            }
            
            /* NUOVO: Stili per chat proattiva */
            .livechat-proactive-popup {
                position: fixed;
                bottom: 100px;
                right: 20px;
                background: white;
                border-radius: 12px;
                box-shadow: 0 8px 30px rgba(0,0,0,0.15);
                max-width: 280px;
                z-index: 999998;
                animation: slideInProactive 0.5s ease-out;
                border: 1px solid #e0e0e0;
            }
            
            @keyframes slideInProactive {
                from {
                    opacity: 0;
                    transform: translateY(20px) scale(0.9);
                }
                to {
                    opacity: 1;
                    transform: translateY(0) scale(1);
                }
            }
            
            .livechat-proactive-header {
                background: linear-gradient(135deg, ${primaryColor} 0%, ${adjustColor(primaryColor, -15)} 100%);
                color: ${textColor};
                padding: 12px 15px;
                border-radius: 12px 12px 0 0;
                font-size: 14px;
                font-weight: 600;
            }
            
            .livechat-proactive-content {
                padding: 15px;
            }
            
            .livechat-proactive-message {
                font-size: 14px;
                line-height: 1.4;
                margin-bottom: 15px;
                color: #333;
            }
            
            .livechat-proactive-actions {
                display: flex;
                gap: 8px;
            }
            
            .livechat-proactive-btn {
                flex: 1;
                padding: 8px 12px;
                border: none;
                border-radius: 6px;
                font-size: 12px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.2s;
            }
            
            .livechat-proactive-btn.accept {
                background: ${primaryColor};
                color: ${textColor};
            }
            
            .livechat-proactive-btn.accept:hover {
                background: ${adjustColor(primaryColor, -15)};
            }
            
            .livechat-proactive-btn.decline {
                background: #f8f9fa;
                color: #666;
                border: 1px solid #dee2e6;
            }
            
            .livechat-proactive-btn.decline:hover {
                background: #e9ecef;
            }
            
            /* Mobile responsiveness */
            @media (max-width: 480px) {
                .livechat-window {
                    width: calc(100vw - 40px);
                    height: calc(100vh - 100px);
                    bottom: 10px;
                    right: 20px;
                    left: 20px;
                }
                
                #livechat-widget {
                    right: 20px;
                    bottom: 20px;
                }
                
                .livechat-proactive-popup {
                    right: 20px;
                    left: 20px;
                    max-width: none;
                }
            }
            
            /* Custom CSS aggiuntivo */
            ${settings.custom_css || ''}
        `;
    }
    
    // Aggiusta colore per sfumature
    function adjustColor(color, percent) {
        const num = parseInt(color.replace("#", ""), 16);
        const amt = Math.round(2.55 * percent);
        const R = (num >> 16) + amt;
        const G = (num >> 8 & 0x00FF) + amt;
        const B = (num & 0x0000FF) + amt;
        return "#" + (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
            (G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
            (B < 255 ? B < 1 ? 0 : B : 255)).toString(16).slice(1);
    }
    
    // Crea HTML widget
    function createWidgetHTML() {
        const settings = widgetSettings || {};
        const chatTitle = settings.chat_header_text || 'Chat Assistenza';
        const subtitle = settings.welcome_message || 'Siamo qui per aiutarti';
        const offlineMessage = settings.offline_message || 'Lascia un messaggio';
        
        return `
            <div id="livechat-widget">
                <div class="livechat-window" id="livechat-window">
                    <!-- Header Chat -->
                    <div class="livechat-header">
                        <div class="livechat-header-info">
                            <h3>${chatTitle}</h3>
                            <p id="livechat-subtitle">${subtitle}</p>
                        </div>
                        <button class="livechat-close" onclick="window.LiveChat.closeWidget()">×</button>
                    </div>
                    
                    <!-- Area Messaggi -->
                    <div class="livechat-messages" id="livechat-messages">
                        <!-- I messaggi verranno inseriti qui dinamicamente -->
                    </div>
                    
                    <!-- Indicatore "sta scrivendo" -->
                    <div class="livechat-typing" id="livechat-typing">
                        L'operatore sta scrivendo...
                    </div>
                    
                    <!-- Area Input Chat -->
                    <div class="livechat-input-area" id="livechat-chat-input">
                        <div class="livechat-input-container">
                            <textarea 
                                class="livechat-input" 
                                id="livechat-input" 
                                placeholder="Scrivi un messaggio..."
                                rows="1"
                            ></textarea>
                            <button class="livechat-send" id="livechat-send" title="Invia messaggio">
                                <span>→</span>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Form Offline -->
                    <div class="livechat-offline-form" id="livechat-offline-form">
                        <h4 style="margin: 0 0 10px 0; color: #333;">${offlineMessage}</h4>
                        <p style="margin: 0 0 15px 0; color: #666; font-size: 13px;">
                            Compila il form e ti ricontatteremo appena possibile.
                        </p>
                        
                        <div class="livechat-form-group">
                            <label class="livechat-form-label">Nome *</label>
                            <input type="text" class="livechat-form-input" id="offline-name" required>
                        </div>
                        
                        <div class="livechat-form-group">
                            <label class="livechat-form-label">Email *</label>
                            <input type="email" class="livechat-form-input" id="offline-email" required>
                        </div>
                        
                        <div class="livechat-form-group">
                            <label class="livechat-form-label">Telefono</label>
                            <input type="tel" class="livechat-form-input" id="offline-phone">
                        </div>
                        
                        <div class="livechat-form-group">
                            <label class="livechat-form-label">Messaggio *</label>
                            <textarea class="livechat-form-textarea" id="offline-message" required placeholder="Descrivi la tua richiesta..."></textarea>
                        </div>
                        
                        <button type="submit" class="livechat-form-submit" id="offline-submit">
                            Invia Messaggio
                        </button>
                    </div>
                </div>
                
                <!-- Bottone Chat -->
                <button class="livechat-button" id="livechat-button" title="Apri chat">
                    <span id="livechat-button-icon">💬</span>
                    <div class="livechat-status-indicator" id="livechat-status"></div>
                </button>
            </div>
        `;
    }
    
    // Setup event listeners
    function setupWidgetEvents() {
        // Bottone apertura/chiusura
        const button = document.getElementById('livechat-button');
        const window = document.getElementById('livechat-window');
        const input = document.getElementById('livechat-input');
        const sendButton = document.getElementById('livechat-send');
        
        // Click bottone principale
        button.addEventListener('click', toggleWidget);
        
        // Auto-resize textarea
        input.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 100) + 'px';
        });
        
        // Invio messaggio con Enter
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // Bottone invio
        sendButton.addEventListener('click', sendMessage);
        
        // Form offline
        const offlineForm = document.getElementById('offline-submit');
        offlineForm.addEventListener('click', submitOfflineMessage);
        
        // Esponi API globale
        window.LiveChat = {
            openWidget: openWidget,
            closeWidget: closeWidget,
            sendMessage: sendMessageAPI,
            isOpen: () => window.style.display === 'flex',
            // NUOVE API per chat proattive
            acceptProactiveChat: acceptProactiveChat,
            declineProactiveChat: declineProactiveChat
        };
    }
    
    // Toggle apertura/chiusura widget
    function toggleWidget() {
        const window = document.getElementById('livechat-window');
        const isOpen = window.style.display === 'flex';
        
        if (isOpen) {
            closeWidget();
        } else {
            openWidget();
        }
    }
    
    // Apri widget
    function openWidget() {
        const window = document.getElementById('livechat-window');
        const chatInput = document.getElementById('livechat-chat-input');
        const offlineForm = document.getElementById('livechat-offline-form');
        
        window.style.display = 'flex';
        
        // Mostra chat live o form offline basato su stato agenti
        if (isAgentsOnline) {
            chatInput.style.display = 'block';
            offlineForm.style.display = 'none';
            document.getElementById('livechat-input').focus();
            
            // Avvia chat se non già avviata
            if (!currentChatId) {
                startChat();
            }
        } else {
            chatInput.style.display = 'none';
            offlineForm.style.display = 'flex';
            document.getElementById('offline-name').focus();
        }
        
        // Rimuovi notifiche
        const button = document.getElementById('livechat-button');
        button.classList.remove('has-notification');
        
        // Rimuovi popup proattivi se presenti
        const proactivePopup = document.getElementById('livechat-proactive-popup');
        if (proactivePopup) {
            proactivePopup.remove();
        }
    }
    
    // Chiudi widget
    function closeWidget() {
        const window = document.getElementById('livechat-window');
        window.style.display = 'none';
    }
    
    // Inizializza connessione Socket.IO
    function initializeSocket() {
        if (typeof io === 'undefined') {
            console.log('⚠️ Socket.IO non disponibile, modalità polling');
            // Fallback a polling se Socket.IO non disponibile
            setupPollingFallback();
            return;
        }
        
        try {
            socket = io(WIDGET_CONFIG.socketUrl);
            
            socket.on('connect', function() {
                console.log('🔌 Connesso al server chat');
                
                // Registra come visitatore
                socket.emit('visitor_connect', {
                    visitorId: visitorId,
                    sessionId: sessionId,
                    domain: WIDGET_CONFIG.domain,
                    ...visitorData
                });
            });
            
            socket.on('disconnect', function() {
                console.log('🔌 Disconnesso dal server chat');
            });
            
            socket.on('agents_status', function(data) {
                updateAgentsStatus(data.online);
            });
            
            socket.on('chat_started', function(data) {
                currentChatId = data.chatId;
                console.log('💬 Chat avviata:', currentChatId);
            });
            
            socket.on('agent_message', function(data) {
                addMessage(data.message, 'agent', data.agentName);
                showNotification();
            });
            
            socket.on('agent_typing', function() {
                showTypingIndicator();
            });
            
            socket.on('agent_stopped_typing', function() {
                hideTypingIndicator();
            });
            
            socket.on('chat_ended', function() {
                addMessage('La chat è terminata. Grazie per averci contattato!', 'system');
                currentChatId = null;
            });
            
            // NUOVI EVENTI per chat proattive
            socket.on('proactive_chat_started', handleProactiveChatStarted);
            socket.on('proactive_chat_accepted', handleProactiveChatAccepted);
            socket.on('proactive_chat_declined', handleProactiveChatDeclined);
            
        } catch (error) {
            console.error('Errore inizializzazione Socket.IO:', error);
            setupPollingFallback();
        }
    }
    
    // NUOVO: Handler chat proattiva iniziata dall'agente
    function handleProactiveChatStarted(data) {
        console.log('🚀 Chat proattiva ricevuta:', data);
        
        if (data && data.chatId && data.initialMessage) {
            currentChatId = data.chatId;
            
            // Mostra popup chat proattiva
            showProactivePopup(data);
        }
    }
    
    // NUOVO: Mostra popup chat proattiva
    function showProactivePopup(chatData) {
        // Rimuovi popup esistenti
        const existingPopup = document.getElementById('livechat-proactive-popup');
        if (existingPopup) {
            existingPopup.remove();
        }
        
        const agentName = chatData.agentName || 'Assistenza';
        const message = chatData.initialMessage || 'Ciao! Come posso aiutarti?';
        
        const popup = document.createElement('div');
        popup.id = 'livechat-proactive-popup';
        popup.className = 'livechat-proactive-popup';
        popup.innerHTML = `
            <div class="livechat-proactive-header">
                💬 ${agentName}
            </div>
            <div class="livechat-proactive-content">
                <div class="livechat-proactive-message">${message}</div>
                <div class="livechat-proactive-actions">
                    <button class="livechat-proactive-btn accept" onclick="window.LiveChat.acceptProactiveChat()">
                        Rispondi
                    </button>
                    <button class="livechat-proactive-btn decline" onclick="window.LiveChat.declineProactiveChat()">
                        Non ora
                    </button>
                </div>
            </div>
        `;
        
        document.body.appendChild(popup);
        
        // Auto-rimuovi dopo 30 secondi se non interagisce
        setTimeout(() => {
            if (popup.parentElement) {
                declineProactiveChat();
            }
        }, 30000);
        
        playNotificationSound();
    }
    
    // NUOVO: Accetta chat proattiva
    function acceptProactiveChat() {
        console.log('✅ Chat proattiva accettata');
        
        // Rimuovi popup
        const popup = document.getElementById('livechat-proactive-popup');
        if (popup) {
            popup.remove();
        }
        
        // Apri widget e inizia chat
        openWidget();
        
        // Notifica server
        if (socket && socket.connected && currentChatId) {
            socket.emit('accept_proactive_chat', {
                chatId: currentChatId,
                visitorId: visitorId
            });
        }
        
        // Aggiungi messaggio di benvenuto se non presente
        setTimeout(() => {
            const messagesContainer = document.getElementById('livechat-messages');
            if (messagesContainer.children.length === 0) {
                addMessage('Chat avviata. Come posso aiutarti?', 'agent', 'Assistenza');
            }
        }, 500);
    }
    
    // NUOVO: Rifiuta chat proattiva
    function declineProactiveChat() {
        console.log('❌ Chat proattiva rifiutata');
        
        // Rimuovi popup
        const popup = document.getElementById('livechat-proactive-popup');
        if (popup) {
            popup.remove();
        }
        
        // Notifica server
        if (socket && socket.connected && currentChatId) {
            socket.emit('decline_proactive_chat', {
                chatId: currentChatId,
                visitorId: visitorId
            });
        }
        
        // Reset chat ID
        currentChatId = null;
    }
    
    // Handler per eventi chat proattiva
    function handleProactiveChatAccepted(data) {
        console.log('✅ Chat proattiva confermata dal server:', data);
    }
    
    function handleProactiveChatDeclined(data) {
        console.log('❌ Chat proattiva rifiutata confermata dal server:', data);
        currentChatId = null;
    }
    
    // Fallback polling se Socket.IO non disponibile
    function setupPollingFallback() {
        console.log('📡 Modalità polling attivata');
        
        // Controlla stato agenti ogni 30 secondi
        setInterval(checkAgentsStatus, 30000);
        checkAgentsStatus(); // Prima chiamata immediata
        
        // Se in chat, controlla nuovi messaggi ogni 3 secondi
        setInterval(function() {
            if (currentChatId) {
                checkNewMessages();
            }
        }, 3000);
    }
    
    // Controlla stato agenti via API
    async function checkAgentsStatus() {
        try {
            const response = await fetch(`${WIDGET_CONFIG.apiBase}/api/widget/agents-status/${WIDGET_CONFIG.domain}`);
            const data = await response.json();
            updateAgentsStatus(data.online);
        } catch (error) {
            console.error('Errore controllo agenti:', error);
        }
    }
    
    // Controlla nuovi messaggi via API
    async function checkNewMessages() {
        if (!currentChatId) return;
        
        try {
            const response = await fetch(`${WIDGET_CONFIG.apiBase}/api/widget/messages/${currentChatId}?since=${getLastMessageTime()}`);
            const messages = await response.json();
            
            messages.forEach(msg => {
                if (msg.sender_type === 'agent') {
                    addMessage(msg.message, 'agent', msg.agent_name);
                    showNotification();
                }
            });
        } catch (error) {
            console.error('Errore controllo messaggi:', error);
        }
    }
    
    // Aggiorna stato agenti
    function updateAgentsStatus(online) {
        isAgentsOnline = online;
        const statusIndicator = document.getElementById('livechat-status');
        const subtitle = document.getElementById('livechat-subtitle');
        
        if (online) {
            statusIndicator.classList.remove('offline');
            statusIndicator.title = 'Agenti online';
            if (subtitle) {
                subtitle.textContent = widgetSettings?.welcome_message || 'Siamo qui per aiutarti';
            }
        } else {
            statusIndicator.classList.add('offline');
            statusIndicator.title = 'Agenti offline';
            if (subtitle) {
                subtitle.textContent = 'Lascia un messaggio, ti ricontatteremo';
            }
        }
        
        console.log('👥 Agenti online:', online);
    }
    
    // Avvia nuova chat
    async function startChat() {
        try {
            const response = await fetch(`${WIDGET_CONFIG.apiBase}/api/widget/chat/start`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    visitorId: visitorId,
                    sessionId: sessionId,
                    domain: WIDGET_CONFIG.domain,
                    ...visitorData
                })
            });
            
            if (response.ok) {
                const data = await response.json();
                currentChatId = data.chatId;
                
                // Messaggio di benvenuto
                if (widgetSettings?.welcome_message) {
                    addMessage(widgetSettings.welcome_message, 'agent', 'Assistenza');
                }
                
                console.log('💬 Chat avviata:', currentChatId);
            }
        } catch (error) {
            console.error('Errore avvio chat:', error);
        }
    }
    
    // Invia messaggio
    function sendMessage() {
        const input = document.getElementById('livechat-input');
        const message = input.value.trim();
        
        if (!message) return;
        
        // Aggiungi messaggio all'interfaccia
        addMessage(message, 'visitor');
        
        // Pulisci input
        input.value = '';
        input.style.height = 'auto';
        
        // Invia al server
        if (socket && socket.connected) {
            socket.emit('visitor_message', {
                chatId: currentChatId,
                message: message,
                visitorId: visitorId,
                timestamp: new Date().toISOString()
            });
        } else {
            // Fallback API
            sendMessageAPI(message);
        }
    }
    
    // API per invio messaggio
    async function sendMessageAPI(message) {
        try {
            const response = await fetch(`${WIDGET_CONFIG.apiBase}/api/widget/message/send`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    chatId: currentChatId,
                    visitorId: visitorId,
                    message: message,
                    timestamp: new Date().toISOString()
                })
            });
            
            if (!response.ok) {
                throw new Error('Errore invio messaggio');
            }
        } catch (error) {
            console.error('Errore invio messaggio:', error);
            // Mostra errore all'utente
            addMessage('Errore invio messaggio. Riprova.', 'system');
        }
    }
    
    // Aggiungi messaggio alla chat
    function addMessage(text, sender, senderName = null) {
        const messagesContainer = document.getElementById('livechat-messages');
        const messageElement = document.createElement('div');
        const timestamp = new Date().toLocaleTimeString('it-IT', {
            hour: '2-digit',
            minute: '2-digit'
        });
        
        messageElement.className = `livechat-message ${sender}`;
        
        if (sender === 'system') {
            messageElement.innerHTML = `
                <div class="livechat-message-bubble">${text}</div>
            `;
        } else {
            const displayName = sender === 'agent' ? (senderName || 'Assistenza') : 'Tu';
            messageElement.innerHTML = `
                <div class="livechat-message-bubble">${text}</div>
                <div class="livechat-message-time">${displayName} • ${timestamp}</div>
            `;
        }
        
        messagesContainer.appendChild(messageElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
        
        // Salva timestamp ultimo messaggio
        setStorageItem('livechat_last_message', Date.now().toString());
    }
    
    // Ottieni timestamp ultimo messaggio
    function getLastMessageTime() {
        return getStorageItem('livechat_last_message') || '0';
    }
    
    // Mostra indicatore "sta scrivendo"
    function showTypingIndicator() {
        const typingDiv = document.getElementById('livechat-typing');
        typingDiv.style.display = 'block';
        
        const messagesContainer = document.getElementById('livechat-messages');
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
    
    // Nascondi indicatore "sta scrivendo"
    function hideTypingIndicator() {
        const typingDiv = document.getElementById('livechat-typing');
        typingDiv.style.display = 'none';
    }
    
    // Mostra notifica nuovo messaggio
    function showNotification() {
        const window = document.getElementById('livechat-window');
        const button = document.getElementById('livechat-button');
        
        // Se widget chiuso, mostra notifica
        if (window.style.display !== 'flex') {
            button.classList.add('has-notification');
            
            // Notifica sonora (se supportata)
            if (widgetSettings?.sound_notifications) {
                playNotificationSound();
            }
        }
    }
    
    // Suona notifica
    function playNotificationSound() {
        try {
            const audio = new Audio('data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmUaBPZbEQA=');
            audio.volume = 0.3;
            audio.play().catch(() => {}); // Ignora errori
        } catch (e) {}
    }
    
    // Invia messaggio offline
    async function submitOfflineMessage() {
        const name = document.getElementById('offline-name').value.trim();
        const email = document.getElementById('offline-email').value.trim();
        const phone = document.getElementById('offline-phone').value.trim();
        const message = document.getElementById('offline-message').value.trim();
        
        // Validazione base
        if (!name || !email || !message) {
            alert('Compila tutti i campi obbligatori');
            return;
        }
        
        // Validazione email
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            alert('Inserisci un indirizzo email valido');
            return;
        }
        
        try {
            const response = await fetch(`${WIDGET_CONFIG.apiBase}/api/widget/offline-message`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    visitorId: visitorId,
                    domain: WIDGET_CONFIG.domain,
                    name: name,
                    email: email,
                    phone: phone,
                    message: message,
                    ...visitorData
                })
            });
            
            if (response.ok) {
                // Mostra messaggio di successo
                const offlineForm = document.getElementById('livechat-offline-form');
                offlineForm.innerHTML = `
                    <div style="text-align: center; padding: 20px;">
                        <div style="font-size: 48px; margin-bottom: 15px;">✅</div>
                        <h3 style="margin: 0 0 10px 0; color: #28a745;">Messaggio Inviato!</h3>
                        <p style="margin: 0; color: #666; font-size: 14px;">
                            Grazie per averci contattato. Ti risponderemo il prima possibile.
                        </p>
                        <button onclick="window.LiveChat.closeWidget()" 
                                style="margin-top: 15px; background: ${widgetSettings?.primary_color || '#007bff'}; 
                                       color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer;">
                            Chiudi
                        </button>
                    </div>
                `;
                
                console.log('📧 Messaggio offline inviato');
            } else {
                throw new Error('Errore invio');
            }
        } catch (error) {
            console.error('Errore invio messaggio offline:', error);
            alert('Errore durante l\'invio. Riprova più tardi.');
        }
    }
    
    // Setup trigger automatico
    function setupTrigger() {
        const triggerDelay = (widgetSettings?.trigger_delay_seconds || 30) * 1000;
        
        // Solo se agenti online
        if (!isAgentsOnline) return;
        
        // Solo se non è già stato mostrato in questa sessione
        const hasTriggered = getStorageItem('livechat_triggered_session') === sessionId;
        if (hasTriggered) return;
        
        triggerTimeout = setTimeout(() => {
            // Verifica che widget non sia già aperto
            const window = document.getElementById('livechat-window');
            if (window && window.style.display !== 'flex') {
                showTrigger();
                setStorageItem('livechat_triggered_session', sessionId);
            }
        }, triggerDelay);
    }
    
    // Mostra trigger automatico
    function showTrigger() {
        const button = document.getElementById('livechat-button');
        const triggerText = widgetSettings?.testo_trigger || 'Serve aiuto?';
        
        // Anima bottone
        button.classList.add('has-notification');
        
        // Crea popup trigger
        const triggerPopup = document.createElement('div');
        triggerPopup.id = 'livechat-trigger-popup';
        triggerPopup.innerHTML = `
            <div style="position: absolute; bottom: calc(100% + 10px); right: 0; 
                        background: white; padding: 15px; border-radius: 8px; 
                        box-shadow: 0 4px 20px rgba(0,0,0,0.15); max-width: 250px;
                        border: 1px solid #e0e0e0;">
                <div style="font-weight: 600; margin-bottom: 8px; color: #333;">${triggerText}</div>
                <div style="font-size: 13px; color: #666; margin-bottom: 12px;">
                    ${widgetSettings?.welcome_message || 'Come possiamo aiutarti?'}
                </div>
                <div style="display: flex; gap: 8px;">
                    <button onclick="window.LiveChat.openWidget(); this.parentElement.parentElement.parentElement.remove();"
                            style="background: ${widgetSettings?.primary_color || '#007bff'}; color: white; 
                                   border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; 
                                   font-size: 12px; flex: 1;">
                        Inizia Chat
                    </button>
                    <button onclick="this.parentElement.parentElement.parentElement.remove();"
                            style="background: #f8f9fa; color: #666; border: 1px solid #dee2e6; 
                                   padding: 8px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                        ×
                    </button>
                </div>
                <div style="position: absolute; bottom: -8px; right: 20px; width: 0; height: 0; 
                           border-left: 8px solid transparent; border-right: 8px solid transparent; 
                           border-top: 8px solid white;"></div>
            </div>
        `;
        
        document.getElementById('livechat-widget').appendChild(triggerPopup);
        
        // Auto-rimuovi dopo 10 secondi
        setTimeout(() => {
            if (triggerPopup.parentElement) {
                triggerPopup.remove();
            }
        }, 10000);
        
        console.log('🎯 Trigger automatico mostrato');
    }
    
    // Widget fallback per errori
    function loadFallbackWidget() {
        console.log('🆘 Caricamento widget fallback');
        
        // Configurazione minimal
        widgetSettings = {
            chat_header_text: 'Chat Assistenza',
            welcome_message: 'Ciao! Come possiamo aiutarti?',
            offline_message: 'Lascia un messaggio',
            primary_color: '#007bff',
            secondary_color: '#6c757d',
            text_color: '#ffffff',
            border_radius: 8,
            widget_position: 'bottom-right',
            widget_size: 'medium',
            trigger_delay_seconds: 30,
            sound_notifications: true
        };
        
        // Crea interfaccia
        createWidgetInterface();
        
        // Stato offline
        updateAgentsStatus(false);
        
        // Setup tracking anche in modalità fallback
        setupVisitorTracking();
        
        isWidgetLoaded = true;
        console.log('✅ Widget fallback caricato');
    }
    
    // Utilità localStorage sicura
    function getStorageItem(key) {
        try {
            return localStorage.getItem(key);
        } catch (e) {
            return null;
        }
    }
    
    function setStorageItem(key, value) {
        try {
            localStorage.setItem(key, value);
        } catch (e) {
            // Ignora errori localStorage
        }
    }
    
    // Cleanup al cambio pagina
    window.addEventListener('beforeunload', function() {
        if (socket && socket.connected) {
            socket.emit('visitor_disconnect', {
                visitorId: visitorId,
                sessionId: sessionId
            });
        }
        
        // Cleanup intervals
        if (heartbeatInterval) {
            clearInterval(heartbeatInterval);
        }
        if (triggerTimeout) {
            clearTimeout(triggerTimeout);
        }
    });
    
    // Inizializzazione automatica quando DOM è pronto
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initWidget);
    } else {
        // DOM già pronto
        setTimeout(initWidget, 100);
    }
    
})();

// =====================================================
// FINE WIDGET LIVE CHAT MULTI-TENANT CON TRACKING
// =====================================================