<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Template: Mode Gardien
 * Interface de gestion du Mode Gardien d'AVI
 */
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mode Gardien - AVI</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 40px 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            background: white;
            border-radius: 20px;
            padding: 40px;
            margin-bottom: 30px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 36px;
            color: #1a1a1a;
            margin-bottom: 10px;
        }
        
        .header .subtitle {
            font-size: 18px;
            color: #666;
        }
        
        .status-badge {
            display: inline-block;
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 600;
            font-size: 14px;
            margin-top: 20px;
        }
        
        .status-badge.active {
            background: #10b981;
            color: white;
        }
        
        .status-badge.inactive {
            background: #ef4444;
            color: white;
        }
        
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .card {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.1);
        }
        
        .card h2 {
            font-size: 24px;
            color: #1a1a1a;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .card .icon {
            font-size: 32px;
        }
        
        .stat-value {
            font-size: 48px;
            font-weight: 800;
            color: #667eea;
            margin: 20px 0;
        }
        
        .stat-label {
            font-size: 14px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .settings-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .form-group label {
            font-weight: 600;
            color: #1a1a1a;
            font-size: 14px;
        }
        
        .form-group input,
        .form-group select {
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            transition: all 0.3s;
        }
        
        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .toggle-switch {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .switch {
            position: relative;
            width: 50px;
            height: 26px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: #10b981;
        }
        
        input:checked + .slider:before {
            transform: translateX(24px);
        }
        
        .btn {
            padding: 14px 32px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            font-family: 'Inter', sans-serif;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }
        
        .btn-danger {
            background: #ef4444;
            color: white;
        }
        
        .btn-danger:hover {
            background: #dc2626;
        }
        
        .reviews-list {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .review-item {
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 20px;
            transition: all 0.3s;
        }
        
        .review-item:hover {
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
        }
        
        .review-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }
        
        .reviewer-name {
            font-weight: 600;
            color: #1a1a1a;
        }
        
        .stars {
            color: #fbbf24;
            font-size: 18px;
        }
        
        .review-text {
            color: #666;
            font-style: italic;
            margin-bottom: 12px;
            padding: 12px;
            background: #f9fafb;
            border-radius: 8px;
        }
        
        .response-text {
            color: #1a1a1a;
            padding: 12px;
            background: #ecfdf5;
            border-radius: 8px;
            border-left: 4px solid #10b981;
        }
        
        .response-meta {
            display: flex;
            gap: 20px;
            margin-top: 8px;
            font-size: 12px;
            color: #666;
        }
        
        .workflow-steps {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .workflow-step {
            display: flex;
            gap: 16px;
            align-items: flex-start;
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            flex-shrink: 0;
        }
        
        .step-content h3 {
            font-size: 16px;
            color: #1a1a1a;
            margin-bottom: 4px;
        }
        
        .step-content p {
            font-size: 14px;
            color: #666;
        }
        
        .alert {
            padding: 16px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .alert-info {
            background: #dbeafe;
            color: #1e40af;
            border-left: 4px solid #3b82f6;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }
        
        .webhook-url {
            background: #f9fafb;
            padding: 12px 16px;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            word-break: break-all;
            margin-top: 12px;
            border: 1px solid #e5e7eb;
        }
        
        /* Guardian Status Panel (Level 15) */
        .guardian-status-panel {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 30px;
            color: white;
            margin-bottom: 30px;
        }
        
        .guardian-status-panel h2 {
            color: white;
            margin-bottom: 20px;
        }
        
        .status-indicator {
            display: flex;
            align-items: center;
            gap: 15px;
            background: rgba(255,255,255,0.15);
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        
        .status-indicator .status-icon {
            font-size: 48px;
        }
        
        .status-indicator .status-details h3 {
            font-size: 24px;
            margin-bottom: 5px;
        }
        
        .status-indicator .status-details p {
            opacity: 0.9;
        }
        
        .last-response-card {
            background: rgba(255,255,255,0.1);
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        
        .last-response-card h4 {
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 1px;
            opacity: 0.8;
            margin-bottom: 10px;
        }
        
        .last-response-card .response-summary {
            font-size: 16px;
            line-height: 1.6;
        }
        
        .last-response-card .response-time {
            margin-top: 10px;
            font-size: 13px;
            opacity: 0.8;
        }
        
        .protocol-badges {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        
        .protocol-badge {
            background: rgba(255,255,255,0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .google-maps-link {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: white;
            color: #667eea;
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .google-maps-link:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        /* Rating distribution */
        .rating-distribution {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        .rating-bar {
            flex: 1;
            text-align: center;
        }
        
        .rating-bar .bar {
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 8px;
            position: relative;
            overflow: hidden;
        }
        
        .rating-bar .bar-fill {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: #10b981;
            border-radius: 8px;
            transition: height 0.5s ease;
        }
        
        .rating-bar .bar-label {
            margin-top: 8px;
            font-size: 12px;
            opacity: 0.9;
        }
        
        /* Alert card for flagged reviews */
        .alert-warning {
            background: #fef3c7;
            color: #92400e;
            border-left: 4px solid #f59e0b;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- En-tête -->
        <div class="header">
            <h1>🤖 Mode Gardien</h1>
            <p class="subtitle">AVI gère vos avis Google automatiquement, 24/7</p>
            <span class="status-badge" id="status-badge">
                <span id="status-text">Chargement...</span>
            </span>
        </div>

        <!-- Panneau de Statut Level 15 -->
        <div class="guardian-status-panel" id="guardian-status-panel">
            <h2>🛡️ Statut du Mode Gardien</h2>
            
            <div class="status-indicator">
                <div class="status-icon" id="guardian-icon">🛡️</div>
                <div class="status-details">
                    <h3 id="guardian-status-label">Mode Gardien Actif</h3>
                    <p id="guardian-status-desc">AVI répond automatiquement à vos avis Google</p>
                </div>
            </div>
            
            <div class="last-response-card" id="last-response-card">
                <h4>📝 Dernière Réponse Automatique</h4>
                <div class="response-summary" id="last-response-summary">
                    Chargement...
                </div>
                <div class="response-time" id="last-response-time"></div>
            </div>
            
            <div class="protocol-badges">
                <div class="protocol-badge" title="Pour les avis 4-5 étoiles">
                    🌟 Protocole Ambassadeur
                </div>
                <div class="protocol-badge" title="Pour les avis 1-2 étoiles">
                    🛡️ Protocole Riposte Stratégique
                </div>
                <div class="protocol-badge" title="Variation automatique">
                    🎲 Température 0.7
                </div>
            </div>
            
            <div style="margin-top: 20px;">
                <a href="https://business.google.com" target="_blank" class="google-maps-link">
                    📍 Voir sur Google Maps
                </a>
            </div>
            
            <!-- Distribution des notes -->
            <div style="margin-top: 25px;">
                <h4 style="font-size: 14px; text-transform: uppercase; letter-spacing: 1px; opacity: 0.8; margin-bottom: 15px;">Distribution des Avis</h4>
                <div class="rating-distribution" id="rating-distribution">
                    <div class="rating-bar">
                        <div class="bar"><div class="bar-fill" id="bar-5" style="height: 0%;"></div></div>
                        <div class="bar-label">5⭐</div>
                    </div>
                    <div class="rating-bar">
                        <div class="bar"><div class="bar-fill" id="bar-4" style="height: 0%;"></div></div>
                        <div class="bar-label">4⭐</div>
                    </div>
                    <div class="rating-bar">
                        <div class="bar"><div class="bar-fill" id="bar-3" style="height: 0%; background: #f59e0b;"></div></div>
                        <div class="bar-label">3⭐</div>
                    </div>
                    <div class="rating-bar">
                        <div class="bar"><div class="bar-fill" id="bar-2" style="height: 0%; background: #ef4444;"></div></div>
                        <div class="bar-label">2⭐</div>
                    </div>
                    <div class="rating-bar">
                        <div class="bar"><div class="bar-fill" id="bar-1" style="height: 0%; background: #ef4444;"></div></div>
                        <div class="bar-label">1⭐</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Statistiques -->
        <div class="grid">
            <div class="card">
                <h2><span class="icon">📊</span> Avis Traités</h2>
                <div class="stat-value" id="total-reviews">0</div>
                <div class="stat-label">Total des avis</div>
            </div>

            <div class="card">
                <h2><span class="icon">⚡</span> Temps de Réponse</h2>
                <div class="stat-value" id="avg-response-time">0</div>
                <div class="stat-label">Minutes en moyenne</div>
            </div>

            <div class="card">
                <h2><span class="icon">⭐</span> Note Moyenne</h2>
                <div class="stat-value" id="avg-rating">0.0</div>
                <div class="stat-label">Sur 5 étoiles</div>
            </div>
        </div>

        <!-- Configuration -->
        <div class="card">
            <h2><span class="icon">⚙️</span> Configuration</h2>
            
            <div class="alert alert-info">
                <strong>💡 Comment ça marche ?</strong><br>
                Le Mode Gardien analyse automatiquement chaque avis Google reçu, génère une réponse personnalisée et la publie en moins d'une heure. Vous recevez une notification par email pour chaque réponse.
            </div>

            <form class="settings-form" id="guardian-settings-form">
                <div class="form-group">
                    <label>ID de votre fiche Google Business</label>
                    <input type="text" id="google-location-id" placeholder="accounts/123456789/locations/987654321" required>
                    <small style="color: #666;">Trouvez votre ID dans Google Business Profile Manager</small>
                </div>

                <div class="form-group">
                    <label>Token d'accès Google API</label>
                    <input type="password" id="google-access-token" placeholder="ya29.a0AfH6SMB..." required>
                    <small style="color: #666;">Générez un token OAuth 2.0 depuis Google Cloud Console</small>
                </div>

                <div class="form-group">
                    <label>Ton de voix</label>
                    <select id="tone-of-voice">
                        <option value="professional">Professionnel</option>
                        <option value="friendly">Amical</option>
                        <option value="casual">Décontracté</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Délai de réponse (minutes)</label>
                    <input type="number" id="response-delay" value="60" min="1" max="1440">
                    <small style="color: #666;">Temps d'attente avant publication (cible : moins de 60 min)</small>
                </div>

                <div class="form-group">
                    <div class="toggle-switch">
                        <label class="switch">
                            <input type="checkbox" id="auto-respond" checked>
                            <span class="slider"></span>
                        </label>
                        <label for="auto-respond">Réponse automatique</label>
                    </div>
                </div>

                <div class="form-group">
                    <div class="toggle-switch">
                        <label class="switch">
                            <input type="checkbox" id="include-seo" checked>
                            <span class="slider"></span>
                        </label>
                        <label for="include-seo">Optimisation SEO</label>
                    </div>
                </div>

                <div class="form-group">
                    <div class="toggle-switch">
                        <label class="switch">
                            <input type="checkbox" id="notification-email" checked>
                            <span class="slider"></span>
                        </label>
                        <label for="notification-email">Notifications par email</label>
                    </div>
                </div>

                <div style="display: flex; gap: 12px;">
                    <button type="submit" class="btn btn-primary" id="activate-btn">
                        🚀 Activer le Mode Gardien
                    </button>
                    <button type="button" class="btn btn-danger" id="deactivate-btn" style="display: none;">
                        ⏸️ Désactiver
                    </button>
                </div>
            </form>

            <div id="webhook-info" style="display: none; margin-top: 20px;">
                <div class="alert alert-success">
                    <strong>✅ Mode Gardien activé !</strong><br>
                    Configurez ce webhook dans Google Business Profile API :
                    <div class="webhook-url" id="webhook-url"></div>
                </div>
            </div>
        </div>

        <!-- Workflow -->
        <div class="card">
            <h2><span class="icon">🔄</span> Workflow Automatique</h2>
            <div class="workflow-steps">
                <div class="workflow-step">
                    <div class="step-number">1</div>
                    <div class="step-content">
                        <h3>Réception</h3>
                        <p>AVI reçoit l'avis via webhook Google en temps réel</p>
                    </div>
                </div>
                <div class="workflow-step">
                    <div class="step-number">2</div>
                    <div class="step-content">
                        <h3>Scan Stars</h3>
                        <p>Identification du nombre d'étoiles pour définir le ton</p>
                    </div>
                </div>
                <div class="workflow-step">
                    <div class="step-number">3</div>
                    <div class="step-content">
                        <h3>Analyse NLP</h3>
                        <p>Extraction du contexte, sentiment et mots-clés</p>
                    </div>
                </div>
                <div class="workflow-step">
                    <div class="step-number">4</div>
                    <div class="step-content">
                        <h3>Rédaction</h3>
                        <p>Génération d'une réponse personnalisée et optimisée SEO</p>
                    </div>
                </div>
                <div class="workflow-step">
                    <div class="step-number">5</div>
                    <div class="step-content">
                        <h3>Publication</h3>
                        <p>Publication automatique sur votre fiche Google</p>
                    </div>
                </div>
                <div class="workflow-step">
                    <div class="step-number">6</div>
                    <div class="step-content">
                        <h3>Rapport</h3>
                        <p>Notification email avec la réponse générée</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Avis récents -->
        <div class="card">
            <h2><span class="icon">💬</span> Avis Récents</h2>
            <div class="reviews-list" id="reviews-list">
                <p style="color: #666; text-align: center; padding: 40px;">
                    Aucun avis traité pour le moment
                </p>
            </div>
        </div>
    </div>

    <script>
        // Configuration
        const auditId = new URLSearchParams(window.location.search).get('audit_id') || '1';
        const apiUrl = '/wp-json/avision/v1';
        const wpRestNonce = <?php echo wp_json_encode( function_exists( 'wp_create_nonce' ) ? wp_create_nonce( 'wp_rest' ) : '' ); ?>;
        function aviGuardianFetch(url, options) {
            const o = Object.assign({ credentials: 'include' }, options || {});
            const h = new Headers(o.headers || undefined);
            if (wpRestNonce) h.set('X-WP-Nonce', wpRestNonce);
            o.headers = h;
            return fetch(url, o);
        }
        
        // Charger les données au démarrage
        document.addEventListener('DOMContentLoaded', () => {
            loadGuardianStatus();
            loadStatistics();
            loadReviews();
            loadDashboardPanel();
        });
        
        // Charger le statut du Mode Gardien
        async function loadGuardianStatus() {
            try {
                const response = await aviGuardianFetch(`${apiUrl}/guardian/status?audit_id=${auditId}`);
                const data = await response.json();
                
                if (data.success && data.is_active) {
                    document.getElementById('status-badge').className = 'status-badge active';
                    document.getElementById('status-text').textContent = '✅ Actif';
                    document.getElementById('activate-btn').style.display = 'none';
                    document.getElementById('deactivate-btn').style.display = 'block';
                    document.getElementById('webhook-info').style.display = 'block';
                    document.getElementById('webhook-url').textContent = data.webhook_url;
                    
                    // Mettre à jour le panneau Level 15
                    document.getElementById('guardian-icon').textContent = '🛡️';
                    document.getElementById('guardian-status-label').textContent = 'Mode Gardien Actif';
                    document.getElementById('guardian-status-desc').textContent = 'AVI répond automatiquement à vos avis Google';
                    document.getElementById('guardian-status-panel').style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
                } else {
                    document.getElementById('status-badge').className = 'status-badge inactive';
                    document.getElementById('status-text').textContent = '⏸️ Inactif';
                    
                    // Mettre à jour le panneau Level 15
                    document.getElementById('guardian-icon').textContent = '⏸️';
                    document.getElementById('guardian-status-label').textContent = 'Mode Gardien Inactif';
                    document.getElementById('guardian-status-desc').textContent = 'Activez le Mode Gardien pour répondre automatiquement';
                    document.getElementById('guardian-status-panel').style.background = 'linear-gradient(135deg, #6b7280 0%, #4b5563 100%)';
                }
            } catch (error) {
                console.error('Error loading status:', error);
            }
        }
        
        // Charger les statistiques et mettre à jour le panneau
        async function loadStatistics() {
            try {
                const response = await aviGuardianFetch(`${apiUrl}/guardian/stats?audit_id=${auditId}`);
                const data = await response.json();
                
                if (data.success) {
                    const stats = data.statistics;
                    document.getElementById('total-reviews').textContent = stats.total_reviews || 0;
                    document.getElementById('avg-response-time').textContent = 
                        Math.round(stats.avg_response_time_minutes || 0);
                    
                    // Calculer la note moyenne
                    const totalStars = (stats.reviews_5_stars * 5) + 
                                      (stats.reviews_4_stars * 4) + 
                                      (stats.reviews_3_stars * 3) + 
                                      (stats.reviews_2_stars * 2) + 
                                      (stats.reviews_1_star * 1);
                    const avgRating = stats.total_reviews > 0 ? 
                                     (totalStars / stats.total_reviews).toFixed(1) : 0;
                    document.getElementById('avg-rating').textContent = avgRating;
                    
                    // Mettre à jour la distribution des notes (barres visuelles)
                    updateRatingDistribution(stats);
                }
            } catch (error) {
                console.error('Error loading statistics:', error);
            }
        }
        
        // Mettre à jour la distribution des notes
        function updateRatingDistribution(stats) {
            const total = stats.total_reviews || 1; // Éviter division par 0
            
            const ratings = {
                5: stats.reviews_5_stars || 0,
                4: stats.reviews_4_stars || 0,
                3: stats.reviews_3_stars || 0,
                2: stats.reviews_2_stars || 0,
                1: stats.reviews_1_star || 0
            };
            
            // Trouver le max pour normaliser
            const maxCount = Math.max(...Object.values(ratings), 1);
            
            for (let star = 1; star <= 5; star++) {
                const percentage = (ratings[star] / maxCount) * 100;
                const bar = document.getElementById(`bar-${star}`);
                if (bar) {
                    bar.style.height = `${percentage}%`;
                }
            }
        }
        
        // Charger le panneau Dashboard (Level 15) avec historique
        async function loadDashboardPanel() {
            try {
                const response = await aviGuardianFetch(`${apiUrl}/reviews?audit_id=${auditId}&limit=1`);
                const data = await response.json();
                
                if (data.success && data.reviews && data.reviews.length > 0) {
                    const lastReview = data.reviews[0];
                    
                    // Calculer le temps écoulé
                    const responseTime = new Date(lastReview.response_published_at || lastReview.created_at);
                    const timeAgo = getTimeAgo(responseTime);
                    
                    // Créer le résumé
                    const reviewType = getReviewType(lastReview.rating);
                    const summary = `Dernière réponse automatique générée ${timeAgo} (${lastReview.rating}⭐ - ${reviewType})`;
                    
                    document.getElementById('last-response-summary').textContent = summary;
                    
                    // Ajouter les détails
                    const details = `
                        <div style="margin-top: 10px; font-size: 14px; opacity: 0.9;">
                            <strong>Avis de ${lastReview.reviewer_name}:</strong> 
                            "${(lastReview.review_text || 'Sans commentaire').substring(0, 80)}..."
                        </div>
                    `;
                    document.getElementById('last-response-time').innerHTML = details;
                    
                } else {
                    document.getElementById('last-response-summary').textContent = 
                        'Aucune réponse automatique générée pour le moment';
                    document.getElementById('last-response-time').innerHTML = 
                        '<span style="opacity: 0.7;">Activez le Mode Gardien pour commencer</span>';
                }
            } catch (error) {
                console.error('Error loading dashboard panel:', error);
                document.getElementById('last-response-summary').textContent = 
                    'En attente de données...';
            }
        }
        
        // Fonction utilitaire: calcul du temps écoulé
        function getTimeAgo(date) {
            const now = new Date();
            const diff = now - date;
            const minutes = Math.floor(diff / 60000);
            const hours = Math.floor(diff / 3600000);
            const days = Math.floor(diff / 86400000);
            
            if (minutes < 1) return 'à l\'instant';
            if (minutes < 60) return `il y a ${minutes} minute${minutes > 1 ? 's' : ''}`;
            if (hours < 24) return `il y a ${hours} heure${hours > 1 ? 's' : ''}`;
            return `il y a ${days} jour${days > 1 ? 's' : ''}`;
        }
        
        // Fonction utilitaire: type d'avis selon les étoiles
        function getReviewType(rating) {
            const types = {
                5: 'Client très satisfait',
                4: 'Client satisfait',
                3: 'Avis mitigé',
                2: 'Client mécontent',
                1: 'Client très mécontent'
            };
            return types[rating] || 'Avis';
        }
        
        // Charger les avis récents
        async function loadReviews() {
            try {
                const response = await aviGuardianFetch(`${apiUrl}/reviews?audit_id=${auditId}&limit=5`);
                const data = await response.json();
                
                if (data.success && data.reviews && data.reviews.length > 0) {
                    const reviewsList = document.getElementById('reviews-list');
                    reviewsList.innerHTML = data.reviews.map(review => {
                        // Déterminer le protocole utilisé
                        const protocol = review.protocol_used || (review.rating >= 4 ? 'ambassador' : (review.rating <= 2 ? 'strategic' : 'standard'));
                        const protocolLabel = protocol === 'ambassador' ? '🌟 Ambassadeur' : 
                                             (protocol === 'strategic_response' || protocol === 'strategic' ? '🛡️ Riposte' : '📝 Standard');
                        
                        // Déterminer le statut
                        const status = review.response_published ? '✅ Publié' : 
                                      (review.status === 'flagged' ? '⚠️ Signalé' : '⏳ En attente');
                        
                        const responseTime = review.response_time_seconds ? 
                                            Math.round(review.response_time_seconds / 60) : 0;
                        
                        return `
                            <div class="review-item" style="border-left: 4px solid ${review.rating >= 4 ? '#10b981' : (review.rating <= 2 ? '#ef4444' : '#f59e0b')};">
                                <div class="review-header">
                                    <span class="reviewer-name">${review.reviewer_name || 'Anonyme'}</span>
                                    <span class="stars">${'⭐'.repeat(review.rating)}${'☆'.repeat(5-review.rating)}</span>
                                </div>
                                <div class="review-text">"${review.review_text || '(Avis sans commentaire)'}"</div>
                                ${review.response_text ? `<div class="response-text">${review.response_text}</div>` : ''}
                                <div class="response-meta">
                                    <span>${status}</span>
                                    <span>⏱️ ${responseTime} min</span>
                                    <span>${protocolLabel}</span>
                                    ${review.response_published_at ? 
                                        `<span>📅 ${new Date(review.response_published_at).toLocaleDateString('fr-FR')}</span>` : ''}
                                </div>
                            </div>
                        `;
                    }).join('');
                } else {
                    document.getElementById('reviews-list').innerHTML = `
                        <p style="color: #666; text-align: center; padding: 40px;">
                            Aucun avis traité pour le moment.<br>
                            <small>Les avis apparaîtront ici une fois le Mode Gardien activé.</small>
                        </p>
                    `;
                }
            } catch (error) {
                console.error('Error loading reviews:', error);
            }
        }
        
        // Activer le Mode Gardien
        document.getElementById('guardian-settings-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData();
            formData.append('action', 'activate_guardian');
            formData.append('audit_id', auditId);
            formData.append('google_location_id', document.getElementById('google-location-id').value);
            formData.append('google_access_token', document.getElementById('google-access-token').value);
            formData.append('tone_of_voice', document.getElementById('tone-of-voice').value);
            formData.append('response_delay', document.getElementById('response-delay').value);
            formData.append('auto_respond', document.getElementById('auto-respond').checked);
            formData.append('include_seo', document.getElementById('include-seo').checked);
            formData.append('notification_email', document.getElementById('notification-email').checked);
            
            try {
                const response = await aviGuardianFetch(apiUrl, {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('✅ Mode Gardien activé avec succès !');
                    loadGuardianStatus();
                    document.getElementById('webhook-url').textContent = data.webhook_url;
                } else {
                    alert('❌ Erreur: ' + (data.error || 'Unknown error'));
                }
            } catch (error) {
                alert('❌ Erreur de connexion');
                console.error(error);
            }
        });
        
        // Désactiver le Mode Gardien
        document.getElementById('deactivate-btn').addEventListener('click', async () => {
            if (!confirm('Êtes-vous sûr de vouloir désactiver le Mode Gardien ?')) {
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'deactivate_guardian');
            formData.append('audit_id', auditId);
            
            try {
                const response = await aviGuardianFetch(apiUrl, {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('✅ Mode Gardien désactivé');
                    location.reload();
                }
            } catch (error) {
                alert('❌ Erreur de connexion');
                console.error(error);
            }
        });
    </script>
</body>
</html>
