document.addEventListener('DOMContentLoaded', function () {
    let lastScrollTop = 0;
    const topbar = document.getElementById('topbar');

    // Scroll event listener for topbar behavior
    window.addEventListener('scroll', function () {
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        if (scrollTop > lastScrollTop) {
            // Scrolling down
            topbar.style.transform = 'translateY(-100%)';
            topbar.classList.add('transparent');
        } else {
            // Scrolling up
            topbar.style.transform = 'translateY(0)';
            if (scrollTop === 0) {
                // At the top of the page
                topbar.classList.remove('transparent');
            }
        }
        lastScrollTop = scrollTop;
    });

    // Form submission and interaction logic
    const form = document.getElementById('converter-form');
    const cancelButton = document.getElementById('cancel-button');
    const statusMessage = document.getElementById('status-message');
    const xmlOutput = document.getElementById('xml-output');
    const toggleButton = document.getElementById('toggle-button');
    const downloadButton = document.getElementById('download-button');
    let isConverting = false;

    // Form submission handler
    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        if (isConverting) return;

        isConverting = true;
        statusMessage.textContent = "Please wait...";
        xmlOutput.textContent = "";
        xmlOutput.classList.add('collapsed');
        toggleButton.style.display = 'none';
        downloadButton.style.display = 'none';

        const formData = new FormData(form);
        const anilistUsername = formData.get('anilist_username');
        const xmlUsername = formData.get('xml_username');

        try {
            const response = await fetch('https://anilistxml.swightshome.xyz/convert', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ anilist_username: anilistUsername, xml_username: xmlUsername })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            const data = await response.json();
            xmlOutput.textContent = data.xml_content;
            statusMessage.textContent = "MAL XML file created successfully.";
            toggleButton.style.display = 'inline-block';
            downloadButton.style.display = 'inline-block';

            // Create a downloadable XML file
            const blob = new Blob([data.xml_content], { type: 'application/xml' });
            const url = URL.createObjectURL(blob);
            downloadButton.href = url;
        } catch (error) {
            statusMessage.textContent = `Error: ${error.message}`;
            console.error('Conversion error:', error);
        } finally {
            isConverting = false;
        }
    });

    // Cancel button handler
    cancelButton.addEventListener('click', async () => {
        if (!isConverting) return;

        try {
            const response = await fetch('https://anilistxml.swightshome.xyz/cancel', {
                method: 'POST'
            });

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            statusMessage.textContent = "Process cancelled.";
        } catch (error) {
            statusMessage.textContent = `Error: ${error.message}`;
            console.error('Cancellation error:', error);
        } finally {
            isConverting = false;
        }
    });

    // Toggle XML output visibility
    toggleButton.addEventListener('click', () => {
        if (xmlOutput.classList.contains('collapsed')) {
            xmlOutput.classList.remove('collapsed');
            xmlOutput.classList.add('expanded');
            toggleButton.textContent = "Hide XML";
        } else {
            xmlOutput.classList.remove('expanded');
            xmlOutput.classList.add('collapsed');
            toggleButton.textContent = "Show XML";
        }
    });
});