<!DOCTYPE html>
<html>
<head>
    <title>ZlewnieGEN V5.2</title>
    <link rel="icon" href="/static/favicon.ico" type="image/png">
    <link rel="stylesheet" href="/static/style.css">
    <link href='https://fonts.googleapis.com/css?family=Cabin+Condensed:700' rel='stylesheet' type='text/css'>
</head>
<body>
    <h1>Wczytaj plik kanałów oraz studni/studni witualnych jako shapefile spakowany do .ZIP</h1>

    <!-- Remove the <form> element completely -->
    <div>
        <div class="form-group">
            <label for="k_przewod_fc">(K) Przewód <i>Shapefile (ZIP)</i>:</label>
            <input type="file"
                   id="k_przewod_fc"
                   name="k_przewod_fc"
                   accept=".zip"
                   required>
            <span class="error" id="kPrzewodError">Please select a ZIP file</span>
        </div>

        <div class="form-group">
            <label for="studnia_fc">(K) Studnia <i>Shapefile (ZIP)</i>:</label>
            <input type="file"
                   id="studnia_fc"
                   name="studnia_fc"
                   accept=".zip"
                   required>
            <span class="error" id="studniaError">Please select a ZIP file</span>
        </div>

        <div class="form-group">
            <label for="nrw_ids">NRW IDs (np.: 302257218, 302258005, (...)):</label>
            <input type="text"
                   id="nrw_ids"
                   name="nrw_ids"
                   pattern="\d+(,\s*\d+)*"
                   required>
            <span class="error" id="nrwIdsError">Invalid NRW IDs format</span>
        </div>

        <button type="button" id="submitBtn">Uruchom</button>

        <div class="progress-container">
            <progress id="progressBar" value="0" max="100"></progress>
            <span id="progressText">0%</span>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const submitBtn = document.getElementById('submitBtn');
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            let progressInterval;

            // Enable/disable button based on form state
            function validateForm() {
                const kPrzewodFile = document.getElementById('k_przewod_fc').files[0];
                const studniaFile = document.getElementById('studnia_fc').files[0];
                const nrwIdsInput = document.getElementById('nrw_ids');

                const isValid = (
                    kPrzewodFile &&
                    studniaFile &&
                    nrwIdsInput.value.trim() !== ''
                );

                submitBtn.disabled = !isValid;
            }

            // Set up event listeners for form changes
            document.getElementById('k_przewod_fc').addEventListener('change', validateForm);
            document.getElementById('studnia_fc').addEventListener('change', validateForm);
            document.getElementById('nrw_ids').addEventListener('input', validateForm);

            // Initial validation
            validateForm();

            // Process button click
            submitBtn.addEventListener('click', async (e) => {
                console.log("Button clicked - starting processing");
                e.preventDefault();

                // Disable button during processing
                submitBtn.disabled = true;
                progressBar.value = 0;
                progressText.textContent = '0%';

                // Create FormData
                const formData = new FormData();
                formData.append('k_przewod_fc', document.getElementById('k_przewod_fc').files[0]);
                formData.append('studnia_fc', document.getElementById('studnia_fc').files[0]);
                formData.append('nrw_ids', document.getElementById('nrw_ids').value);

                try {
                    console.log("Sending request to /process_files/");

                    // Start processing
                    const response = await fetch("/process_files/", {
                        method: "POST",
                        body: formData,
                    });

                    console.log("Received response:", response.status);

                    if (!response.ok) {
                        const error = await response.json();
                        throw new Error(error.error || 'Processing failed');
                    }

                    const result = await response.json();
                    console.log("Processing started:", result.message);

                    // Start progress polling
                    progressInterval = setInterval(async () => {
                        try {
                            console.log("Checking progress...");
                            const res = await fetch("/progress/");
                            const data = await res.json();

                            console.log(`Current progress: ${data.progress}%`);
                            progressBar.value = data.progress;
                            progressText.textContent = `${data.progress}%`;

                            if (data.progress >= 100) {
                                clearInterval(progressInterval);
                                console.log("Processing complete, preparing download...");

                                // Get result file path
                                const pathRes = await fetch("/get_result_path/");
                                const pathData = await pathRes.json();

                                if (pathData.path) {
                                    // Trigger download after short delay
                                    setTimeout(() => {
                                        console.log("Downloading file:", pathData.path);
                                        window.location.href = "/download/";
                                        submitBtn.disabled = false;
                                    }, 1000);
                                } else {
                                    console.error("Result path not found");
                                    alert("Processing complete but file not found");
                                    submitBtn.disabled = false;
                                }
                            }
                        } catch (err) {
                            console.error('Progress polling error:', err);
                            clearInterval(progressInterval);
                            alert('Error checking progress: ' + err.message);
                            submitBtn.disabled = false;
                        }
                    }, 1000);
                } catch (error) {
                    console.error('Processing error:', error);
                    alert('Error: ' + error.message);
                    submitBtn.disabled = false;
                }
            });
        });
    </script>
</body>
</html> make table and inputs centered ath beter styling and add debug widow to show what is going on in background while prcessing