document.addEventListener('DOMContentLoaded', function() {

    // Function to render search results from a response object
    function renderResults(data) {
        const resultsDiv = document.getElementById('results');
        resultsDiv.innerHTML = '<h5>Suchergebnisse:</h5>';

        if (data.results && data.results.length > 0) {
            data.results.forEach(file => {
                const card = document.createElement('div');
                const filenameWithoutExtension = file.filename.split('.').slice(0, -1).join('.');
                const parentFolder = file.relative_path.split('/').slice(0, -1).join('/');
                const transcriptURL = '/transcript/' + parentFolder + '/Transkription/' + filenameWithoutExtension + '.md';
                card.className = 'card';
                card.innerHTML = `
                    <div class="card-body">
                        <p><button class="btn btn-light" onclick="player.loadTrack('${file.relative_path}')" style="width:100%;">🔊 ${filenameWithoutExtension}</button></p>
                        <p><button onclick="window.open('/path/${file.relative_path}', '_self');" class="btn btn-light btn-sm" style="width:100%;">📁 ${parentFolder}</button></p>
                        <p class="card-text">Anzahl Downloads: ${file.hitcount}</p>
                        ${ file.performance_date !== undefined ? `<p class="card-text">Datum: ${file.performance_date}</p>` : ``}
                        ${ file.transcript_hits  !== undefined ? `<p class="card-text">Treffer im Transkript: ${file.transcript_hits} <a href="#" class="show-transcript" data-url="${transcriptURL}" highlight="${file.query}">&#128196;</a></p>` : ``}
                    </div>
                `;
                resultsDiv.appendChild(card);
            });
            attachEventListeners();
        } else {
            resultsDiv.innerHTML = '<p>No results found.</p>';
        }
    }

    // Restore previous search response if available from localStorage
    const previousResponse = localStorage.getItem("searchResponse");
    if (previousResponse) {
        try {
            const data = JSON.parse(previousResponse);
            renderResults(data);
        } catch (e) {
            console.error('Error parsing searchResponse from localStorage:', e);
        }
    }

    // Restore previous search word (Suchwort) if available
    const previousQuery = localStorage.getItem("searchQuery");
    if (previousQuery) {
        document.getElementById('query').value = previousQuery;
    }

    // Restore previous selected category if available, otherwise default remains "Alles"
    const previousCategory = localStorage.getItem("searchCategory");
    if (previousCategory !== null) {
        const radio = document.querySelector('input[name="category"][value="' + previousCategory + '"]');
        if (radio) {
            radio.checked = true;
        }
    }

    // Restore the checkbox state for "Im Transkript suchen"
    const previousIncludeTranscript = localStorage.getItem("searchIncludeTranscript");
    if (previousIncludeTranscript !== null) {
        document.getElementById('includeTranscript').checked = (previousIncludeTranscript === 'true');
    }

    // Form submission event
    document.getElementById('searchForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const query = document.getElementById('query').value.trim();
        const includeTranscript = document.getElementById('includeTranscript').checked;

        // Get the selected category radio button, if any
        const categoryRadio = document.querySelector('input[name="category"]:checked');
        const category = categoryRadio ? categoryRadio.value : '';

        // Prevent accidental re-selection of already selected radio buttons
        const radios = document.querySelectorAll('input[name="category"]');
        radios.forEach(radio => {
            radio.addEventListener('mousedown', function(e) {
                this.wasChecked = this.checked;
            });
            radio.addEventListener('click', function(e) {
                if (this.wasChecked) {
                    this.checked = false;
                    this.wasChecked = false;
                    e.preventDefault();
                }
            });
        });

        // Prepare form data for the fetch request
        // Send the query and the category as separate parameters.
        const formData = new FormData();
        formData.append('query', query);
        formData.append('category', category);
        formData.append('folder', document.getElementById('folder').value);
        formData.append('datefrom', document.getElementById('datefrom').value);
        formData.append('dateto', document.getElementById('dateto').value);
        formData.append('includeTranscript', includeTranscript);

        fetch('/searchcommand', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            // Render the results
            renderResults(data);
            // Store the raw response in localStorage
            try {
                localStorage.setItem("searchResponse", JSON.stringify(data));
            } catch (e) {
                console.error('Error saving searchResponse to localStorage:', e);
            }
            // Save the search word, selected category, and checkbox state in localStorage
            localStorage.setItem("searchQuery", query);
            localStorage.setItem("searchCategory", category);
            localStorage.setItem("searchIncludeTranscript", includeTranscript);
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });

    // Clear button event handler
    document.getElementById('clearBtn').addEventListener('click', function() {
        // Remove stored items
        localStorage.removeItem("searchResponse");
        localStorage.removeItem("searchQuery");
        localStorage.removeItem("searchCategory");
        localStorage.removeItem("folder");
        localStorage.removeItem("datefrom");
        localStorage.removeItem("dateto");
        localStorage.removeItem("searchIncludeTranscript");
        // Reset form fields to defaults
        document.getElementById('query').value = '';
        document.querySelector('input[name="category"][value=""]').checked = true;
        const otherRadios = document.querySelectorAll('input[name="category"]:not([value=""])');
        otherRadios.forEach(radio => radio.checked = false);
        document.getElementById('folder').value = ''; // Reset to "Alle"
        document.getElementById('datefrom').value = ''; // Reset date from
        document.getElementById('dateto').value = ''; // Reset date to
        document.getElementById('includeTranscript').checked = false;
        // Clear the results div
        document.getElementById('results').innerHTML = '';
    });

    // Back button event handler - redirect to the root path
    document.getElementById('backBtn').addEventListener('click', function() {
        // window.location.href = '/';
        viewMain();
    });
});

function syncThemeColor() {
    // read the CSS variable from :root (or any selector)
    const cssVar = getComputedStyle(document.documentElement)
                       .getPropertyValue('--dark-background').trim();
    if (cssVar) {
      document
        .querySelector('meta[name="theme-color"]')
        .setAttribute('content', cssVar);
    }
  }
  
  // sync once on load
  document.addEventListener('DOMContentLoaded', syncThemeColor);