<!-- includes/assistant.php (Localhost version) -->
<style>
/* ── Βοηθός CRM (Smart Assistant) Styles ── */
#crm-assistant-btn {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background: var(--gp-primary, #0d6efd);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    cursor: pointer;
    z-index: 9999;
    transition: transform 0.2s, background 0.2s;
    border: none;
}
#crm-assistant-btn:hover {
    transform: scale(1.1);
    background: var(--gp-primary-dark, #0b5ed7);
}
#crm-assistant-badge {
    position: absolute;
    top: 0;
    right: 0;
    background: #dc3545;
    color: white;
    font-size: 12px;
    font-weight: bold;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    display: none; /* hidden by default */
}
#crm-assistant-panel {
    position: fixed;
    bottom: 90px;
    right: 20px;
    width: 320px;
    background: var(--gp-card-bg, #fff);
    border: 1px solid var(--gp-card-border, #e0e0e0);
    border-radius: 12px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.15);
    z-index: 9998;
    display: none; /* hidden by default */
    flex-direction: column;
    overflow: hidden;
    backdrop-filter: blur(16px);
}
#crm-assistant-panel.open {
    display: flex;
}
.assistant-header {
    background: var(--gp-primary, #0d6efd);
    color: white;
    padding: 12px 16px;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.assistant-close {
    cursor: pointer;
    font-size: 18px;
}
.assistant-body {
    padding: 16px;
    max-height: 300px;
    overflow-y: auto;
    color: var(--gp-text, #333);
}
.assistant-item {
    display: flex;
    align-items: flex-start;
    gap: 12px;
    padding: 10px 0;
    border-bottom: 1px solid var(--gp-card-border, #eee);
    text-decoration: none;
    color: inherit;
    transition: background 0.15s;
}
.assistant-item:hover {
    background: rgba(0,0,0,0.02);
}
.assistant-item:last-child {
    border-bottom: none;
}
.assistant-icon {
    font-size: 20px;
}
.assistant-text strong {
    display: block;
    font-size: 14px;
    margin-bottom: 2px;
}
.assistant-text span {
    font-size: 12px;
    color: var(--gp-muted, #666);
}
.assistant-controls {
    padding: 12px;
    border-top: 1px solid var(--gp-card-border, #e0e0e0);
    display: flex;
    justify-content: center;
    background: rgba(0,0,0,0.02);
}
#assistant-voice-btn {
    background: #10b981;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 20px;
    cursor: pointer;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: background 0.2s;
}
#assistant-voice-btn:hover {
    background: #059669;
}
#assistant-voice-btn.listening {
    background: #ef4444;
    animation: pulse 1.5s infinite;
}
@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}
</style>

<!-- Το Κουμπί του Βοηθού -->
<button id="crm-assistant-btn" aria-label="Smart Assistant">
    🤖
    <div id="crm-assistant-badge">0</div>
</button>

<!-- Το Panel του Βοηθού -->
<div id="crm-assistant-panel">
    <div class="assistant-header">
        <span>🤖 CRM Βοηθός</span>
        <span class="assistant-close" id="crm-assistant-close">&times;</span>
    </div>
    <div class="assistant-body" id="crm-assistant-content">
        <div style="text-align:center; padding:20px; color:var(--gp-muted);">Φόρτωση...</div>
    </div>
    <div class="assistant-controls">
        <button id="assistant-voice-btn">
            🎤 Φωνητική Εντολή
        </button>
    </div>
</div>

<script>
(function() {
    const btn = document.getElementById('crm-assistant-btn');
    const panel = document.getElementById('crm-assistant-panel');
    const closeBtn = document.getElementById('crm-assistant-close');
    const content = document.getElementById('crm-assistant-content');
    const badge = document.getElementById('crm-assistant-badge');
    const voiceBtn = document.getElementById('assistant-voice-btn');
    
    let notificationsData = [];

    // Toggle Panel
    btn.addEventListener('click', () => {
        panel.classList.toggle('open');
        if (panel.classList.contains('open')) {
            fetchNotifications();
        }
    });

    closeBtn.addEventListener('click', () => {
        panel.classList.remove('open');
    });

    // Fetch Notifications from API
    function fetchNotifications() {
        fetch('/gopools/public/api/assistant_status.php', { method: 'GET' })
        .then(res => res.json())
        .then(data => {
            if (data.ok && data.notifications) {
                notificationsData = data.notifications;
                updateUI();
            }
        })
        .catch(err => {
            console.error('Error fetching assistant data:', err);
            content.innerHTML = '<div style="text-align:center; padding:20px; color:red;">Σφάλμα σύνδεσης.</div>';
        });
    }

    function updateUI() {
        content.innerHTML = '';
        
        // Update badge
        const criticalCount = notificationsData.filter(n => n.type !== 'info').length;
        if (criticalCount > 0) {
            badge.style.display = 'flex';
            badge.textContent = criticalCount;
        } else {
            badge.style.display = 'none';
        }

        // Render list
        notificationsData.forEach(item => {
            const el = document.createElement('a');
            el.className = 'assistant-item';
            el.href = item.url;
            el.innerHTML = `
                <div class="assistant-icon">${item.icon}</div>
                <div class="assistant-text">
                    <strong>${item.title}</strong>
                    <span>${item.message}</span>
                </div>
            `;
            content.appendChild(el);
        });
    }

    // Polling every 5 minutes
    setInterval(fetchNotifications, 5 * 60 * 1000);
    // Initial fetch to show badge on load
    setTimeout(fetchNotifications, 2000);

    // --- Web Speech API (Φωνητικές Εντολές) ---
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    let recognition;

    if (SpeechRecognition) {
        recognition = new SpeechRecognition();
        recognition.lang = 'el-GR';
        recognition.interimResults = false;
        recognition.maxAlternatives = 1;

        recognition.onstart = function() {
            voiceBtn.classList.add('listening');
            voiceBtn.innerHTML = '🎤 Ακούω...';
        };

        recognition.onresult = function(event) {
            const transcript = event.results[0][0].transcript.toLowerCase();
            console.log('Ακούστηκε: ', transcript);
            handleVoiceCommand(transcript);
        };

        recognition.onspeechend = function() {
            recognition.stop();
        };

        recognition.onerror = function(event) {
            console.error('Speech recognition error', event.error);
            
            let errorMsg = "Σφάλμα: " + event.error;
            if (event.error === 'not-allowed') {
                errorMsg = "Το πρόγραμμα περιήγησης μπλόκαρε το μικρόφωνο. Ελέγξτε τις ρυθμίσεις του browser σας (πάνω δεξιά στη γραμμή διευθύνσεων) και επιτρέψτε την πρόσβαση.";
            } else if (event.error === 'audio-capture') {
                errorMsg = "Δεν βρέθηκε μικρόφωνο. Ελέγξτε αν είναι συνδεδεμένο.";
            } else if (event.error === 'network') {
                errorMsg = "Σφάλμα δικτύου κατά την αναγνώριση φωνής.";
            }
            alert(errorMsg);
            
            stopListeningUI();
        };

        recognition.onend = function() {
            stopListeningUI();
        };

        voiceBtn.addEventListener('click', () => {
            try {
                recognition.start();
            } catch (e) {
                // If already started
                recognition.stop();
            }
        });
    } else {
        voiceBtn.style.display = 'none';
        console.warn("Speech Recognition API not supported in this browser.");
    }

    function stopListeningUI() {
        voiceBtn.classList.remove('listening');
        voiceBtn.innerHTML = '🎤 Φωνητική Εντολή';
    }

    // Απλή Μηχανή Ανάλυσης Εντολών
    function handleVoiceCommand(command) {
        if (command.includes('έξοδα') || command.includes('εξοδα')) {
            window.location.href = '/gopools/public/expenses/index.php';
        } else if (command.includes('έργα') || command.includes('εργα') || command.includes('projects')) {
            window.location.href = '/gopools/public/projects/index.php';
        } else if (command.includes('νέο έργο') || command.includes('νεο εργο')) {
            window.location.href = '/gopools/public/projects/edit.php';
        } else if (command.includes('ρυθμίσεις')) {
            window.location.href = '/gopools/public/settings/index.php';
        } else if (command.includes('dashboard') || command.includes('αρχική')) {
            window.location.href = '/gopools/public/dashboard/index.php';
        } else if (command.includes('εκκρεμότητες') || command.includes('ενημέρωση')) {
            panel.classList.add('open');
            readNotifications();
        } else {
            alert('Δεν κατάλαβα την εντολή: "' + command + '"');
        }
    }

    // Text to Speech
    function readNotifications() {
        if (!window.speechSynthesis) return;

        let textToSpeak = "";
        const criticalCount = notificationsData.filter(n => n.type !== 'info').length;

        if (criticalCount === 0) {
            textToSpeak = "Δεν υπάρχουν εκκρεμότητες.";
        } else {
            textToSpeak = "Έχετε τις εξής εκκρεμότητες: ";
            notificationsData.forEach(n => {
                if (n.type !== 'info') {
                    textToSpeak += n.title + ". ";
                }
            });
        }

        const utterance = new SpeechSynthesisUtterance(textToSpeak);
        utterance.lang = 'el-GR';
        window.speechSynthesis.speak(utterance);
    }
})();
</script>
