<?php
// includes/virtual-assistant.php - FINAL WORKING VERSION
$lang = isset($_GET['lang']) ? $_GET['lang'] : (isset($_SESSION['lang']) ? $_SESSION['lang'] : 'hr');
if (!in_array($lang, ['hr', 'en', 'de', 'it', 'pl', 'cs'])) $lang = 'hr';

$texts = [
    'hr' => ['title'=>'KI Asistent','subtitle'=>'Pomažem ti pronaći savršen restoran!','hungry'=>'Jesi li gladan?',
             'search'=>'Traži kuhinju ili jelo...','cuisines'=>'Vrste kuhinje','loading'=>'Učitavam kuhinje...',
             'based_on'=>'Na temelju restorana u Makarskoj','no_results'=>'Nema pronađenih kuhinja',
             'close'=>'Zatvori','search_btn'=>'Traži','restaurant'=>'restoran','restaurants'=>'restorana',
             'cuisine_types'=>'Kuhinje','restaurants_with'=>'Restorani sa'],
    'en' => ['title'=>'AI Assistant','subtitle'=>'I help you find the perfect restaurant!','hungry'=>'Are you hungry?',
             'search'=>'Search for cuisine or dish...','cuisines'=>'Cuisine Types','loading'=>'Loading cuisines...',
             'based_on'=>'Based on restaurants in Makarska','no_results'=>'No cuisines found',
             'close'=>'Close','search_btn'=>'Search','restaurant'=>'restaurant','restaurants'=>'restaurants',
             'cuisine_types'=>'Cuisines','restaurants_with'=>'Restaurants with'],
    'de' => ['title'=>'KI-Assistent','subtitle'=>'Ich helfe dir, das perfekte Restaurant zu finden!','hungry'=>'Hast du Hunger?',
             'search'=>'Suche nach Küche oder Gericht...','cuisines'=>'Küchenarten','loading'=>'Lade Küchen...',
             'based_on'=>'Basierend auf Restaurants in Makarska','no_results'=>'Keine Küchen gefunden',
             'close'=>'Schließen','search_btn'=>'Suchen','restaurant'=>'Restaurant','restaurants'=>'Restaurants',
             'cuisine_types'=>'Küchen','restaurants_with'=>'Restaurants mit'],
    'it' => ['title'=>'Assistente AI','subtitle'=>'Ti aiuto a trovare il ristorante perfetto!','hungry'=>'Hai fame?',
             'search'=>'Cerca cucina o piatto...','cuisines'=>'Tipi di Cucina','loading'=>'Caricamento cucine...',
             'based_on'=>'Basato sui ristoranti di Makarska','no_results'=>'Nessuna cucina trovata',
             'close'=>'Chiudi','search_btn'=>'Cerca','restaurant'=>'ristorante','restaurants'=>'ristoranti',
             'cuisine_types'=>'Cucine','restaurants_with'=>'Ristoranti con'],
    'pl' => ['title'=>'Asystent AI','subtitle'=>'Pomagam znaleźć idealną restaurację!','hungry'=>'Czy jesteś głodny?',
             'search'=>'Szukaj kuchni lub dania...','cuisines'=>'Rodzaje Kuchni','loading'=>'Ładowanie kuchni...',
             'based_on'=>'Na podstawie restauracji w Makarska','no_results'=>'Nie znaleziono kuchni',
             'close'=>'Zamknij','search_btn'=>'Szukaj','restaurant'=>'restauracja','restaurants'=>'restauracje',
             'cuisine_types'=>'Kuchnie','restaurants_with'=>'Restauracje z'],
    'cs' => ['title'=>'AI Asistent','subtitle'=>'Pomáhám vám najít perfektní restauraci!','hungry'=>'Máte hlad?',
             'search'=>'Hledat kuchyni nebo jídlo...','cuisines'=>'Typy Kuchyně','loading'=>'Načítání kuchyní...',
             'based_on'=>'Na základě restaurací v Makarska','no_results'=>'Nebyla nalezena žádná kuchyně',
             'close'=>'Zavřít','search_btn'=>'Hledat','restaurant'=>'restaurace','restaurants'=>'restaurace',
             'cuisine_types'=>'Kuchyně','restaurants_with'=>'Restaurace s']
];
$t = $texts[$lang];
?>

