document.addEventListener('DOMContentLoaded', async () => {
    await loadSettings();
    await initDesktopShell();
    initAuthUi();
    if (!await initAuthGate()) return;
    await continueAuthenticatedStartup();
});

async function continueAuthenticatedStartup() {
    await normalizeDesktopRuntimeSettings();
    applyLanguage();
    if (!state.settings.onboarding_complete) {
        openOnboarding();
        return;
    }

    await bootApp();
    startLiveSyncLoop();
}

async function normalizeDesktopRuntimeSettings() {
    if (!isDesktopShell || !isDesktopShell()) return;
    if (getDesktopPreferredLocalRuntime() !== 'embedded') return;

    const recommendedModel = getDesktopRecommendedLocalRuntimeModel();
    const patch = {};

    if ((state.settings.local_runtime || '') !== 'embedded') patch.local_runtime = 'embedded';
    if (!state.settings.local_runtime_model) patch.local_runtime_model = recommendedModel;
    if ((state.settings.ai_provider || '') === 'ollama') patch.ai_provider = 'embedded';
    if ((state.settings.ai_provider || '') === 'embedded' && (!state.settings.ai_model || state.settings.ai_model === 'llama3.1:8b')) {
        patch.ai_model = recommendedModel;
    }
    if ((state.settings.embedding_provider || '') !== 'embedded') patch.embedding_provider = 'embedded';
    if (!state.settings.embedding_model || state.settings.embedding_model === 'nomic-embed-text') {
        patch.embedding_model = recommendedModel;
    }

    if (Object.keys(patch).length) {
        await saveSettingsPatch(patch);
    }
}

async function bootApp() {
    const [servicesData, ordersData] = await Promise.all([api.getServices(), api.getExecutiveOrders(), initBoard()]);
    state.services = servicesData.services || [];
    state.executiveOrders = ordersData.orders || [];
    updateHeaderIdentity();
    applyLanguage();
    initTooltips();

    if (window.matchMedia('(max-width: 980px)').matches) {
        document.body.classList.add('dock-collapsed');
        document.getElementById('topDockToggle')?.setAttribute('aria-expanded', 'false');
    }

    if (!state.uiInitialized) {
        initModals();
        initDashboard();
        initHealthUi();
        initAI();
        initSettingsUi();
        initAgentsView();
        state.uiInitialized = true;
    }

    renderDailyBriefing();

    if (state.settings.onboarding_complete && !state.settings.platform_tutorial_dismissed) {
        setTimeout(() => openGuideModal(), 250);
    }
}

function updateHeaderIdentity() {
    const s = state.settings;
    const nameEl    = document.getElementById('headerOwnerName');
    const companyEl = document.getElementById('headerCompanyName');
    if (nameEl)    nameEl.textContent    = s.owner_name    || 'Your Name';
    if (companyEl) companyEl.textContent = s.company_name  || '';
}

async function loadSettings() {
    state.settings = await api.getSettings();
    state.settings.app_language = 'en';
    state.showMockData = state.settings?.show_mock_data !== 0;
}

async function saveSettingsPatch(patch) {
    const nextSettings = {
        ...state.settings,
        ...patch,
        app_language: 'en'
    };
    await api.saveSettings(nextSettings);
    state.settings = await api.getSettings();
    applyLanguage();
    updateHeaderIdentity();
    return state.settings;
}
