<nav id="main-nav" class="relative bg-blue-600 rounded-lg mt-1 m-2 shadow-md transition-all duration-300">
    <!-- Desktop Navigation Bar -->
    <div class="flex justify-between items-center h-12 px-4 sm:px-6 overflow-x-auto whitespace-nowrap">
        <!-- Logo / Left section -->
        <div class="flex items-center flex-shrink-0 md:w-32">
            <h2 class="text-xl font-bold text-white hover:scale-110 transition duration-200">
                <a href="{% url 'homepage:home' %}">qivip</a>
            </h2>
        </div>

        <!-- Desktop Search (centered on screen) - Hidden on mobile -->
        <div class="hidden md:flex justify-center items-center absolute left-1/2 transform -translate-x-1/2 min-w-40 ">
            <form method="get" action="{% url link|default:'library:overview_quiz' %}" class="mr-2 ml-2 flex items-center justify-center w-screen max-w-sm bg-white rounded-full px-4 py-1 shadow-md dark:bg-gray-900">
                <input id="quiz-search-desktop" list="quiz-names-desktop" type="text" name="search" placeholder="Suche ..." value="{{ request.GET.search }}"
                       class="text-sm w-full px-3 py-1 text-black bg-transparent focus:outline-none lg:text-base dark:text-white">
                <button class="py-1 text-blue-600">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5 md:size-6">
                        <path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
                    </svg>              
                </button>
            </form>
        </div>
    
        <!-- Desktop Navigation Links - Hidden on mobile -->
        <div class="hidden md:flex items-center">
            <ul class="flex space-x-4 qp-nav-list">
                {% if show_search %}
                <li><a href="{% url 'library:overview_quiz' %}">Bibliothek</a></li>
                {% else%}
                <li><a href="{% url 'library:overview_quiz' %}">Bibliothek</a></li>
                {% endif %}
                {% if user.is_authenticated %}
                <li><a href="{% url 'accounts:home' %}">Konto</a></li>
                {% else %}
                <li><a href="{% url 'accounts:login' %}">Anmelden</a></li>
                {% endif %}
            </ul>
        </div>

        <!-- Mobile menu button - Only visible on mobile -->
        <div class="flex md:hidden items-center">
            <button id="mobile-menu-button" class="text-white focus:outline-none">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                </svg>
            </button>
        </div>
    </div>

    <!-- Mobile Navigation Menu - Hidden by default - FULLWIDTH DROPDOWN -->
    <div id="mobile-menu" class="hidden absolute w-full z-50 md:hidden opacity-0 transform -translate-y-2 transition-all duration-300 ">
        <div class="bg-blue-500 pt-3 pb-4 rounded-b-lg shadow-inner">
            <!-- Search in mobile menu -->
            <form method="get" action="{% url link|default:'library:overview_quiz' %}" class="px-4 mb-4 ">
                <div class="flex items-center justify-center bg-white rounded-full px-4 py-2 shadow-md dark:bg-gray-900">
                    <input id="quiz-search-mobile" list="quiz-names-mobile" type="text" name="search" placeholder="Suche ..." value="{{ request.GET.search }}"
                            class="w-full text-sm px-2 text-black bg-transparent focus:outline-none dark:text-white">
                    <button class="text-blue-600">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" 
                                stroke="currentColor" class="size-5">
                            <path stroke-linecap="round" stroke-linejoin="round" 
                                    d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
                        </svg>              
                    </button>
                </div>

                <datalist id="quiz-names-desktop">
                    {% for quiz in quiz_names %}
                        <option value="{{ quiz.name }}">
                    {% endfor %}
                </datalist>

                <datalist id="quiz-names-mobile">
                    {% for quiz in quiz_names %}
                        <button value="{{ quiz.name }}" onclick="performSearch(this.value)"><option value="{{ quiz.name }}" ></option></button>
                    {% endfor %}
                </datalist>
                
                

              
                {{ quiz_names|json_script:"quiz-names-data" }}

                <script>
                    async function fetchQuizNames() {
                        try {
                            const response = await fetch("{% url 'library:quiz_names_json' %}");
                            if (!response.ok) throw new Error("Netzwerkfehler");
                            const data = await response.json();
                            if (Array.isArray(data)) return data;
                        } catch (err) {
                            console.error("Fehler beim Laden der Quiz-Namen:", err);
                        }
                        return [];
                    }
                
                    function setupAutocomplete(inputId, datalistId, quizNames) {
                        const searchInput = document.getElementById(inputId);
                        const datalist = document.getElementById(datalistId);
                        if (!searchInput || !datalist) return;
                
                        // Wenn der Benutzer den Text ändert, Filter anwenden
                        searchInput.addEventListener('input', () => {
                            const value = searchInput.value.toLowerCase();
                            datalist.innerHTML = '';
                            quizNames
                                .filter(name => name.toLowerCase().includes(value))
                                .slice(0, 10)
                                .forEach(name => {
                                    const option = document.createElement('option');
                                    option.value = name;
                                    datalist.appendChild(option);
                                    
                                });
                        });
       

                    }
                
                    // Funktion zum Durchführen der Suche
                    function performSearch(query) {
                        datalist.innerHTML = '';
                        // Hier kann deine Logik zur Verarbeitung der Suche eingefügt werden

                        // Falls du die Seite zu einer Suchergebnisseite weiterleiten möchtest:
                        window.location.href = `{% url 'library:overview_quiz' %}?search=${query}`;
                    }
                
                    document.addEventListener('DOMContentLoaded', async () => {
                        const quizNames = await fetchQuizNames();
                        setupAutocomplete('quiz-search-desktop', 'quiz-names-desktop', quizNames);
                        setupAutocomplete('quiz-search-mobile', 'quiz-names-mobile', quizNames);
                    });
                </script>
                
                    
                
            </form>

            <!-- Mobile Navigation Links -->
            <div class="space-y-2 px-4">
                <a href="{% url 'library:overview_quiz' %}" class="block py-2 text-white font-medium rounded-lg hover:bg-blue-600 transition duration-200">
                    Bibliothek
                </a>
                {% if user.is_authenticated %}
                <a href="{% url 'accounts:home' %}" class="block py-2 text-white font-medium rounded-lg hover:bg-blue-600 transition duration-200">
                    Konto
                </a>
                {% else %}
                <a href="{% url 'accounts:login' %}" class="block py-2 text-white font-medium rounded-lg hover:bg-blue-600 transition duration-200">
                    Anmelden
                </a>
                {% endif %}
            </div>
        </div>
    </div>
</nav>

<!-- Mobile Menu Script -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const mobileMenu = document.getElementById('mobile-menu');
        const mainNav = document.getElementById('main-nav');

        mobileMenuButton.addEventListener('click', function() {
            // Toggle menu visibility
            if (mobileMenu.classList.contains('hidden')) {
                // Show menu
                mobileMenu.classList.remove('hidden');
                // Entferne unten abgerundete Ecken der Navbar wenn Menü offen
                mainNav.classList.remove('rounded-lg');
                mainNav.classList.add('rounded-t-lg');
                // Animation einfahren
                setTimeout(() => {
                    mobileMenu.classList.remove('opacity-0', 'transform', '-translate-y-2');
                    mobileMenu.classList.add('opacity-100');
                }, 50);
            } else {
                // Ausfahren Animation
                mobileMenu.classList.add('opacity-0', 'transform', '-translate-y-2');
                mobileMenu.classList.remove('opacity-100');
                // Nach der Animation verstecken
                setTimeout(() => {
                    mobileMenu.classList.add('hidden');
                    // Stelle die abgerundeten Ecken wieder her
                    mainNav.classList.remove('rounded-t-lg');
                    mainNav.classList.add('rounded-lg');
                }, 300);
            }
        });
    });
</script>