<!-- BUTTON & OVERLAY CODE (UNVERÄNDERT) -->
<button id="virtualAssistantBtn" class="virtual-assistant-btn" aria-label="<?= htmlspecialchars($t['hungry']) ?>">
    <span class="assistant-icon">🤖</span>
    <span class="assistant-text"><?= htmlspecialchars($t['hungry']) ?></span>
    <div class="assistant-pulse"></div>
</button>

<div id="assistantOverlay" class="assistant-overlay">
    <div class="assistant-container">
        <div class="assistant-header">
            <div class="assistant-title">
                <span class="assistant-emoji">🤖</span>
                <h3><?= htmlspecialchars($t['title']) ?></h3>
            </div>
            <p class="assistant-subtitle"><?= htmlspecialchars($t['subtitle']) ?></p>
            <button id="closeAssistant" class="btn-close" aria-label="<?= htmlspecialchars($t['close']) ?>">
                <i class="fas fa-times"></i>
            </button>
        </div>

        <div class="assistant-search">
            <input type="text" id="assistantSearch" placeholder="<?= htmlspecialchars($t['search']) ?>" autocomplete="off">
            <button class="search-btn"><i class="fas fa-search"></i></button>
        </div>

        <div class="assistant-cuisines">
            <h4><i class="fas fa-utensils"></i> <?= htmlspecialchars($t['cuisines']) ?></h4>
            <div id="cuisineGrid" class="cuisine-grid">
                <div class="loading-cuisines">
                    <i class="fas fa-spinner fa-spin"></i>
                    <p><?= htmlspecialchars($t['loading']) ?></p>
                </div>
            </div>
        </div>

        <div class="assistant-footer">
            <small><i class="fas fa-info-circle"></i> <?= htmlspecialchars($t['based_on']) ?></small>
        </div>
    </div>
</div>

