
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');
    const form = document.getElementById('url-form');

    // Simple URL validation regex (covers http/https and domains)
    const urlPattern = /^(https?:\/\/)[\w.-]+(\.[\w\.-]+)+[/#?]?.*$/i;

    form.addEventListener('submit', async (evt) => {
        evt.preventDefault();

        const url = urlBox.value.trim();
        if (!url) {
            responseArea.textContent = 'Please enter a URL.';
            return;
        }
        if (!urlPattern.test(url)) {
            responseArea.textContent = 'Please enter a valid URL (must start with http:// or https://).';
            return;
        }

        // Prepare UI
        urlBox.value = '';
        submitButton.disabled = true;
        responseArea.textContent = 'Processing...\n';

        try {
            const response = await fetch('/process-url', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ url }),
            });

            if (!response.ok) {
                throw new Error(`Server returned ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
            responseArea.textContent = ''; // clear before streaming

            async function readChunk() {
                const { done, value } = await reader.read();
                if (done) {
                    submitButton.disabled = false;
                    return;
                }

                const chunk = decoder.decode(value, { stream: true });
                responseArea.innerHTML += chunk;
                responseSection.scrollTop = responseSection.scrollHeight;

                await readChunk();
            }

            await readChunk();

        } catch (err) {
            console.error(err);
            responseArea.textContent = `Error: ${err.message}`;
            submitButton.disabled = false;
        }
    });
});

