document.addEventListener('DOMContentLoaded', function () {
    const searchForm = document.getElementById('searchForm');
    const videoContainer = document.getElementById('videoContainer');
    const regenerateBtn = document.getElementById('regenerateBtn');
    const yearInput = document.getElementById('yearInput');
    let lastSearchedYear = '';

    function showSpinner() {
        videoContainer.innerHTML = `<div class="d-flex justify-content-center align-items-center" style="height: 100%;"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>`;
    }

    function showError(message) {
        videoContainer.innerHTML = `<div class="alert alert-warning" role="alert">${message}</div>`;
        regenerateBtn.style.display = 'none';
    }

    function displayVideo(videoUrl) {
        if (videoUrl.includes('youtube.com')) {
            videoContainer.innerHTML = `<iframe src="${videoUrl}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
        } else {
            videoContainer.innerHTML = `<video controls autoplay muted playsinline src="${videoUrl}" style="width: 100%; height: 100%;"></video>`;
        }
        regenerateBtn.style.display = 'block';
    }

    async function fetchAndDisplayAd(year) {
        lastSearchedYear = year;
        showSpinner();
        regenerateBtn.style.display = 'none';

        try {
            const response = await fetch(`api.php?year=${year}`);
            if (!response.ok) {
                throw new Error('Network response was not ok.');
            }
            const data = await response.json();

            if (data.videoUrl) {
                displayVideo(data.videoUrl);
            } else {
                showError('No video found for this year. Please try another.');
            }
        } catch (error) {
            console.error('Error fetching ad:', error);
            showError('Failed to fetch video. Please try again later.');
        }
    }

    searchForm.addEventListener('submit', function (e) {
        e.preventDefault();
        const year = yearInput.value;
        if (year) {
            fetchAndDisplayAd(year);
        }
    });

    regenerateBtn.addEventListener('click', function () {
        if (lastSearchedYear) {
            fetchAndDisplayAd(lastSearchedYear);
        }
    });
});