<!-- CSS STYLES FÜR RESTAURANT-KARTEN -->
<style id="assistant-restaurant-styles">
/* Diese Styles beeinflussen das bestehende Design NICHT */
.restaurant-result-card {
    background: var(--va-bg);
    border: 2px solid var(--va-border);
    border-radius: var(--va-radius-lg);
    padding: 18px;
    display: flex;
    align-items: flex-start;
    gap: 16px;
    cursor: pointer;
    transition: all var(--va-transition-normal);
    margin-bottom: 12px;
}
.restaurant-result-card:hover {
    border-color: var(--va-primary-light);
    transform: translateY(-3px);
    box-shadow: var(--va-shadow-md);
}
.restaurant-emoji {
    font-size: 28px;
    min-width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--va-bg-light);
    border-radius: var(--va-radius-md);
    flex-shrink: 0;
}
.restaurant-info {
    flex: 1;
    min-width: 0;
}
.restaurant-info h5 {
    margin: 0 0 6px 0;
    color: var(--va-text);
    font-size: 16px;
    font-weight: 600;
}
.restaurant-address {
    margin: 0 0 8px 0;
    color: var(--va-text-light);
    font-size: 13px;
}
.menu-items {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 8px;
}
.menu-item-tag {
    background: rgba(111, 66, 193, 0.1);
    color: var(--va-primary);
    padding: 4px 10px;
    border-radius: 16px;
    font-size: 12px;
    font-weight: 500;
    border: 1px solid rgba(111, 66, 193, 0.2);
}
.item-count {
    margin: 0;
    color: var(--va-success);
    font-size: 13px;
    font-weight: 500;
}
.restaurant-btn {
    background: var(--va-primary);
    color: white;
    width: 40px;
    height: 40px;
    border-radius: var(--va-radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    flex-shrink: 0;
    transition: all var(--va-transition-normal);
}
.restaurant-result-card:hover .restaurant-btn {
    background: var(--va-primary-dark);
    transform: translateX(4px);
}
.results-section {
    margin-bottom: 25px;
}
.section-title {
    margin: 0 0 15px 0;
    color: var(--va-text-light);
    font-size: 14px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 8px;
}
</style>

<script>
// VIRTUAL ASSISTANT - FUNKTIONIERT 100%
document.addEventListener('DOMContentLoaded', function() {
    // Elemente
    const assistantBtn = document.getElementById('virtualAssistantBtn');
    const overlay = document.getElementById('assistantOverlay');
    const closeBtn = document.getElementById('closeAssistant');
    const searchInput = document.getElementById('assistantSearch');
    const cuisineGrid = document.getElementById('cuisineGrid');
    
    // Konfiguration
    const currentLang = '<?= $lang ?>';
    let allCuisines = [];
    let isOpen = false;

    // Event Listener
    assistantBtn.addEventListener('click', openAssistant);
    closeBtn.addEventListener('click', closeAssistant);
    
    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) closeAssistant();
    });
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape' && isOpen) closeAssistant();
    });
    
    // SUCHFUNKTION
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.trim();
        
        if (!searchTerm) {
            // Leere Suche: Küchen anzeigen
            displayCuisines(allCuisines);
            return;
        }
        
        if (searchTerm.length < 2) {
            // Zu kurze Suche
            const filtered = allCuisines.filter(c => 
                c.name.toLowerCase().includes(searchTerm.toLowerCase())
            );
            displayCuisines(filtered);
            return;
        }
        
        // ERWEITERTE SUCHE
        performSearch(searchTerm);
    });
    
    // Funktionen
    function openAssistant() {
        overlay.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        isOpen = true;
        loadCuisines();
        setTimeout(() => searchInput.focus(), 300);
    }
    
    function closeAssistant() {
        overlay.style.display = 'none';
        document.body.style.overflow = 'auto';
        isOpen = false;
        searchInput.value = '';
    }
    
    async function loadCuisines() {
        try {
            showLoading();
            const response = await fetch(`api/cuisines-simple.php?lang=${currentLang}&_=${Date.now()}`);
            const data = await response.json();
            
            if (data.success) {
                allCuisines = data.cuisines;
                displayCuisines(allCuisines);
            } else {
                showNoResults();
            }
        } catch (error) {
            console.error('Error:', error);
            showNoResults();
        }
    }
    
    async function performSearch(searchTerm) {
        showLoading();
        
        try {
            // 1. In Küchen suchen
            const searchLower = searchTerm.toLowerCase();
            const cuisineResults = allCuisines.filter(c => 
                c.name.toLowerCase().includes(searchLower)
            );
            
            // 2. In Menu-Kategorien suchen (NEU)
            let restaurantResults = [];
            try {
                const menuResponse = await fetch(
                    `api/search-menu.php?lang=${currentLang}&q=${encodeURIComponent(searchTerm)}&_=${Date.now()}`
                );
                const menuData = await menuResponse.json();
                
                if (menuData.success && menuData.results && menuData.results.length > 0) {
                    restaurantResults = menuData.results;
                }
            } catch (menuError) {
                console.log('Menu search optional:', menuError);
            }
            
            // 3. Ergebnisse kombinieren
            if (cuisineResults.length === 0 && restaurantResults.length === 0) {
                showNoResults();
                return;
            }
            
            // HTML erstellen
            let html = '';
            const restaurantText = '<?= $t["restaurants"] ?>';
            
            // A) KÜCHEN-ERGEBNISSE
            if (cuisineResults.length > 0) {
                html += `<div class="results-section">
                            <h5 class="section-title">
                                <i class="fas fa-utensils"></i> <?= htmlspecialchars($t['cuisine_types']) ?>
                            </h5>`;
                
                cuisineResults.forEach(cuisine => {
                    const url = `restaurants-list.php?cuisine=${encodeURIComponent(cuisine.name)}&lang=${currentLang}&from=assistant`;
                    html += `
                    <div class="cuisine-card" onclick="window.location.href='${url}'">
                        <div class="cuisine-icon">${cuisine.emoji}</div>
                        <div class="cuisine-info">
                            <h5>${escapeHtml(cuisine.name)}</h5>
                            <p class="cuisine-count">${cuisine.restaurant_count} ${restaurantText}</p>
                        </div>
                        <div class="cuisine-btn"><i class="fas fa-arrow-right"></i></div>
                    </div>
                    `;
                });
                
                html += `</div>`;
            }
            
            // B) RESTAURANT-ERGEBNISSE
            if (restaurantResults.length > 0) {
                html += `<div class="results-section" style="margin-top: ${cuisineResults.length > 0 ? '20px' : '0'}">
                            <h5 class="section-title">
                                <i class="fas fa-store"></i> 
                                <?= htmlspecialchars($t['restaurants_with']) ?> "${escapeHtml(searchTerm)}"
                            </h5>`;
                
                restaurantResults.forEach(restaurant => {
                    const url = `restaurant-details.php?id=${restaurant.id}&lang=${currentLang}&from=assistant`;
                    const itemsHtml = restaurant.menu_items.slice(0, 3).map(item => 
                        `<span class="menu-item-tag">${escapeHtml(item)}</span>`
                    ).join('');
                    
                    const moreText = restaurant.menu_items.length > 3 ? 
                        `<span style="color:#6c757d; font-size:12px; margin-left:4px;">+${restaurant.menu_items.length - 3} mehr</span>` : '';
                    
                    html += `
                    <div class="restaurant-result-card" onclick="window.location.href='${url}'">
                        <div class="restaurant-emoji">${restaurant.emoji}</div>
                        <div class="restaurant-info">
                            <h5>${escapeHtml(restaurant.name)}</h5>
                            ${restaurant.address ? `<p class="restaurant-address">📍 ${escapeHtml(restaurant.address)}</p>` : ''}
                            ${restaurant.menu_items.length > 0 ? `
                            <div class="menu-items">
                                ${itemsHtml}
                                ${moreText}
                            </div>
                            ` : ''}
                            <p class="item-count">
                                <i class="fas fa-utensil-spoon"></i> 
                                ${restaurant.total_matches} Gericht${restaurant.total_matches !== 1 ? 'e' : ''}
                            </p>
                        </div>
                        <div class="restaurant-btn">
                            <i class="fas fa-arrow-right"></i>
                        </div>
                    </div>
                    `;
                });
                
                html += `</div>`;
            }
            
            cuisineGrid.innerHTML = html;
            
        } catch (error) {
            console.error('Search error:', error);
            showNoResults();
        }
    }
    
    function displayCuisines(cuisines) {
        if (!cuisines || cuisines.length === 0) {
            showNoResults();
            return;
        }
        
        const restaurantText = '<?= $t["restaurants"] ?>';
        let html = '';
        
        cuisines.forEach(cuisine => {
            const url = `restaurants-list.php?cuisine=${encodeURIComponent(cuisine.name)}&lang=${currentLang}&from=assistant`;
            html += `
            <div class="cuisine-card" onclick="window.location.href='${url}'">
                <div class="cuisine-icon">${cuisine.emoji}</div>
                <div class="cuisine-info">
                    <h5>${escapeHtml(cuisine.name)}</h5>
                    <p class="cuisine-count">${cuisine.restaurant_count} ${restaurantText}</p>
                </div>
                <div class="cuisine-btn"><i class="fas fa-arrow-right"></i></div>
            </div>
            `;
        });
        
        cuisineGrid.innerHTML = html;
    }
    
    function showLoading() {
        cuisineGrid.innerHTML = `
            <div class="loading-cuisines">
                <i class="fas fa-spinner fa-spin"></i>
                <p><?= htmlspecialchars($t['loading']) ?></p>
            </div>
        `;
    }
    
    function showNoResults() {
        cuisineGrid.innerHTML = `
            <div class="no-results">
                <i class="fas fa-search"></i>
                <p><?= htmlspecialchars($t['no_results']) ?></p>
            </div>
        `;
    }
    
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text || '';
        return div.innerHTML;
    }
});
</script>