// Settings Modal Management

// Function to open modal
window.openSettingsModal = function() {
    const modal = document.getElementById('settings-modal');
    if (modal) {
        modal.style.display = 'flex';
        loadSettings();
    }
};

// Function to close modal
window.closeSettingsModal = function() {
    const modal = document.getElementById('settings-modal');
    if (modal) {
        modal.style.display = 'none';
    }
};

// Close modal when clicking outside
window.addEventListener('click', function(event) {
    const modal = document.getElementById('settings-modal');
    if (event.target === modal) {
        window.closeSettingsModal();
    }
});

// Load settings when modal opens
async function loadSettings() {
    try {
        const response = await fetch('/api/settings');
        if (!response.ok) {
            throw new Error('Failed to load settings');
        }

        const settings = await response.json();
        const settingsMap = {};
        settings.forEach(s => {
            settingsMap[s.key] = s.value;
        });

        // Populate fields with correct IDs
        const labelstudioUrl = document.getElementById('labelstudio-url');
        const labelstudioToken = document.getElementById('labelstudio-token');
        const yoloxPathInput = document.getElementById('yolox-path');
        const yoloxVenvPathInput = document.getElementById('yolox-venv-path');
        const yoloxOutputPathInput = document.getElementById('yolox-output-path');
        const yoloxDataDirInput = document.getElementById('yolox-data-dir');
        
        if (labelstudioUrl) labelstudioUrl.value = settingsMap.labelstudio_api_url || '';
        if (labelstudioToken) labelstudioToken.value = settingsMap.labelstudio_api_token || '';
        if (yoloxPathInput) yoloxPathInput.value = settingsMap.yolox_path || '';
        if (yoloxVenvPathInput) yoloxVenvPathInput.value = settingsMap.yolox_venv_path || '';
        if (yoloxOutputPathInput) yoloxOutputPathInput.value = settingsMap.yolox_output_path || '';
        if (yoloxDataDirInput) yoloxDataDirInput.value = settingsMap.yolox_data_dir || '';
    } catch (error) {
        console.error('Error loading settings:', error);
        const saveStatus = document.getElementById('save-status');
        if (saveStatus) {
            showMessage(saveStatus, 'Fehler beim Laden: ' + error.message, 'error');
        }
    }
}

// Helper functions
function showMessage(element, message, type) {
    if (element) {
        element.textContent = message;
        element.className = 'status-message ' + type;
        element.style.display = 'block';
    }
}

function hideMessage(element) {
    if (element) {
        element.style.display = 'none';
    }
}

// Event listeners - wait for DOM to be ready
document.addEventListener('DOMContentLoaded', function() {
    // Test Label Studio connection
    const testLabelStudioBtn = document.getElementById('test-labelstudio-btn');
    if (testLabelStudioBtn) {
        testLabelStudioBtn.addEventListener('click', async () => {
            const apiUrl = document.getElementById('labelstudio-url').value.trim();
            const apiToken = document.getElementById('labelstudio-token').value.trim();
            const labelstudioStatus = document.getElementById('labelstudio-status');
            const loader = document.getElementById('test-ls-loader');

            if (!apiUrl || !apiToken) {
                showMessage(labelstudioStatus, 'Bitte geben Sie URL und Token ein', 'error');
                return;
            }

            testLabelStudioBtn.disabled = true;
            if (loader) loader.style.display = 'block';
            hideMessage(labelstudioStatus);

            try {
                const response = await fetch('/api/settings/test/labelstudio', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ api_url: apiUrl, api_token: apiToken })
                });

                const result = await response.json();

                if (result.success) {
                    showMessage(labelstudioStatus, '✓ ' + result.message, 'success');
                } else {
                    showMessage(labelstudioStatus, '✗ ' + result.message, 'error');
                }
            } catch (error) {
                showMessage(labelstudioStatus, '✗ Fehler: ' + error.message, 'error');
            } finally {
                testLabelStudioBtn.disabled = false;
                if (loader) loader.style.display = 'none';
            }
        });
    }

    // Test YOLOX path
    const testYoloxBtn = document.getElementById('test-yolox-btn');
    if (testYoloxBtn) {
        testYoloxBtn.addEventListener('click', async () => {
            const path = document.getElementById('yolox-path').value.trim();
            const venvPath = document.getElementById('yolox-venv-path').value.trim();
            const yoloxStatus = document.getElementById('yolox-status');
            const loader = document.getElementById('test-yolox-loader');

            if (!path) {
                showMessage(yoloxStatus, 'Bitte geben Sie einen YOLOX Pfad ein', 'error');
                return;
            }

            testYoloxBtn.disabled = true;
            if (loader) loader.style.display = 'block';
            hideMessage(yoloxStatus);

            try {
                const response = await fetch('/api/settings/test/yolox', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        yolox_path: path,
                        yolox_venv_path: venvPath 
                    })
                });

                const result = await response.json();

                if (result.success) {
                    showMessage(yoloxStatus, '✓ ' + result.message, 'success');
                } else {
                    showMessage(yoloxStatus, '✗ ' + result.message, 'error');
                }
            } catch (error) {
                showMessage(yoloxStatus, '✗ Fehler: ' + error.message, 'error');
            } finally {
                testYoloxBtn.disabled = false;
                if (loader) loader.style.display = 'none';
            }
        });
    }

    // Save settings
    const saveSettingsBtn = document.getElementById('save-settings-btn');
    if (saveSettingsBtn) {
        saveSettingsBtn.addEventListener('click', async () => {
            const labelstudioUrl = document.getElementById('labelstudio-url').value.trim();
            const labelstudioToken = document.getElementById('labelstudio-token').value.trim();
            const yoloxPathValue = document.getElementById('yolox-path').value.trim();
            const yoloxVenvPathValue = document.getElementById('yolox-venv-path').value.trim();
            const yoloxOutputPathValue = document.getElementById('yolox-output-path').value.trim();
            const yoloxDataDirValue = document.getElementById('yolox-data-dir').value.trim();
            const saveStatus = document.getElementById('save-status');

            // Validation
            if (!labelstudioUrl || !labelstudioToken || !yoloxPathValue || !yoloxVenvPathValue || !yoloxOutputPathValue || !yoloxDataDirValue) {
                showMessage(saveStatus, 'Bitte füllen Sie alle Felder aus', 'error');
                return;
            }

            const settings = {
                labelstudio_api_url: labelstudioUrl,
                labelstudio_api_token: labelstudioToken,
                yolox_path: yoloxPathValue,
                yolox_venv_path: yoloxVenvPathValue,
                yolox_output_path: yoloxOutputPathValue,
                yolox_data_dir: yoloxDataDirValue
            };

            saveSettingsBtn.disabled = true;
            const originalText = saveSettingsBtn.textContent;
            saveSettingsBtn.textContent = 'Speichern...';
            hideMessage(saveStatus);

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

                if (!response.ok) {
                    throw new Error('Failed to save settings');
                }

                showMessage(saveStatus, '✓ Einstellungen erfolgreich gespeichert!', 'success');
                
                // Close modal after 1.5 seconds
                setTimeout(() => {
                    window.closeSettingsModal();
                }, 1500);
            } catch (error) {
                showMessage(saveStatus, '✗ Fehler beim Speichern: ' + error.message, 'error');
            } finally {
                saveSettingsBtn.disabled = false;
                saveSettingsBtn.textContent = originalText;
            }
        });
    }
});
