function setSettingsTab(tabId = 'account') {
    state.activeSettingsTab = tabId;
    document.querySelectorAll('[data-settings-tab]').forEach((button) => {
        const isActive = button.dataset.settingsTab === tabId;
        button.classList.toggle('bg-white/10', isActive);
        button.classList.toggle('border-white/20', isActive);
        button.classList.toggle('text-white', isActive);
        button.classList.toggle('text-gray-400', !isActive);
    });
    document.querySelectorAll('[data-settings-panel]').forEach((panel) => {
        panel.classList.toggle('hidden', panel.dataset.settingsPanel !== tabId);
    });
}

function populateSettingsForm() {
    const desktopDefaults = getDesktopDefaultAiSetup();
    const embeddedPreferred = getDesktopPreferredLocalRuntime() === 'embedded';
    renderAccountSummary();
    document.getElementById('aiProviderSelect').value = state.settings.ai_provider || desktopDefaults.ai_provider || 'openrouter';
    document.getElementById('aiModelInput').value = state.settings.ai_model || '';
    document.getElementById('aiApiKeyInput').value = state.settings.ai_api_key || '';
    document.getElementById('embeddingProviderSelect').value = state.settings.embedding_provider || desktopDefaults.embedding_provider || 'ollama';
    document.getElementById('embeddingModelInput').value = state.settings.embedding_model || desktopDefaults.embedding_model || 'nomic-embed-text';
    document.getElementById('settingsLocalRuntime').value = state.settings.local_runtime || getDesktopPreferredLocalRuntime();
    document.getElementById('settingsLocalRuntimeModel').value = state.settings.local_runtime_model || '';
    document.getElementById('settingsOwnerName').value = state.settings.owner_name || '';
    document.getElementById('settingsCompanyName').value = state.settings.company_name || '';
    document.getElementById('settingsCity').value = state.settings.city || '';
    document.getElementById('settingsLanguage').value = 'en';
    document.getElementById('settingsAgentHour').value = state.settings.agent_run_hour ?? 7;
    renderDesktopStatusPanel('desktopSettingsStatus', { showRecommendationNote: false });
    document.querySelectorAll('[data-ollama-option]').forEach((option) => {
        option.hidden = embeddedPreferred;
        option.disabled = embeddedPreferred;
    });
    if (embeddedPreferred && document.getElementById('aiProviderSelect').value === 'ollama') {
        document.getElementById('aiProviderSelect').value = 'embedded';
    }
    if (embeddedPreferred && document.getElementById('embeddingProviderSelect').value === 'ollama') {
        document.getElementById('embeddingProviderSelect').value = 'embedded';
    }
    syncDesktopRecommendedModels();
}

function openSettingsModal() {
    populateSettingsForm();
    setSettingsTab(state.activeSettingsTab || 'account');
    const modal = document.getElementById('settingsModal');
    modal.scrollTop = 0;
    modal.classList.remove('hidden');
    setTimeout(() => {
        modal.classList.remove('opacity-0');
        modal.querySelector('.glass-panel')?.classList.remove('scale-95');
    }, 10);
}

function closeSettingsModal() {
    const modal = document.getElementById('settingsModal');
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel')?.classList.add('scale-95');
    setTimeout(() => modal.classList.add('hidden'), 300);
}

async function saveSettingsFromModal() {
    await api.saveSettings({
        ai_provider: document.getElementById('aiProviderSelect').value,
        ai_model: document.getElementById('aiModelInput').value.trim(),
        ai_api_key: document.getElementById('aiApiKeyInput').value.trim(),
        embedding_provider: document.getElementById('embeddingProviderSelect').value,
        embedding_model: document.getElementById('embeddingModelInput').value.trim(),
        local_runtime: document.getElementById('settingsLocalRuntime').value,
        local_runtime_model: document.getElementById('settingsLocalRuntimeModel').value.trim(),
        owner_name: document.getElementById('settingsOwnerName').value,
        company_name: document.getElementById('settingsCompanyName').value,
        city: document.getElementById('settingsCity').value,
        app_language: 'en',
        show_mock_data: state.showMockData ? 1 : 0,
        platform_tutorial_dismissed: state.settings.platform_tutorial_dismissed,
        agent_run_hour: parseInt(document.getElementById('settingsAgentHour').value, 10) || 7
    });
    state.settings = await api.getSettings();
    applyLanguage();
    updateHeaderIdentity();
    renderDailyBriefing(true);
    await refreshActiveAppState({ maintainFocus: true, includeAgents: true });
    closeSettingsModal();
    showToast(t('toast.settingsSaved'), 'success');
}

async function backfillSettingsMemory() {
    const btn = document.getElementById('backfillMemoryBtn');
    if (!btn) return;
    btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> ${escapeHtml(t('common.running'))}`;
    btn.disabled = true;
    try {
        const res = await api.backfillMemory();
        showToast(res.message, 'success');
    } catch (_error) {
        showToast(t('settings.backfillFailed'), 'error');
    } finally {
        btn.innerHTML = `<i class="fas fa-sync"></i> ${escapeHtml(t('settings.backfill'))}`;
        btn.disabled = false;
    }
}

function initSettingsUi() {
    document.getElementById('openSettingsBtn')?.addEventListener('click', openSettingsModal);
    document.getElementById('closeSettingsModal')?.addEventListener('click', closeSettingsModal);
    document.getElementById('saveSettingsBtn')?.addEventListener('click', saveSettingsFromModal);
    document.getElementById('backfillMemoryBtn')?.addEventListener('click', backfillSettingsMemory);
    document.getElementById('resetWorkspaceBtn')?.addEventListener('click', () => {
        customConfirm(t('toast.resetWorkspaceConfirm'), async () => {
            try {
                const res = await api.resetWorkspace();
                showToast(res.message || t('settings.resetDone'), 'success');
                setTimeout(() => window.location.reload(), 400);
            } catch (error) {
                showToast(error.message || t('toast.workspaceResetFailed'), 'error');
            }
        });
    });

    document.querySelectorAll('[data-settings-tab]').forEach((button) => {
        button.addEventListener('click', () => setSettingsTab(button.dataset.settingsTab));
    });
}
