document.addEventListener("DOMContentLoaded", () => {
    const responseArea = document.getElementById('response-area');
    const responseSection = document.getElementById('response-section');
    const submitButton = document.getElementById('submit');
    const urlBox = document.getElementById('url_box');

    // Before sending HTMX request, prepare UI and handle empty input
    document.body.addEventListener('htmx:beforeRequest', function(evt) {
        if (evt.detail.elt.id === 'url-form') {
            const url = urlBox.value.trim();
            if (!url) {
                evt.detail.shouldCancel = true;
                responseArea.innerText = 'Please enter a URL.';
                return;
            }
            urlBox.value = '';
            submitButton.disabled = true;
            responseArea.innerText = 'Processing...';
        }
    });

    document.body.addEventListener('htmx:afterRequest', function(evt) {
        if (evt.detail.elt.id === 'url-form') {
            const text = evt.detail.xhr.responseText.trim();
            if (text === "Processing started. Check /stream_output for updates.") {
                streamOutput(responseArea, responseSection, submitButton);
            } else {
                responseArea.innerText = text;
                submitButton.disabled = false;
            }
        }
    });

    function streamOutput(responseArea, responseSection, submitButton) {
        // Fetch the streaming output
        fetch('/stream_output')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const reader = response.body.getReader();
                const decoder = new TextDecoder("utf-8");

                responseArea.innerHTML = "";

                function readStream() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            submitButton.disabled = false;
                            return;
                        }
                        const chunk = decoder.decode(value, { stream: true });
                        responseArea.innerHTML += chunk;
                        responseSection.scrollTop = responseSection.scrollHeight;
                        readStream();
                    }).catch(error => {
                        console.error('Error reading stream:', error);
                        responseArea.innerText = 'Error reading stream: ' + error.message;
                        submitButton.disabled = false;
                    });
                }

                readStream();
            })
            .catch(error => {
                console.error('Error fetching stream:', error);
                responseArea.innerText = 'Error fetching stream: ' + error.message;
                submitButton.disabled = false;
            });
    }
});
