<!DOCTYPE html>

<html lang="it">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Itineris - L'Arte del Viaggio</title>

    

    <!-- Libraries -->

    <script src="https://cdn.tailwindcss.com"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />

    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <script src="https://npmcdn.com/flatpickr/dist/l10n/index.js"></script>

    

    <!-- Google Fonts & Icons -->

    <link rel="preconnect" href="https://fonts.googleapis.com">

    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700&family=Plus+Jakarta+Sans:wght@400;500;700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />


    <style>

        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #0c0a18; color: #e0e0e0; }

        .font-serif { font-family: 'Playfair Display', serif; }

        .view { display: none; }

        .view.active { display: block; animation: fadeIn 0.7s ease-in-out; }

        @keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }

        .frost-glass { background: rgba(12, 10, 24, 0.5); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(255, 255, 255, 0.1); }

        #map { height: 250px; border-radius: 0.75rem; z-index: 1; filter: grayscale(30%) contrast(120%);}

        .leaflet-container { z-index: 1 !important; }

        .leaflet-pane, .leaflet-tile, .leaflet-marker-icon, .leaflet-marker-shadow, .leaflet-tile-container, .leaflet-pane > svg, .leaflet-pane > canvas { max-width: none !important; max-height: none !important; }

        .form-input, .form-textarea { background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); color: white; }

        .form-input::placeholder, .form-textarea::placeholder { color: rgba(255, 255, 255, 0.4); }

        .form-input:focus, .form-textarea:focus { background: rgba(255, 255, 255, 0.1); border-color: #c4b5fd; box-shadow: 0 0 0 3px rgba(167, 139, 250, 0.3); outline: none; }

        #video-bg { position: fixed; right: 0; bottom: 0; min-width: 100%; min-height: 100%; z-index: -1; object-fit: cover; filter: brightness(0.4); }

        .lang-select { background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.1); color: white; -webkit-appearance: none; -moz-appearance: none; appearance: none; padding-right: 2rem; background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%239ca3af' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e"); background-position: right 0.5rem center; background-repeat: no-repeat; background-size: 1.5em 1.5em; }

        .tab-button { transition: all 0.3s; }

        .tab-button.active { background-color: #6366f1; color: white; }

        .tab-button:not(.active) { background-color: rgba(255, 255, 255, 0.1); color: rgba(255, 255, 255, 0.7); }

        .pro-badge { background: linear-gradient(to right, #a855f7, #ef4444); color: white; font-size: 0.6rem; padding: 2px 6px; border-radius: 99px; vertical-align: super; margin-left: 4px;}

    </style>

</head>

<body class="w-full">

    <video autoplay muted loop id="video-bg">

        <source src="https://assets.mixkit.co/videos/preview/mixkit-flying-over-a-large-calm-lake-near-the-mountains-4993-large.mp4" type="video/mp4">

    </video>


    <header id="main-header" class="fixed top-0 left-0 right-0 z-20 transition-all duration-300">

        <nav class="container mx-auto px-6 py-4 flex justify-between items-center">

            <div class="flex items-center gap-4">

                <h1 class="text-3xl font-serif text-white">Itineris</h1>

                <select id="language-switcher" class="lang-select text-sm rounded-md px-3 py-1.5 focus:outline-none focus:ring-2 focus:ring-indigo-400"></select>

            </div>

            <div id="nav-auth-links" class="flex items-center space-x-2">

                 <button onclick="switchView('auth-view')" class="text-white font-medium px-4 py-2 rounded-lg hover:bg-white/10 transition" data-translate-key="loginButtonNav"></button>

                 <button onclick="switchView('auth-view', {isRegister: true})" class="bg-indigo-500 text-white font-semibold py-2 px-5 rounded-lg hover:bg-indigo-600 transition shadow-lg shadow-indigo-500/30" data-translate-key="startNowButton"></button>

            </div>

            <div id="nav-user-dash" class="hidden items-center space-x-4">

                <span id="welcome-message" class="font-semibold text-white/80"></span>

                <button onclick="switchView('support-view')" class="text-white hover:text-indigo-300 flex items-center gap-2"><span class="material-symbols-outlined">support_agent</span><span data-translate-key="supportButton"></span></button>

                <button onclick="switchView('marketing-view')" class="text-white hover:text-indigo-300 flex items-center gap-2"><span class="material-symbols-outlined">campaign</span><span data-translate-key="promoButton"></span></button>

                <button onclick="switchView('dashboard-view')" class="text-white hover:text-indigo-300 flex items-center gap-2"><span class="material-symbols-outlined">dashboard</span><span data-translate-key="dashboardButton"></span></button>

                <button onclick="switchView('premium-view')" class="bg-gradient-to-r from-amber-400 to-orange-500 text-white font-bold py-2 px-4 rounded-lg hover:opacity-90 transition text-sm flex items-center gap-2"><span class="material-symbols-outlined">workspace_premium</span><span data-translate-key="goProButton"></span></button>

                <button onclick="logout()" class="text-red-400 hover:text-red-300 flex items-center gap-2"><span class="material-symbols-outlined">logout</span><span data-translate-key="logoutButton"></span></button>

            </div>

        </nav>

    </header>


    <main class="relative z-10 pt-24 md:pt-32">

        <!-- Views -->

        <div id="auth-view" class="view active">

            <div class="container mx-auto px-6 text-center flex flex-col items-center justify-center min-h-[70vh]">

                <h2 class="text-5xl md:text-7xl font-serif text-white mb-6 leading-tight" data-translate-key="heroTitle"></h2>

                <p class="text-lg md:text-xl text-white/70 max-w-3xl mb-10" data-translate-key="heroSubtitle"></p>

                <div class="w-full max-w-sm p-8 frost-glass rounded-2xl">

                    <h3 id="auth-title" class="text-2xl font-bold text-white text-center mb-6" data-translate-key="loginToStart"></h3>

                    <form id="auth-form" onsubmit="handleAuth(event)">

                        <input type="email" id="auth-email" class="w-full p-3 mb-4 rounded-lg form-input" required data-translate-placeholder="authEmailPlaceholder">

                        <input type="password" id="auth-password" class="w-full p-3 mb-4 rounded-lg form-input" required data-translate-placeholder="authPasswordPlaceholder">

                        <button id="auth-button" type="submit" class="w-full bg-gradient-to-r from-indigo-500 to-purple-500 text-white font-bold py-3 rounded-lg hover:opacity-90 transition-opacity shadow-lg shadow-indigo-500/40" data-translate-key="loginButton"></button>

                    </form>

                    <p id="auth-switch-text" class="text-center mt-4 text-sm text-white/60"></p>

                </div>

            </div>

        </div>

        <div id="dashboard-view" class="view">

             <div class="container mx-auto px-6">

                <div class="flex justify-between items-center mb-8">

                    <h2 class="text-4xl font-serif text-white" data-translate-key="dashboardTitle"></h2>

                    <button onclick="handleCreateNewTrip()" class="bg-gradient-to-r from-green-500 to-teal-500 text-white font-bold py-3 px-6 rounded-xl hover:opacity-90 transition shadow-lg shadow-green-500/30 flex items-center gap-2">

                        <span class="material-symbols-outlined">add_location</span><span data-translate-key="createNewTrip"></span>

                    </button>

                </div>

                <div id="saved-trips-container">

                    <div id="saved-trips-list" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"></div>

                    <div class="mt-12">

                        <h3 class="text-2xl font-serif text-white mb-4" data-translate-key="featuredInspirationsTitle"></h3>

                        <div id="featured-trip" class="frost-glass rounded-2xl flex flex-col md:flex-row items-center overflow-hidden group">

                           <img src="https://placehold.co/600x400/34d399/ffffff?text=Svizzera" alt="Paesaggio svizzero" class="w-full md:w-1/3 h-full object-cover transition-transform duration-500 group-hover:scale-105">

                           <div class="p-8">

                                <p class="text-sm font-bold text-teal-300" data-translate-key="sponsoredBy"></p>

                                <h4 class="text-3xl font-serif text-white mt-2" data-translate-key="featuredTripTitle"></h4>

                                <p class="text-white/70 mt-4" data-translate-key="featuredTripDesc"></p>

                                <button onclick="viewFeaturedTrip()" class="mt-6 bg-white/10 text-white font-bold py-2 px-4 rounded-lg hover:bg-white/20 transition" data-translate-key="viewFeaturedTripButton"></button>

                           </div>

                        </div>

                    </div>

                </div>

            </div>

        </div>

        <div id="wizard-view" class="view">

            <div class="container mx-auto px-6 flex justify-center">

                 <div class="w-full max-w-3xl p-8 frost-glass rounded-2xl">

                    <!-- TABS -->

                    <div class="flex mb-8 border-b border-white/10">

                        <button id="plan-trip-tab" onclick="switchWizardTab('plan')" class="tab-button flex-1 py-3 font-bold flex items-center justify-center gap-2" data-translate-key="planTripTab"></button>

                        <button id="inspire-me-tab" onclick="switchWizardTab('inspire')" class="tab-button flex-1 py-3 font-bold flex items-center justify-center gap-2" data-translate-key="inspireMeTab"></button>

                    </div>


                    <!-- PLAN TRIP FORM -->

                    <div id="plan-trip-form-container">

                        <h2 class="text-4xl font-serif text-white text-center mb-8" data-translate-key="wizardTitle"></h2>

                        <form id="wizard-form" onsubmit="generateItinerary(event)" class="space-y-6">

                            <div>

                                <label for="destination" class="block text-lg font-medium text-white/80 mb-2" data-translate-key="destinationLabel"></label>

                                <input type="text" id="destination" name="destination" class="w-full p-3 rounded-lg form-input" required data-translate-placeholder="destinationPlaceholder">

                            </div>

                            <div>

                                <label for="dates" class="block text-lg font-medium text-white/80 mb-2" data-translate-key="datesLabel"></label>

                                <input type="text" id="dates" name="dates" class="w-full p-3 rounded-lg form-input" required data-translate-placeholder="datesPlaceholder">

                            </div>

                            <div class="grid md:grid-cols-2 gap-6">

                                <div>

                                    <label for="style" class="block text-lg font-medium text-white/80 mb-2" data-translate-key="styleLabel"></label>

                                    <select id="style" name="style" class="w-full p-3 rounded-lg form-input"></select>

                                </div>

                                <div>

                                    <label for="budget" class="block text-lg font-medium text-white/80 mb-2" data-translate-key="budgetLabel"></label>

                                    <select id="budget" name="budget" class="w-full p-3 rounded-lg form-input"></select>

                                </div>

                            </div>

                            <button type="submit" class="w-full bg-gradient-to-r from-indigo-500 to-purple-500 text-white font-bold py-3 rounded-lg hover:opacity-90 transition-opacity text-lg shadow-lg shadow-indigo-500/40" data-translate-key="generateButton"></button>

                        </form>

                    </div>

                    

                    <!-- INSPIRE ME FORM -->

                    <div id="inspire-me-form-container" class="hidden">

                         <h2 class="text-4xl font-serif text-white text-center mb-8" data-translate-key="inspireMeTitle"></h2>

                         <form id="inspire-form" onsubmit="generateInspirationItinerary(event)" class="space-y-6">

                            <div>

                                <label for="inspiration-prompt" class="block text-lg font-medium text-white/80 mb-2" data-translate-key="inspirationLabel"></label>

                                <textarea id="inspiration-prompt" name="inspiration-prompt" rows="4" class="w-full p-3 rounded-lg form-textarea" required data-translate-placeholder="inspirationPlaceholder"></textarea>

                            </div>

                             <div class="text-sm text-white/60">

                                 <span data-translate-key="inspirationExamplesTitle"></span>

                                 <ul class="list-disc list-inside mt-2">

                                     <li data-translate-key="inspirationExample1"></li>

                                     <li data-translate-key="inspirationExample2"></li>

                                     <li data-translate-key="inspirationExample3"></li>

                                 </ul>

                             </div>

                            <button type="submit" class="w-full bg-gradient-to-r from-rose-500 to-amber-500 text-white font-bold py-3 rounded-lg hover:opacity-90 transition-opacity text-lg shadow-lg shadow-rose-500/40" data-translate-key="inspireMeButton"></button>

                         </form>

                    </div>

                 </div>

            </div>

        </div>

        <div id="itinerary-view" class="view container mx-auto px-6 pb-12">

            <div class="flex justify-end mb-4">

                <button onclick="switchView('premium-view')" class="text-amber-400 font-bold flex items-center gap-2 hover:text-amber-300 transition group">

                    <span data-translate-key="inviteFriends"></span>

                    <span class="material-symbols-outlined text-amber-400 text-lg transition-transform group-hover:scale-110">workspace_premium</span>

                </button>

            </div>

            <div id="itinerary-content-wrapper" class="p-6 md:p-10 frost-glass rounded-2xl"></div>

            <div class="mt-8 text-center space-x-2 md:space-x-4">

                <button id="save-trip-btn" onclick="saveCurrentItinerary()" class="bg-blue-600 text-white font-bold py-3 px-6 rounded-lg hover:bg-blue-700 transition shadow-lg shadow-blue-500/30"></button>

                <button onclick="downloadPDF()" class="bg-teal-500 text-white font-bold py-3 px-6 rounded-lg hover:bg-teal-600 transition shadow-lg shadow-teal-500/30" data-translate-key="downloadPdfButton"></button>

                <button onclick="switchView('dashboard-view')" class="bg-white/10 text-white font-bold py-3 px-6 rounded-lg hover:bg-white/20 transition" data-translate-key="backToDashboardButton"></button>

            </div>

        </div>

        <div id="premium-view" class="view container mx-auto px-6 pb-12 text-center">

            <h2 class="text-5xl font-serif text-white" data-translate-key="premiumTitle"></h2>

            <p class="text-xl text-white/70 mt-4 mb-10 max-w-2xl mx-auto" data-translate-key="premiumSubtitle"></p>

            <div class="p-8 frost-glass rounded-2xl max-w-4xl mx-auto">

                <div class="grid md:grid-cols-3 gap-8">

                    <div class="text-left">

                        <span class="material-symbols-outlined text-4xl text-indigo-300">smart_toy</span>

                        <h3 class="text-xl font-bold mt-2" data-translate-key="premiumFeature1Title"></h3>

                        <p class="text-white/60 mt-1" data-translate-key="premiumFeature1Desc"></p>

                    </div>

                     <div class="text-left">

                        <span class="material-symbols-outlined text-4xl text-indigo-300">group</span>

                        <h3 class="text-xl font-bold mt-2" data-translate-key="premiumFeature2Title"></h3>

                        <p class="text-white/60 mt-1" data-translate-key="premiumFeature2Desc"></p>

                    </div>

                     <div class="text-left">

                        <span class="material-symbols-outlined text-4xl text-indigo-300">checklist</span>

                        <h3 class="text-xl font-bold mt-2" data-translate-key="premiumFeature3Title"></h3>

                        <p class="text-white/60 mt-1" data-translate-key="premiumFeature3Desc"></p>

                    </div>

                </div>

                <button class="mt-10 bg-gradient-to-r from-amber-400 to-orange-500 text-white font-bold py-4 px-8 rounded-lg text-lg" data-translate-key="upgradeNowButton"></button>

            </div>

        </div>

        <div id="loading-view" class="view text-center py-16">

            <svg class="animate-spin h-16 w-16 text-indigo-400 mx-auto mb-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>

            <h2 id="loading-title" class="text-3xl font-serif text-white"></h2>

            <p id="loading-subtitle" class="text-white/60 mt-2"></p>

        </div>

        <div id="marketing-view" class="view container mx-auto px-6 pb-12">

            <h2 class="text-4xl font-serif text-white mb-8" data-translate-key="promoDashboardTitle"></h2>

            <div class="grid lg:grid-cols-3 gap-8">

                <div class="lg:col-span-2">

                    <div class="p-8 frost-glass rounded-2xl">

                        <h3 class="text-2xl font-bold text-white mb-4" data-translate-key="videoGeneratorTitle"></h3>

                        <p class="text-white/60 mb-6" data-translate-key="videoGeneratorSubtitle"></p>

                        <form id="video-generator-form" onsubmit="generateMarketingVideo(event)" class="flex gap-4">

                            <input type="text" id="video-theme" name="video-theme" class="w-full p-3 rounded-lg form-input" required data-translate-placeholder="videoThemePlaceholder">

                            <button type="submit" class="bg-gradient-to-r from-pink-500 to-orange-500 text-white font-bold py-3 px-6 rounded-lg hover:opacity-90 transition">

                                <span class="material-symbols-outlined">auto_awesome</span>

                            </button>

                        </form>

                        <div id="video-storyboard-result" class="mt-8"></div>

                    </div>

                </div>

                <div>

                    <div class="p-8 frost-glass rounded-2xl">

                         <h3 class="text-2xl font-bold text-white mb-4" data-translate-key="googleAdsTitle"></h3>

                         <p class="text-white/60 mb-6" data-translate-key="googleAdsSubtitle"></p>

                         <div class="space-y-4">

                            <div>

                                <span class="text-sm text-white/50" data-translate-key="adStatus"></span>

                                <p class="text-lg font-bold text-green-400">● Attiva</p>

                            </div>

                            <div>

                                <span class="text-sm text-white/50" data-translate-key="adBudget"></span>

                                <p class="text-lg font-bold">50,00 €</p>

                            </div>

                             <div>

                                <span class="text-sm text-white/50" data-translate-key="adTarget"></span>

                                <p class="text-lg font-bold">Viaggiatori, 25-55, Mondo</p>

                            </div>

                            <div>

                                <span class="text-sm text-white/50" data-translate-key="adKeywords"></span>

                                <div id="keyword-list" class="flex flex-wrap gap-2 mt-2"></div>

                            </div>

                            <div class="pt-4">

                                <a href="https://ads.google.com/" target="_blank" class="w-full text-center block bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition" data-translate-key="manageOnGoogleAds"></a>

                            </div>

                         </div>

                    </div>

                </div>

            </div>

        </div>

        <div id="support-view" class="view container mx-auto px-6 pb-12">

             <h2 class="text-4xl font-serif text-white mb-8" data-translate-key="supportCenterTitle"></h2>

             <div class="frost-glass rounded-2xl flex flex-col md:flex-row h-[70vh] overflow-hidden">

                <div class="w-full md:w-1/3 border-r border-white/10 overflow-y-auto">

                    <div class="p-4 border-b border-white/10">

                        <h3 class="font-bold text-lg text-white" data-translate-key="inboxTitle"></h3>

                    </div>

                    <div id="inbox-list"></div>

                </div>

                <div id="message-detail-view" class="w-full md:w-2/3 flex flex-col"></div>

             </div>

        </div>


        <!-- SETUP MODAL -->

        <div id="setup-modal" class="fixed inset-0 bg-black/80 z-50 hidden items-center justify-center p-4">

            <div class="bg-[#1a1829] p-8 rounded-2xl max-w-2xl w-full border border-white/10 shadow-2xl">

                <h2 class="text-3xl font-serif text-white mb-4">Configurazione Iniziale Richiesta</h2>

                <p class="text-white/70 mb-6">Per attivare il salvataggio dei tuoi viaggi e l'autenticazione, è necessario collegare la tua istanza personale di Firebase. È un'operazione da fare una sola volta.</p>

                <ol class="text-white/70 list-decimal list-inside space-y-2 mb-6 text-sm">

                    <li>Vai alla <a href="https://console.firebase.google.com/" target="_blank" class="text-indigo-300 underline">tua console Firebase</a> e seleziona il tuo progetto.</li>

                    <li>Vai su "Impostazioni progetto" (icona ingranaggio) e copia l'oggetto di configurazione <code class="bg-white/10 px-1 rounded-sm">firebaseConfig</code> dalla tua app web.</li>

                    <li>Incollalo qui sotto e clicca "Salva e Inizializza".</li>

                </ol>

                <textarea id="firebase-config-input" rows="8" class="w-full p-3 rounded-lg form-input font-mono text-xs" placeholder="const firebaseConfig = { ... };"></textarea>

                <button onclick="saveFirebaseConfig()" class="mt-4 w-full bg-gradient-to-r from-green-500 to-teal-500 text-white font-bold py-3 rounded-lg">Salva e Inizializza</button>

            </div>

        </div>

    </main>


<script type="module">

    // Import Firebase modules

    import { initializeApp } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js";

    import { getAuth, onAuthStateChanged, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, setPersistence, inMemoryPersistence } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-auth.js";

    import { getFirestore, collection, doc, addDoc, onSnapshot, deleteDoc, query } from "https://www.gstatic.com/firebasejs/11.6.1/firebase-firestore.js";

    

    // --- START OF INLINED TRANSLATIONS.JS ---

    const translations = {

        langName: "English",

        welcomeMessage: "Hello, {name}!",

        loginButtonNav: "Login",

        startNowButton: "Start Now",

        dashboardButton: "Dashboard",

        promoButton: "Promotion",

        supportButton: "Support",

        logoutButton: "Logout",

        goProButton: "Go Pro",

        heroTitle: "Your dream trip,<br>designed by intelligence.",

        heroSubtitle: "Enter a destination. Let our AI create a tailor-made itinerary with flights, hotels, and activities. Your next journey begins with an idea.",

        loginToStart: "Login to start",

        authEmailPlaceholder: "Email",

        authPasswordPlaceholder: "Password",

        loginButton: "Login",

        registerPrompt: "Don't have an account?",

        registerLink: "Sign Up",

        loginPrompt: "Already have an account?",

        dashboardTitle: "Dashboard",

        createNewTrip: "Create New Trip",

        noTripsSaved: "No saved trips yet. Start creating your next adventure!",

        viewButton: "View",

        deleteButton: "Delete",

        featuredInspirationsTitle: "Featured Inspirations",

        sponsoredBy: "Presented by the Switzerland Tourism Board",

        featuredTripTitle: "Secrets of the Swiss Alps",

        featuredTripDesc: "An exclusive 7-day luxury journey through breathtaking landscapes, curated by local experts.",

        viewFeaturedTripButton: "Explore this Journey",

        planTripTab: "Plan a Trip",

        inspireMeTab: "Inspire Me",

        wizardTitle: "Create a new itinerary",

        inspireMeTitle: "How do you want to feel?",

        destinationLabel: "Destination",

        destinationPlaceholder: "e.g., Kyoto, Patagonia, Iceland...",

        datesLabel: "Trip Dates",

        datesPlaceholder: "Select a date range",

        styleLabel: "Style",

        budgetLabel: "Budget",

        generateButton: "Generate Itinerary with AI",

        inspirationLabel: "Describe your desired feeling, theme, or inspiration...",

        inspirationPlaceholder: "e.g., 'A romantic weekend in Paris, but avoiding the usual tourist traps.'",

        inspirationExamplesTitle: "Examples:",

        inspirationExample1: "I want to feel like an explorer in a lost world.",

        inspirationExample2: "A weekend of total digital detox in a luxury cabin.",

        inspirationExample3: "A culinary tour of Italy focused on street food.",

        inspireMeButton: "Inspire Me",

        loadingTitle: "The AI is designing your adventure...",

        loadingSubtitle: "One moment, consulting the stars (and the APIs).",

        saveTripButton: "Save Trip",

        tripSavedButton: "Saved",

        downloadPdfButton: "Download PDF",

        backToDashboardButton: "Dashboard",

        days: "{count} days",

        flightsTitle: "Suggested Flights",

        hotelsTitle: "Recommended Hotels",

        activitiesTitle: "Must-Do Activities",

        priceEstimate: "Est. price",

        stops: "{count, plural, =0 {0 stops} =1 {1 stop} other {# stops}}",

        priceFrom: "from",

        priceNight: "night",

        noSuggestions: "No suggestions available.",

        searchOnSkyscanner: "Search on Skyscanner",

        searchOnBooking: "Search on Booking.com",

        viewOnGetYourGuide: "View on GetYourGuide",

        inviteFriends: "Invite Friends",

        conciergeTitle: "AI Concierge",

        viewOfferButton: "View Offer",

        promoDashboardTitle: "Promotion Dashboard",

        videoGeneratorTitle: "Promotional Video Generator",

        videoGeneratorSubtitle: "Enter a theme or destination to generate a script and storyboard for a 30-second promotional video.",

        videoThemePlaceholder: "e.g., Adventure in Costa Rica",

        googleAdsTitle: "Google Ads Campaign",

        googleAdsSubtitle: "Simulated overview of an active campaign to promote Itineris.",

        adStatus: "Status",

        adBudget: "Daily Budget",

        adTarget: "Target Audience",

        adKeywords: "Keywords",

        adKeyword1: "ai travel planner",

        adKeyword2: "create itinerary",

        adKeyword3: "custom trips",

        manageOnGoogleAds: "Manage in Google Ads",

        videoLoadingTitle: "The AI is directing your video...",

        videoLoadingSubtitle: "Get the popcorn ready!",

        scene: "Scene",

        visual: "Visual",

        voiceover: "Voiceover",

        supportCenterTitle: "Support Center",

        inboxTitle: "Inbox",

        statusNew: "NEW",

        noMessageSelected: "No message selected. Choose one from the list.",

        from: "From",

        suggestedReply: "Suggested Reply",

        generateReplyPlaceholder: "Click to generate a reply with AI...",

        apiErrorPlaceholder: "Error during generation. Please try again.",

        generateReplyButton: "Generate AI Reply",

        sendReplyButton: "Send Reply",

        emptyReplyError: "The reply cannot be empty.",

        replySentSuccess: "Reply sent (simulated).",

        supportSubject1: "Question about my Japan trip",

        supportBody1: "Hi, I generated an itinerary for Kyoto and would like to know if it's possible to add a visit to Nara. Thanks!",

        supportSubject2: "Login issue",

        supportBody2: "Hello, I can't reset my password. Can you help me?",

        supportSubject3: "Platform feedback",

        supportBody3: "Just wanted to say I think your site is fantastic! It's incredibly useful.",

        premiumTitle: "Become an Itineris Pro",

        premiumSubtitle: "Unlock your full travel potential. The Pro plan gives you access to exclusive features designed for the ultimate travel experience.",

        premiumFeature1Title: "24/7 AI Travel Assistant",

        premiumFeature1Desc: "Get real-time advice, translations, and local recommendations on the go via our mobile app.",

        premiumFeature2Title: "Collaborative Planning",

        premiumFeature2Desc: "Invite friends to plan together. Comment, vote on activities, and build your perfect group trip.",

        premiumFeature3Title: "Smart Checklists & Alerts",

        premiumFeature3Desc: "Receive proactive checklists for visas and bookings, plus real-time alerts for your flights.",

        upgradeNowButton: "Upgrade Now - €9.99/month",

        freeLimitReached: "You have reached your limit of 3 saved trips. Upgrade to Itineris Pro to save unlimited trips!",

        authError: "Error: {message}",

        apiError: "AI Error: {message}",

        noAIContent: "No valid content received from the AI.",

        datesRequiredError: "Please select the trip dates.",

        loginToProceed: "You need to log in to proceed.",

        tripSavedSuccess: "Trip saved!",

        saveError: "Could not save the trip.",

        deleteConfirm: "Are you sure you want to delete this trip?",

        deleteError: "Could not delete the trip.",

        creatingPdf: "Creating...",

        pdfError: "Error creating PDF.",

        styles: { culturale: "Cultural", relax: "Relax", avventura: "Adventure", gastronomico: "Gastronomic" },

        budgets: { economico: "💰 Budget", medio: "💰💰 Standard", lusso: "💰💰💰 Luxury" },

        concierge: { insurance: { title: "Travel Insurance", icon: "health_and_safety" }, car_rental: { title: "Car Rental", icon: "directions_car" }, esim: { title: "eSIM Data Plan", icon: "wifi" }, lounge: { title: "Airport Lounge Access", icon: "airline_seat_recline_extra" } },

        itineraryPrompt: "Act as an expert {currentLanguage}-speaking travel agent. Create a travel proposal for {destination} for {duration} days. Travel style: '{style}', accommodation budget: '{budget}'. Provide realistic and interesting suggestions, including the 3-letter IATA airport code for the destination. Respond only with the JSON.",

        inspirationPrompt: "Act as a creative, {currentLanguage}-speaking travel expert. A user wants to feel this way: '{userInput}'. First, determine the perfect destination in the world that matches this feeling. Then, generate a complete 7-day itinerary for that destination with flights, hotels, activities, coordinates, and the destination's IATA code. Respond only with the JSON.",

        videoPrompt: "Act as a creative director. Generate a concept for a 30-second promotional video for 'Itineris' based on the theme: '{theme}'. Create a catchy title, a short description, and a 3-scene storyboard. For each scene, provide a title, a visual description, and a line of voiceover in {currentLanguage}. Respond only with the JSON.",

        supportPrompt: "Act as a friendly and efficient support agent for 'Itineris', an AI travel planner. Respond in {currentLanguage} to the following customer message professionally and helpfully. Customer message: '{customerMessage}'. Respond only with the JSON containing the 'reply' key.",

        translationPrompt: "Translate the following JSON object containing UI strings for a web application from English to {langName}. Maintain the exact same JSON structure and keys. Only translate the string values. Do not add explanations or any text outside of the JSON object. The source JSON is: {sourceJson}",

        conciergePrompt: "Act as a proactive travel concierge in {currentLanguage}. Based on the following itinerary details: {itineraryJson}, determine which of these services are relevant: travel insurance, car rental, eSIM, airport lounge access. For each relevant service, provide a short, compelling suggestion_text and a placeholder affiliate_link. Respond only with the JSON.",

    };

    const languages = [ { code: 'en', name: 'English' }, { code: 'it', name: 'Italiano' }, { code: 'es', name: 'Español' }, { code: 'fr', name: 'Français' }, { code: 'de', name: 'Deutsch' }, { code: 'pt', name: 'Português' }, { code: 'ru', name: 'Русский' }, { code: 'zh', name: '中文' }, { code: 'ja', name: '日本語' }, { code: 'ar', name: 'العربية' }, { code: 'hi', name: 'हिन्दी' }, { code: 'ko', name: '한국어' }, { code: 'nl', 'name': 'Nederlands' }, { code: 'sv', name: 'Svenska' }, { code: 'tr', 'name': 'Türkçe'} ];

    // --- END OF INLINED TRANSLATIONS.JS ---


    // --- GLOBAL STATE & CONFIG ---

    let state = { currentUser: null, currentView: 'auth-view', currentItinerary: null, savedItineraries: new Map(), unsubscribeFromTrips: null, currentLanguage: 'it', supportMessages: [], selectedMessageIndex: -1, cachedTranslations: {} };

    let db, auth, mapInstance, flatpickrInstance;

    const appId = 'itineris-global';

    // This firebaseConfig object is now just a placeholder. The app will use the config from localStorage or prompt the user.

    const firebaseConfig = {}; 

    const geminiApiKey = ""; // **PASTE YOUR GEMINI API KEY HERE. It's recommended to do this after downloading the code.**

    state.cachedTranslations['en'] = translations;

    const FREE_TRIP_LIMIT = 3;


    // --- CORE APP INITIALIZATION ---

    async function initializeAppCore() {

        let effectiveConfig = JSON.parse(localStorage.getItem('itinerisFirebaseConfig'));

        

        if (!effectiveConfig) {

            document.getElementById('setup-modal').classList.add('flex');

            document.getElementById('setup-modal').classList.remove('hidden');

            return; 

        }


        const app = initializeApp(effectiveConfig);

        db = getFirestore(app);

        auth = getAuth(app);

        await setPersistence(auth, inMemoryPersistence);


        onAuthStateChanged(auth, user => {

            if (user) {

                state.currentUser = { uid: user.uid, email: user.email };

                listenToSavedTrips();

                initializeSupportTickets();

                if(state.currentView === 'auth-view') switchView('dashboard-view');

            } else {

                state.currentUser = null;

                if (state.unsubscribeFromTrips) state.unsubscribeFromTrips();

                state.savedItineraries.clear();

                switchView('auth-view');

            }

            updateNav();

        });


        flatpickrInstance = flatpickr("#dates", { mode: "range", dateFormat: "Y-m-d", minDate: "today" });

        initializeLanguage();


        Object.assign(window, {

            switchView, handleAuth, logout, generateItinerary, saveCurrentItinerary,

            viewSavedItinerary, deleteItinerary, downloadPDF, generateMarketingVideo,

            selectSupportMessage, generateAiReply, sendReply, switchWizardTab,

            generateInspirationItinerary, handleCreateNewTrip, viewFeaturedTrip, saveFirebaseConfig

        });


        const header = document.getElementById('main-header');

        window.addEventListener('scroll', () => header.classList.toggle('frost-glass', window.scrollY > 10));

    }

    

    // --- SETUP FUNCTION ---

    function saveFirebaseConfig() {

        const inputElement = document.getElementById('firebase-config-input');

        let configStr = inputElement.value;

        if (configStr.includes('const firebaseConfig =')) {

            configStr = configStr.substring(configStr.indexOf('{'));

        }

        try {

            const configObj = JSON.parse(configStr);

            if (configObj.apiKey && configObj.projectId) {

                localStorage.setItem('itinerisFirebaseConfig', JSON.stringify(configObj));

                alert('Configurazione salvata! La pagina verrà ricaricata.');

                window.location.reload();

            } else {

                alert('Configurazione non valida. Assicurati di aver incollato l\'oggetto corretto.');

            }

        } catch (e) {

            alert('Errore nel formato del testo incollato. Per favore, incolla l\'oggetto JSON di configurazione di Firebase.');

            console.error(e);

        }

    }


    // --- All other functions (I18N, View Management, Auth, Itinerary, etc.) go here... ---

    // The full JavaScript logic is included below.

    

    async function t(key, replacements = {}) {

        const lang = state.currentLanguage;

        if (!state.cachedTranslations[lang]) await fetchAndCacheTranslations(lang);

        let translation = state.cachedTranslations[lang]?.[key] || state.cachedTranslations['en'][key] || key;

        Object.entries(replacements).forEach(([placeholder, value]) => {

            translation = translation.replace(`{${placeholder}}`, value);

        });

        return translation;

    }

    

    async function updateUIText() {

        document.documentElement.lang = state.currentLanguage;

        for (const el of document.querySelectorAll('[data-translate-key]')) { el.innerHTML = await t(el.dataset.translateKey); }

        for (const el of document.querySelectorAll('[data-translate-placeholder]')) { el.placeholder = await t(el.dataset.translatePlaceholder); }

        const authSwitchP = document.getElementById('auth-switch-text');

        if (authSwitchP) {

            const isRegister = document.getElementById('auth-form').dataset.mode === 'register';

            authSwitchP.innerHTML = `${await t(isRegister ? 'loginPrompt' : 'registerPrompt')} <button onclick="switchView('auth-view', {isRegister: ${!isRegister}})" class="text-indigo-300 hover:underline">${await t(isRegister ? 'loginButtonNav' : 'registerLink')}</button>`;

        }

        for (const id of ['style', 'budget']) {

            const el = document.getElementById(id);

            if(el) {

                const baseKeys = Object.keys(state.cachedTranslations.en[id+'s']);

                el.innerHTML = '';

                for(const key of baseKeys){ el.innerHTML += `<option value="${key}">${await t(id+'s.'+key)}</option>`; }

            }

        }

        if (state.currentUser) document.getElementById('welcome-message').textContent = await t('welcomeMessage', { name: state.currentUser.email.split('@')[0] });

        if(document.getElementById('keyword-list')) {

            const keywords = await Promise.all([t('adKeyword1'), t('adKeyword2'), t('adKeyword3')]);

            document.getElementById('keyword-list').innerHTML = keywords.map(kw => `<span class="text-xs bg-white/10 px-2 py-1 rounded">${kw}</span>`).join('');

        }

        const locale = state.currentLanguage === 'zh' ? 'zh' : (flatpickr.l10ns[state.currentLanguage] ? state.currentLanguage : 'default');

        if (flatpickrInstance) flatpickrInstance.set('locale', locale);

        if(state.currentView === 'support-view') renderSupportInbox();

    }

    

    async function setLanguage(lang) {

        state.currentLanguage = lang;

        localStorage.setItem('travelGeniusLang', lang);

        await updateUIText();

    }

    

    function initializeLanguage() {

        const langSwitcher = document.getElementById('language-switcher');

        languages.forEach(lang => { langSwitcher.add(new Option(lang.name, lang.code)); });

        langSwitcher.addEventListener('change', (e) => setLanguage(e.target.value));

        const initialLang = localStorage.getItem('travelGeniusLang') || navigator.language.split('-')[0];

        const supportedLang = languages.find(l => l.code === initialLang);

        langSwitcher.value = supportedLang ? initialLang : 'en';

        setLanguage(langSwitcher.value);

    }

    

    async function fetchAndCacheTranslations(lang) {

        if(state.cachedTranslations[lang]) return;

        console.log(`Fetching translations for: ${lang}`);

        try {

            const aiResponse = await getAiGeneratedContent({ langName: languages.find(l=>l.code === lang).name, sourceJson: JSON.stringify(translations) }, 'translationPrompt');

            state.cachedTranslations[lang] = aiResponse;

        } catch(e) {

            console.error(`Could not fetch translations for ${lang}`, e);

            state.cachedTranslations[lang] = state.cachedTranslations.en; // Fallback

        }

    }

    async function switchView(viewId, params = {}) { 

        document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));

        document.getElementById(viewId).classList.add('active');

        state.currentView = viewId;

        window.scrollTo(0, 0);

        if (viewId === 'auth-view') {

            document.getElementById('auth-form').dataset.mode = params.isRegister ? 'register' : 'login';

            document.getElementById('auth-form').reset();

            updateUIText();

        } else if (viewId === 'support-view') {

            renderSupportInbox();

            if (state.selectedMessageIndex === -1) {

                renderMessageDetail(null);

            }

        } else {

             updateUIText();

        }

    }

    async function updateNav() { 

        const isUser = !!state.currentUser;

        document.getElementById('nav-auth-links').classList.toggle('hidden', isUser);

        document.getElementById('nav-user-dash').classList.toggle('hidden', !isUser);

        document.getElementById('nav-user-dash').classList.toggle('flex', isUser);

        if(isUser) updateUIText();

    }

    async function handleAuth(event) {

        event.preventDefault();

        const form = event.target;

        const [email, password, isRegister] = [form.email.value, form.password.value, form.dataset.mode === 'register'];

        try {

            if (isRegister) await createUserWithEmailAndPassword(auth, email, password);

            else await signInWithEmailAndPassword(auth, email, password);

        } catch (error) { alert(await t('authError', { message: error.message })); }

    }

    async function logout() { await signOut(auth); }

    function switchWizardTab(tab) { 

        const isPlan = tab === 'plan';

        document.getElementById('plan-trip-tab').classList.toggle('active', isPlan);

        document.getElementById('inspire-me-tab').classList.toggle('active', !isPlan);

        document.getElementById('plan-trip-form-container').classList.toggle('hidden', !isPlan);

        document.getElementById('inspire-me-form-container').classList.toggle('hidden', isPlan);

    }

    function listenToSavedTrips() { 

        if (!state.currentUser) return;

        if (state.unsubscribeFromTrips) state.unsubscribeFromTrips(); 

        const q = query(collection(db, `/artifacts/${appId}/users/${state.currentUser.uid}/trips`));

        state.unsubscribeFromTrips = onSnapshot(q, (snapshot) => {

            state.savedItineraries.clear();

            snapshot.forEach((doc) => state.savedItineraries.set(doc.id, { ...doc.data(), firestoreId: doc.id }));

            if(state.currentView === 'dashboard-view') renderDashboard();

        }, (error) => console.error("Error listening to trips:", error));

    }

    async function renderDashboard() { 

        const listContainer = document.getElementById('saved-trips-list');

        if (state.savedItineraries.size === 0) {

            listContainer.innerHTML = `<p class="col-span-full text-white/60 text-center py-12">${await t('noTripsSaved')}</p>`;

            return;

        }

        let cardsHtml = '';

        for (const itinerary of Array.from(state.savedItineraries.values())) {

            cardsHtml += `<div class="frost-glass p-6 rounded-2xl flex flex-col justify-between hover:border-indigo-400/50 transition-all duration-300 transform hover:-translate-y-1"><div><h4 class="font-serif text-2xl text-white">${itinerary.destination}</h4><p class="text-sm text-white/60 mt-1">${itinerary.dateRange} (${await t('days', {count: itinerary.duration})})</p></div><div class="mt-4 flex gap-2"><button onclick="viewSavedItinerary('${itinerary.firestoreId}')" class="flex-grow bg-white/10 text-white px-3 py-2 rounded-md text-sm hover:bg-white/20 transition">${await t('viewButton')}</button><button onclick="deleteItinerary('${itinerary.firestoreId}')" class="bg-red-500/20 text-red-300 px-3 py-2 rounded-md text-sm hover:bg-red-500/40 transition">${await t('deleteButton')}</button></div></div>`;

        }

        listContainer.innerHTML = cardsHtml;

    }

    async function _generateAndShowItinerary(preferences, promptKey, isFeatured = false) { 

        if (!state.currentUser) { alert(await t('loginToProceed')); return switchView('auth-view'); }

        document.getElementById('loading-title').innerHTML = await t('loadingTitle');

        document.getElementById('loading-subtitle').innerHTML = await t('loadingSubtitle');

        switchView('loading-view');

        try {

            const aiResponse = await getAiGeneratedContent(preferences, promptKey);

            const itineraryData = {

                destination: aiResponse.destination,

                dateRange: preferences.dateRange || `7 ${await t('days')}`,

                duration: preferences.duration || 7,

                startDate: preferences.startDate,

                endDate: preferences.endDate,

                ...aiResponse, 

                id: Date.now().toString(),

                isFeatured: isFeatured

            };

            state.currentItinerary = itineraryData;

            await renderItinerary(state.currentItinerary);

            switchView('itinerary-view');

        } catch(error) {

            alert(await t('apiError', {message: error.message}));

            switchView('wizard-view');

        }

    }

    async function generateItinerary(event) { 

        event.preventDefault();

        const form = event.target;

        const [destination, dates, style, budget] = [form.destination.value, form.dates.value, form.style.value, form.budget.value];

        if (!dates) { alert(await t('datesRequiredError')); return; }

        const [startDate, endDate] = dates.split(' to ');

        const duration = Math.round((new Date(endDate || startDate) - new Date(startDate)) / (1000 * 60 * 60 * 24)) + 1;

        const preferences = { destination, dateRange: dates, duration, style, budget, startDate, endDate, currentLanguage: state.cachedTranslations[state.currentLanguage].langName };

        _generateAndShowItinerary(preferences, 'itineraryPrompt');

    }

    async function generateInspirationItinerary(event) { 

        event.preventDefault();

        const userInput = document.getElementById('inspiration-prompt').value;

        const preferences = { userInput, currentLanguage: state.cachedTranslations[state.currentLanguage].langName };

        _generateAndShowItinerary(preferences, 'inspirationPrompt');

    }

    async function renderItinerary(itinerary) { 

        const container = document.getElementById('itinerary-content-wrapper');

        const { destination, dateRange, duration, flights, hotels, activities, iataCode, startDate, endDate } = itinerary;

        const skyscannerUrl = iataCode && startDate ? `https://www.skyscanner.it/trasporti/voli/from-iata/${iataCode}/${startDate?.replace(/-/g, '').substring(2)}/${endDate?.replace(/-/g, '').substring(2)}` : (iataCode ? `https://www.skyscanner.it/trasporti/voli/from-iata/${iataCode}`: null);

        const bookingUrl = `https://www.booking.com/searchresults.it.html?ss=${encodeURIComponent(destination)}`;

        const getyourguideUrl = `https://www.getyourguide.it/s/?q=${encodeURIComponent(destination)}`;

        

        async function renderSection(titleKey, items, icon, url, buttonKey, renderItem) {

            const translatedTitle = await t(titleKey);

            const translatedButton = buttonKey ? await t(buttonKey) : '';

            const translatedItems = items && items.length > 0 ? (await Promise.all(items.map(renderItem))).join('') : `<p class="text-white/50 p-4 bg-white/5 rounded-lg">${await t('noSuggestions')}</p>`;

            return `<div><div class="flex justify-between items-center mb-4"><h3 class="text-2xl font-serif text-white flex items-center gap-3"><span class="material-symbols-outlined text-indigo-300">${icon}</span>${translatedTitle}</h3>${url ? `<a href="${url}" target="_blank" class="bg-white/10 text-white text-xs font-bold py-2 px-3 rounded-lg hover:bg-white/20 transition">${translatedButton}</a>` : ''}</div><div class="space-y-3">${translatedItems}</div></div>`;

        }

        

        const flightsSection = await renderSection('flightsTitle', flights, 'flight', skyscannerUrl, 'searchOnSkyscanner', async f => `<div class="bg-white/5 p-4 rounded-lg"><strong>${f.airline}</strong><span class="text-white/60"> - ${await t('priceEstimate')}: ${f.price}€ (${await t('stops', {count: f.stops})})</span></div>`);

        const hotelsSection = await renderSection('hotelsTitle', hotels, 'hotel', bookingUrl, 'searchOnBooking', async h => `<div class="bg-white/5 p-4 rounded-lg"><strong>${h.name}</strong><span class="text-white/60"> (${h.rating} ★) - ${await t('priceFrom')} ${h.price}€/${await t('priceNight')}</span></div>`);

        const activitiesSection = await renderSection('activitiesTitle', activities, 'local_activity', getyourguideUrl, 'viewOnGetYourGuide', async a => `<div class="bg-white/5 p-4 rounded-lg"><strong>${a.name}</strong><span class="text-white/60"> (${a.type})</span></div>`);

        

        container.innerHTML = `<div id="pdf-content" class="p-2"><h2 class="text-5xl font-serif text-white">${destination}</h2><p class="text-lg text-indigo-300 font-semibold mt-1 mb-6">${dateRange} (${await t('days', {count: duration})})</p><div id="map"></div><div class="grid md:grid-cols-2 gap-x-12 gap-y-8 mt-8">${flightsSection}${hotelsSection}</div><div class="mt-8">${activitiesSection}</div></div>`;

        const saveBtn = document.getElementById('save-trip-btn');

        const isAlreadySaved = !!itinerary.firestoreId || itinerary.isFeatured;

        saveBtn.disabled = isAlreadySaved;

        saveBtn.innerHTML = isAlreadySaved ? `<span class="material-symbols-outlined -mb-1 mr-1">check_circle</span> ${await t('tripSavedButton')}` : `<span class="material-symbols-outlined -mb-1 mr-1">favorite</span> ${await t('saveTripButton')}`;

        if (itinerary.coords) setTimeout(() => initMap(itinerary.coords, itinerary.destination), 0);


        const conciergeContainer = document.createElement('div');

        conciergeContainer.id = 'concierge-section';

        conciergeContainer.className = 'mt-8';

        conciergeContainer.innerHTML = `<div class="flex justify-center"><div class="animate-spin h-6 w-6 text-indigo-400"></div></div>`;

        container.querySelector('#pdf-content').appendChild(conciergeContainer);

        try {

            const conciergeSuggestions = await getAiGeneratedContent({ itineraryJson: JSON.stringify(itinerary), currentLanguage: state.cachedTranslations[state.currentLanguage].langName }, 'conciergePrompt');

            await renderConciergeSection(conciergeSuggestions);

        } catch (e) {

            console.error("Could not fetch concierge suggestions:", e);

            conciergeContainer.innerHTML = '';

        }

    }

    async function saveCurrentItinerary() { 

        if (!state.currentUser || !state.currentItinerary || state.currentItinerary.isFeatured) return;

        if(state.savedItineraries.size >= FREE_TRIP_LIMIT) {

            alert(await t('freeLimitReached'));

            switchView('premium-view');

            return;

        }

        const button = document.getElementById('save-trip-btn');

        button.disabled = true;

        try {

            await addDoc(collection(db, `/artifacts/${appId}/users/${state.currentUser.uid}/trips`), state.currentItinerary);

            alert(await t('tripSavedSuccess'));

            button.innerHTML = `<span class="material-symbols-outlined -mb-1 mr-1">check_circle</span> ${await t('tripSavedButton')}`;

        } catch(error) {

            alert(await t('saveError'));

            button.disabled = false;

        }

    }

    async function deleteItinerary(firestoreId) { 

        if (!state.currentUser || !firestoreId) return;

        if (confirm(await t('deleteConfirm'))) {

            try {

                await deleteDoc(doc(db, `/artifacts/${appId}/users/${state.currentUser.uid}/trips/${firestoreId}`));

            } catch (error) { alert(await t('deleteError')); }

        }

    }

    async function viewSavedItinerary(firestoreId) { 

        const itinerary = state.savedItineraries.get(firestoreId);

        if (itinerary) {

            state.currentItinerary = itinerary;

            await renderItinerary(itinerary);

            switchView('itinerary-view');

        }

    }

    async function handleCreateNewTrip() { 

        if(state.savedItineraries.size >= FREE_TRIP_LIMIT) {

            alert(await t('freeLimitReached'));

            switchView('premium-view');

        } else {

            switchView('wizard-view');

        }

    }

    async function viewFeaturedTrip() { 

        const preferences = { destination: 'Svizzera', duration: 7, style: 'lusso', budget: 'lusso', currentLanguage: state.cachedTranslations[state.currentLanguage].langName };

        _generateAndShowItinerary(preferences, 'itineraryPrompt', true);

    }

    async function renderConciergeSection(suggestions) { 

        const container = document.getElementById('concierge-section');

        if (!container) return;

        async function renderService(service) {

            if (!service || !service.is_relevant) return '';

            const serviceKey = service.service_type.toLowerCase();

            return `<div class="bg-white/5 p-4 rounded-lg flex items-center gap-4"> <span class="material-symbols-outlined text-3xl text-amber-300">${await t(`concierge.${serviceKey}.icon`)}</span> <div> <h5 class="font-bold text-white">${await t(`concierge.${serviceKey}.title`)}</h5> <p class="text-sm text-white/70">${service.suggestion_text}</p> </div> <a href="${service.affiliate_link}" target="_blank" class="ml-auto bg-white/10 text-white text-xs font-bold py-2 px-3 rounded-lg hover:bg-white/20 transition">${await t('viewOfferButton')}</a> </div>`;

        }

        container.innerHTML = `<h3 class="text-2xl font-serif text-white mb-4 flex items-center gap-3"> <span class="material-symbols-outlined text-amber-300">concierge</span> ${await t('conciergeTitle')} <span class="pro-badge">PRO</span> </h3> <div class="space-y-3"> ${(await Promise.all(suggestions.services.map(renderService))).join('')} </div>`;

    }

    async function generateMarketingVideo(event) { 

        event.preventDefault();

        const theme = document.getElementById('video-theme').value;

        document.getElementById('loading-title').innerHTML = await t('videoLoadingTitle');

        document.getElementById('loading-subtitle').innerHTML = await t('videoLoadingSubtitle');

        switchView('loading-view');

        try {

            const aiResponse = await getAiGeneratedContent({ theme, currentLanguage: state.cachedTranslations[state.currentLanguage].langName }, 'videoPrompt');

            await renderVideoStoryboard(aiResponse);

            switchView('marketing-view');

        } catch(error) {

            alert(await t('apiError', {message: error.message}));

            switchView('marketing-view');

        }

    }

    async function renderVideoStoryboard(storyboard) {

        const container = document.getElementById('video-storyboard-result');

        let scenesHtml = '';

        for(let i=0; i<storyboard.scenes.length; i++){

            const scene = storyboard.scenes[i];

            scenesHtml += `<div class="p-4 bg-white/5 rounded-lg"> <h5 class="font-bold text-indigo-300">${await t('scene')} ${i + 1}: ${scene.title}</h5> <p class="text-sm text-white/80 mt-2"><strong class="text-white/50">${await t('visual')}:</strong> ${scene.visual_description}</p> <p class="text-sm text-white/80 mt-1"><strong class="text-white/50">${await t('voiceover')}:</strong> <em>"${scene.voiceover}"</em></p> </div>`;

        }

        container.innerHTML = `<div class="mt-8 border-t border-white/10 pt-6"> <h4 class="font-serif text-3xl text-white">${storyboard.title}</h4> <p class="text-white/60 mt-2 mb-6">${storyboard.description}</p> <div class="space-y-4">${scenesHtml}</div> </div>`;

    }

    function initializeSupportTickets() { 

        state.supportMessages = [{ sender: 'Laura Bianchi', subjectKey: 'supportSubject1', bodyKey: 'supportBody1', status: 'new' }, { sender: 'Kenji Tanaka', subjectKey: 'supportSubject2', bodyKey: 'supportBody2', status: 'new' }, { sender: 'Sven Müller', subjectKey: 'supportSubject3', bodyKey: 'supportBody3', status: 'replied' }]; 

        state.selectedMessageIndex = -1;

    }

    async function renderSupportInbox() { 

        const listContainer = document.getElementById('inbox-list');

        let inboxHtml = '';

        for(let i=0; i < state.supportMessages.length; i++) {

            const msg = state.supportMessages[i];

            inboxHtml += `<div onclick="selectSupportMessage(${i})" class="p-4 border-b border-white/10 cursor-pointer hover:bg-white/5 ${state.selectedMessageIndex === i ? 'bg-indigo-500/20' : ''}"> <div class="flex justify-between items-center"> <p class="font-bold text-white">${msg.sender}</p> ${msg.status === 'new' ? `<span class="text-xs font-bold text-white bg-green-500 px-2 py-0.5 rounded-full">${await t('statusNew')}</span>` : ''} </div> <p class="text-sm text-white/80 truncate">${await t(msg.subjectKey)}</p> </div>`;

        }

        listContainer.innerHTML = inboxHtml;

    }

    async function renderMessageDetail(message) {

        const detailContainer = document.getElementById('message-detail-view');

        if (!message) {

            detailContainer.innerHTML = `<div class="flex-grow flex items-center justify-center"><p class="text-white/50">${await t('noMessageSelected')}</p></div>`;

            return;

        }

        detailContainer.innerHTML = `<div class="p-4 border-b border-white/10"> <h4 class="font-bold text-xl text-white">${await t(message.subjectKey)}</h4> <p class="text-sm text-white/60">${await t('from')}: ${message.sender}</p> </div> <div class="p-4 flex-grow overflow-y-auto"> <p class="text-white/90 whitespace-pre-wrap">${await t(message.bodyKey)}</p> </div> <div class="p-4 border-t border-white/10"> <h5 class="font-bold text-white mb-2">${await t('suggestedReply')}</h5> <textarea id="ai-reply-textarea" rows="5" class="w-full p-3 rounded-lg form-input" placeholder="${await t('generateReplyPlaceholder')}"></textarea> <div id="ai-reply-loader" class="hidden text-center p-4"><div class="animate-spin h-6 w-6 text-indigo-400 mx-auto"></div></div> <div class="flex gap-4 mt-4"> <button onclick="generateAiReply()" class="flex-grow bg-gradient-to-r from-teal-500 to-cyan-500 text-white font-bold py-2 px-4 rounded-lg hover:opacity-90 transition">${await t('generateReplyButton')}</button> <button onclick="sendReply()" class="flex-grow bg-indigo-500 text-white font-bold py-2 px-4 rounded-lg hover:bg-indigo-600 transition">${await t('sendReplyButton')}</button> </div> </div>`;

    }

    async function selectSupportMessage(index) { 

        state.selectedMessageIndex = index;

        await renderSupportInbox();

        await renderMessageDetail(state.supportMessages[index]);

    }

    async function generateAiReply() { 

        if(state.selectedMessageIndex === -1) return;

        const message = state.supportMessages[state.selectedMessageIndex];

        const loader = document.getElementById('ai-reply-loader');

        const textarea = document.getElementById('ai-reply-textarea');

        loader.classList.remove('hidden');

        textarea.value = '';

        try {

            const aiResponse = await getAiGeneratedContent({ customerMessage: await t(message.bodyKey), currentLanguage: state.cachedTranslations[state.currentLanguage].langName }, 'supportPrompt');

            textarea.value = aiResponse.reply;

        } catch(error) {

            alert(await t('apiError', {message: error.message}));

            textarea.placeholder = await t('apiErrorPlaceholder');

        } finally {

            loader.classList.add('hidden');

        }

    }

    async function sendReply() { 

        if(state.selectedMessageIndex === -1) return;

        const textarea = document.getElementById('ai-reply-textarea');

        if(!textarea.value) { alert(await t('emptyReplyError')); return; }

        state.supportMessages[state.selectedMessageIndex].status = 'replied';

        alert(await t('replySentSuccess'));

        await renderSupportInbox();

        await renderMessageDetail(null);

        state.selectedMessageIndex = -1;

    }

    function initMap(coords, destination) { 

        if (mapInstance) mapInstance.remove();

        mapInstance = L.map('map').setView([coords.lat, coords.lon], 13);

        L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', { attribution: '&copy; OpenStreetMap &copy; CARTO' }).addTo(mapInstance);

        L.marker([coords.lat, coords.lon]).addTo(mapInstance).bindPopup(`<b>${destination}</b>`).openPopup();

    }

    async function downloadPDF() { 

        const content = document.getElementById('pdf-content');

        const button = event.target;

        button.textContent = await t('creatingPdf'); button.disabled = true;

        html2canvas(content, { scale: 2, useCORS: true, backgroundColor: '#0c0a18' }).then(canvas => {

            const { jsPDF } = window.jspdf;

            const pdf = new jsPDF({ orientation: 'p', unit: 'mm', format: 'a4' });

            const pdfWidth = pdf.internal.pageSize.getWidth();

            const pdfHeight = (canvas.height * pdfWidth) / canvas.width;

            pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, pdfWidth, pdfHeight);

            pdf.save(`itinerario-itineris-${state.currentItinerary.destination.toLowerCase().replace(/\s/g,'-')}.pdf`);

            button.textContent = t('downloadPdfButton'); button.disabled = false;

        }).catch(async () => {

            alert(await t('pdfError'));

            button.textContent = await t('downloadPdfButton'); button.disabled = false;

        });

    }

    async function getAiGeneratedContent(preferences, promptKey) {

        if (!geminiApiKey) {

             throw new Error("Gemini API key is missing. Please add it to the script.");

        }

        const prompt = await t(promptKey, preferences);

        let jsonSchema;

        if (promptKey === 'itineraryPrompt') {

            jsonSchema = { type: "OBJECT", properties: { "flights": { type: "ARRAY", items: { type: "OBJECT", properties: { "airline": { type: "STRING" }, "price": { type: "NUMBER" }, "stops": { type: "NUMBER" } }, required: ["airline", "price", "stops"] }}, "hotels": { type: "ARRAY", items: { type: "OBJECT", properties: { "name": { type: "STRING" }, "rating": { type: "NUMBER" }, "price": { type: "NUMBER" } }, required: ["name", "rating", "price"] }}, "activities": { type: "ARRAY", items: { type: "OBJECT", properties: { "name": { type: "STRING" }, "type": { type: "STRING" } }, required: ["name", "type"] }}, "coords": { type: "OBJECT", properties: { "lat": { type: "NUMBER" }, "lon": { type: "NUMBER" } }, required: ["lat", "lon"] }, "iataCode": { type: "STRING" }} };

        } else if (promptKey === 'inspirationPrompt') {

             jsonSchema = { type: "OBJECT", properties: { "destination": { "type": "STRING" }, "flights": { type: "ARRAY", items: { type: "OBJECT", properties: { "airline": { type: "STRING" }, "price": { type: "NUMBER" }, "stops": { type: "NUMBER" } }, required: ["airline", "price", "stops"] }}, "hotels": { type: "ARRAY", items: { type: "OBJECT", properties: { "name": { type: "STRING" }, "rating": { type: "NUMBER" }, "price": { type: "NUMBER" } }, required: ["name", "rating", "price"] }}, "activities": { type: "ARRAY", items: { type: "OBJECT", properties: { "name": { type: "STRING" }, "type": { type: "STRING" } }, required: ["name", "type"] }}, "coords": { type: "OBJECT", properties: { "lat": { type: "NUMBER" }, "lon": { type: "NUMBER" } }, required: ["lat", "lon"] }, "iataCode": { type: "STRING" }} };

        } else if (promptKey === 'videoPrompt') {

            jsonSchema = { type: "OBJECT", properties: { "title": { type: "STRING" }, "description": { type: "STRING" }, "scenes": { type: "ARRAY", items: { type: "OBJECT", properties: { "title": { type: "STRING" }, "visual_description": { "type": "STRING" }, "voiceover": { "type": "STRING" } }, required: ["title", "visual_description", "voiceover"] }} } };

        } else if (promptKey === 'supportPrompt') {

             jsonSchema = { type: "OBJECT", properties: { "reply": { type: "STRING" } } };

        } else if (promptKey === 'conciergePrompt') {

             jsonSchema = { type: "OBJECT", properties: { "services": { type: "ARRAY", items: { type: "OBJECT", properties: { "service_type": { "type": "STRING" }, "is_relevant": { type: "BOOLEAN" }, "suggestion_text": { "type": "STRING" }, "affiliate_link": { type: "STRING" } } } } } };

        } else { // translationPrompt

             jsonSchema = { type: "OBJECT", properties: translations, required: Object.keys(translations) };

        }

        

        const payload = { contents: [{ role: "user", parts: [{ text: prompt }] }], generationConfig: { responseMimeType: "application/json", responseSchema: jsonSchema } };

        const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${geminiApiKey}`;

        const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });

        if (!response.ok) throw new Error(`API Error: ${response.status} ${await response.text()}`);

        const result = await response.json();

        if (result.candidates?.[0]?.content?.parts?.[0]?.text) return JSON.parse(result.candidates[0].content.parts[0].text);

        throw new Error(await t('noAIContent'));

    }


    initializeAppCore();

</script>


</body>

</html>