document.addEventListener('DOMContentLoaded', () => {
    let currentStep = 1;
    const totalSteps = 5;

    // State to hold installation configuration
    const installConfig = {
        timezone: 'UTC',
        keyboardLayout: 'us',
        disk: null,
        filesystem: 'btrfs',
        hostname: 'acreetion-pc',
        username: '',
        password: '',
        sudo: true
    };

    const wizardContent = document.getElementById('wizard-content');
    const stepIndicators = document.querySelectorAll('.step');
    const btnNext = document.getElementById('btn-next');
    const btnBack = document.getElementById('btn-back');

    function renderStep(step) {
        const template = document.getElementById(`tpl-step-${step}`);
        if (!template) return;

        wizardContent.innerHTML = '';
        wizardContent.appendChild(template.content.cloneNode(true));

        wizardContent.firstElementChild.classList.add('fade-in');

        // Step specific initializations
        if (step === 2) {
            document.getElementById('timezone-select').value = installConfig.timezone;
            document.getElementById('keyboard-select').value = installConfig.keyboardLayout;

            document.getElementById('timezone-select').addEventListener('change', (e) => {
                installConfig.timezone = e.target.value;
            });
            document.getElementById('keyboard-select').addEventListener('change', (e) => {
                installConfig.keyboardLayout = e.target.value;
            });
        }

        if (step === 3) {
            document.getElementById('fs-select').value = installConfig.filesystem;
            document.getElementById('fs-select').addEventListener('change', (e) => {
                installConfig.filesystem = e.target.value;
            });
            fetchDisks();
        }

        if (step === 4) {
            document.getElementById('hostname').value = installConfig.hostname;
            document.getElementById('username').value = installConfig.username;
            document.getElementById('password').value = installConfig.password;
            document.getElementById('sudo-access').checked = installConfig.sudo;

            const inputs = ['hostname', 'username', 'password'];
            inputs.forEach(id => {
                document.getElementById(id).addEventListener('input', (e) => {
                    installConfig[id] = e.target.value;
                });
            });

            document.getElementById('sudo-access').addEventListener('change', (e) => {
                installConfig.sudo = e.target.checked;
            });
        }

        if (step === 5) {
            document.getElementById('summary-locale').textContent = `${installConfig.keyboardLayout} / ${installConfig.timezone}`;
            document.getElementById('summary-disk').textContent = installConfig.disk || 'None Selected (Cannot Proceed)';
            document.getElementById('summary-fs').textContent = installConfig.filesystem;
            document.getElementById('summary-hostname').textContent = installConfig.hostname;
            document.getElementById('summary-user').textContent = installConfig.username || 'No User';

            btnNext.textContent = 'Install AcreetionOS';
            if (!installConfig.disk || !installConfig.username || !installConfig.password || !installConfig.hostname) {
                btnNext.disabled = true;
            } else {
                btnNext.disabled = false;
            }
        } else {
            btnNext.textContent = 'Next';
            btnNext.disabled = false;
        }

        // Update indicators
        stepIndicators.forEach((ind, index) => {
            if (index < step) {
                ind.classList.add('active');
            } else {
                ind.classList.remove('active');
            }
        });

        // Toggle back button
        if (step > 1) {
            btnBack.classList.remove('hidden');
        } else {
            btnBack.classList.add('hidden');
        }
    }

    async function fetchDisks() {
        try {
            const resp = await fetch('/api/disks');
            const data = await resp.json();
            const diskList = document.getElementById('disk-list');
            const loader = document.getElementById('loading-disks');

            loader.classList.add('hidden');
            diskList.innerHTML = '';

            if (data.disks.length === 0) {
                diskList.innerHTML = '<div class="info-text">No suitable disks found.</div>';
                return;
            }

            data.disks.forEach(disk => {
                const item = document.createElement('div');
                item.className = `disk-item ${installConfig.disk === disk.path ? 'selected' : ''}`;
                item.innerHTML = `
                    <div><strong>${disk.path}</strong></div>
                    <div style="color:var(--text-secondary);font-size:0.875rem;">${disk.size} - ${disk.model}</div>
                `;
                item.addEventListener('click', () => {
                    document.querySelectorAll('.disk-item').forEach(el => el.classList.remove('selected'));
                    item.classList.add('selected');
                    installConfig.disk = disk.path;
                });
                diskList.appendChild(item);
            });

        } catch (err) {
            console.error('Failed to fetch disks:', err);
            document.getElementById('loading-disks').textContent = 'Failed to load disks.';
        }
    }

    async function startInstall() {
        btnNext.disabled = true;
        btnBack.disabled = true;
        document.getElementById('install-progress-container').classList.remove('hidden');
        document.getElementById('install-status-text').textContent = 'Submitting configuration...';

        try {
            const resp = await fetch('/api/install', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(installConfig)
            });
            const data = await resp.json();

            if (data.success) {
                document.getElementById('install-status-text').textContent = 'Installation started...';
                
                // Start polling logs
                const logInterval = setInterval(async () => {
                    try {
                        const logResp = await fetch('/api/logs');
                        const logData = await logResp.json();
                        if (logData.logs.length > 0) {
                            const lastLog = logData.logs[logData.logs.length - 1];
                            document.getElementById('install-status-text').textContent = lastLog;
                            
                            // Simple logic to advance progress bar based on keywords in logs
                            // In a real app, this would be more robust
                            let progress = 10;
                            if (lastLog.includes('formatting')) progress = 20;
                            if (lastLog.includes('syncing')) progress = 30;
                            if (lastLog.includes('base installation')) progress = 50;
                            if (lastLog.includes('bootloader')) progress = 80;
                            if (lastLog.includes('finished')) {
                                progress = 100;
                                clearInterval(logInterval);
                                alert('Installation completed successfully! You can now reboot.');
                            }
                            document.getElementById('install-progress-fill').style.width = `${progress}%`;
                        }
                    } catch (err) {
                        console.error('Log fetch error:', err);
                    }
                }, 2000);
            } else {
                document.getElementById('install-status-text').textContent = `Error: ${data.error}`;
                btnNext.disabled = false;
            }

        } catch (err) {
            document.getElementById('install-status-text').textContent = 'Failed to communicate with backend.';
            btnNext.disabled = false;
        }
    }

    btnNext.addEventListener('click', () => {
        if (currentStep === 5) {
            startInstall();
        } else if (currentStep < totalSteps) {
            currentStep++;
            renderStep(currentStep);
        }
    });

    btnBack.addEventListener('click', () => {
        if (currentStep > 1) {
            currentStep--;
            renderStep(currentStep);
        }
    });

    // Initialize
    renderStep(currentStep);
});
