function getCurrentLanguage() {
    return 'en';
}

function t(key, vars = {}) {
    const language = getCurrentLanguage();
    let text = UI_COPY[language]?.[key] ?? UI_COPY.en[key] ?? key;
    Object.entries(vars).forEach(([varName, value]) => {
        text = text.replaceAll(`{${varName}}`, String(value));
    });
    return text;
}

function normalizeTranslatableText(value) {
    if (value == null) return '';
    if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
        return String(value).trim();
    }
    if (typeof value === 'object') {
        if (typeof value.title === 'string') return value.title.trim();
        if (typeof value.text === 'string') return value.text.trim();
        if (typeof value.name === 'string') return value.name.trim();
        try {
            return JSON.stringify(value).trim();
        } catch {
            return '';
        }
    }
    return String(value).trim();
}

function getCachedTranslation(text) {
    const source = normalizeTranslatableText(text);
    if (!source) return '';
    return source;
}

async function ensureTranslatedTexts(texts = []) {
    return true;
}

function queueTranslationRefresh(texts = []) {
    return texts;
}

function getDivisionCopy(div) {
    const language = getCurrentLanguage();
    const localized = DIVISION_TRANSLATIONS[div?.id]?.[language];
    return {
        name: localized?.name || div?.name || '',
        subtitle: localized?.subtitle || div?.subtitle || ''
    };
}

function getDisplayVfp(div) {
    const language = getCurrentLanguage();
    const defaults = DEFAULT_DIVISION_VFPS[div?.id];
    const current = String(div?.vfp || '').trim();
    if (!defaults) return current;
    const knownValues = Object.values(defaults);
    if (!current || knownValues.includes(current)) {
        return defaults[language] || current;
    }
    return getCachedTranslation(current);
}

function getDisplayInfo(div) {
    const defaults = DEFAULT_DIVISION_INFOS[div?.id];
    const current = String(div?.info || '').trim();
    if (!defaults) return current;
    const knownValues = Object.values(defaults);
    if (!current || knownValues.includes(current)) {
        return defaults.en;
    }
    return current;
}

function getLiveVfp(div) {
    return String(div?.vfp || '').trim();
}

function refreshLocalizedViews() {
    if (state.divisions?.length) renderBoard();
    if (state.activeDashboardDivId) {
        if (state.activeDashboardDivId === 1 && state.div1WorkData) renderDiv1Work();
        if (state.activeDashboardDivId === 2 && state.div2WorkData) renderDiv2Work();
        if (state.activeDashboardDivId === 3 && state.div3WorkData) renderDiv3Work();
        if (state.activeDashboardDivId === 4 && state.div4WorkData) renderDiv4Work();
        if (state.activeDashboardDivId === 5 && state.div5WorkData) renderDiv5Work();
        if (state.activeDashboardDivId === 6 && state.div6WorkData) renderDiv6Work();
        if (state.activeDashboardDivId === 8 && state.edWorkData) renderEdWork();
        if (state.activeDashboardDivId === 7 && state.div7WorkData) renderDiv7Work();
        if (state.battlePlansData) renderBattlePlan(state.activeDashboardDivId);
        if (state.metricsData) renderMetrics(state.activeDashboardDivId);
        if (state.trainingsData) renderTraining(state.activeDashboardDivId);
        renderAIConversationTabs();
        renderAIChatHistory();
        renderMemoryExplorer();
    }
    if (state.services?.length) renderServicesList();
    const onboardingLanguage = document.getElementById('onbLanguage');
    if (onboardingLanguage) onboardingLanguage.value = 'en';
}

function applyRuntimeI18n() {
    const setText = (selector, key, vars = {}) => {
        const el = document.querySelector(selector);
        if (el) el.textContent = t(key, vars);
    };
    const setHtml = (selector, key, vars = {}) => {
        const el = document.querySelector(selector);
        if (el) el.innerHTML = t(key, vars);
    };
    const setRawHtml = (selector, html) => {
        const el = document.querySelector(selector);
        if (el) el.innerHTML = html;
    };
    const setPlaceholder = (selector, key, vars = {}) => {
        const el = document.querySelector(selector);
        if (el) el.setAttribute('placeholder', t(key, vars));
    };

    setHtml('#newConversationBtn', 'ai.newConversationButtonHtml');
    setPlaceholder('#aiInput', 'ai.placeholder');

    setRawHtml('#dashboardAgentsView h3', `<i class="fas fa-bolt text-amber-400"></i> ${escapeHtml(t('agents.title'))}`);
    setText('#dashboardAgentsView h3 + p', 'agents.subtitle');
    const awakenBtn = document.getElementById('awakenAgentsBtn');
    if (awakenBtn) awakenBtn.innerHTML = '<i class="fas fa-power-off"></i> Run Visible Agents';
    setRawHtml('#dashboardAgentsView .mb-6 h4', `<i class="fas fa-terminal text-green-400"></i> ${escapeHtml(t('agents.logTitle'))}`);
    if (document.querySelector('#agentLogContainer .text-gray-500')) {
        setText('#agentLogContainer .text-gray-500', 'agents.standby');
    }
    setRawHtml('#dashboardAgentsView .glass-panel.border-amber-500\\/20 h4', `<i class="fas fa-brain text-amber-400"></i> ${escapeHtml(t('memory.title'))}`);
    const memorySubtitle = document.querySelector('#dashboardAgentsView .glass-panel.border-amber-500\\/20 p');
    if (memorySubtitle) {
        memorySubtitle.innerHTML = `${escapeHtml(t('memory.subtitle'))} <span id="memoryStatsLabel" class="text-amber-300 font-semibold">${escapeHtml(t('common.loading'))}</span>`;
    }
    setPlaceholder('#memorySearchInput', 'memory.searchPlaceholder');
    setHtml('#memorySearchBtn', 'memory.searchButtonHtml');

    setText('#modalTitle', 'modal.divisionInfo');
    setText('#saveInfoBtn', 'common.saveChanges');
    setText('#bpModalTitle', 'battle.addGoal');
    const bpLabel = document.querySelector('#bpInputModal label');
    if (bpLabel) bpLabel.textContent = t('battle.goalDescription');
    setPlaceholder('#bpInputText', 'battle.describeGoal');
    setText('#cancelBpInputBtn', 'common.cancel');
    setHtml('#confirmBpInputBtn', 'battle.saveGoalButtonHtml');
    setRawHtml('#confirmModal h3', `<i class="fas fa-exclamation-triangle text-red-500"></i> ${escapeHtml(t('common.areYouSure'))}`);
    setText('#cancelConfirmBtn', 'common.cancel');
    setText('#acceptConfirmBtn', 'common.confirm');

    setRawHtml('#skillAppearanceModal h3', `<i class="fas fa-icons text-emerald-400"></i> ${escapeHtml(t('skills.appearanceTitle'))}`);
    setText('#skillAppearanceModal h3 + p', 'skills.appearanceBody');
    const skillLabels = document.querySelectorAll('#skillAppearanceModal label');
    if (skillLabels[0]) skillLabels[0].textContent = t('skills.searchIcons');
    if (skillLabels[1]) skillLabels[1].textContent = t('skills.presetColors');
    if (skillLabels[2]) skillLabels[2].textContent = t('skills.customColor');
    setPlaceholder('#skillIconSearch', 'skills.searchPlaceholder');
    setText('#saveSkillColorBtn', 'skills.saveSelectedColor');
    setText('#cancelSkillAppearanceBtn', 'common.close');

    setText('#editItemModal h3', 'tasks.editTask');
    const editLabels = document.querySelectorAll('#editItemModal label');
    if (editLabels[0]) editLabels[0].textContent = t('tasks.taskTitle');
    if (editLabels[1]) editLabels[1].innerHTML = `<i class="fas fa-link"></i> ${escapeHtml(t('tasks.clientPortal'))}`;
    setHtml('#copyMagicLinkBtn', 'common.copyButtonHtml');
    const shareHint = document.querySelector('#editItemModal .text-\\[10px\\]');
    if (shareHint) shareHint.innerHTML = `<i class="fas fa-info-circle mr-1"></i>${escapeHtml(t('tasks.sharePortalHint'))}`;
    const deleteItemBtn = document.getElementById('deleteItemBtn');
    if (deleteItemBtn) deleteItemBtn.innerHTML = `<i class="fas fa-trash"></i> ${escapeHtml(t('common.delete'))}`;
    setText('#saveEditItemBtn', 'common.save');

    setText('#settingsProviderLabel', 'settings.provider');
    setText('#settingsChatModelLabel', 'settings.chatModel');
    setText('#settingsApiKeyLabel', 'settings.apiKey');
    setText('#settingsOwnerNameLabel', 'settings.ownerName');
    setText('#settingsCompanyNameLabel', 'settings.companyName');
    setText('#settingsCityLabel', 'settings.city');
    setText('#settingsAgentHourLabel', 'settings.agentHour');
    setText('#settingsEmbeddingProviderLabel', 'settings.embeddingProvider');
    setText('#settingsEmbeddingModelLabel', 'settings.embeddingModel');
    const howItWorks = document.querySelector('#settingsModal .p-3.bg-amber-500\\/5');
    if (howItWorks) howItWorks.innerHTML = `<b>${escapeHtml(t('settings.howItWorksTitle'))}</b> ${escapeHtml(t('settings.howItWorksBody'))}`;
    setText('#backfillMemoryRow .text-xs.text-white', 'settings.backfillTitle');
    setText('#backfillMemoryRow .text-\\[10px\\]', 'settings.backfillBody');
    setHtml('#backfillMemoryBtn', 'settings.backfillButtonHtml');
    setPlaceholder('#aiModelInput', 'settings.aiModelPlaceholder');
    setPlaceholder('#embeddingModelInput', 'settings.embeddingModelPlaceholder');

    setText('#trReaderTitle', 'training.readerTitle');
    setText('#addItemModal h3', 'dashboard.initializeWorkflow');
    const addItemLabel = document.querySelector('#addItemModal label');
    if (addItemLabel) addItemLabel.textContent = t('tasks.clientTaskName');
    setPlaceholder('#addItemTitleInput', 'tasks.clientTaskPlaceholder');
    setText('#cancelAddItemBtn', 'common.cancel');
    setHtml('#confirmAddItemBtn', 'common.createButtonHtml');

    const guideCards = document.querySelectorAll('#guideModal .grid > div');
    if (guideCards[0]) {
        guideCards[0].querySelector('p').textContent = t('guide.step1');
        guideCards[0].querySelector('h4').textContent = t('guide.step1Title');
        guideCards[0].querySelector('h4 + p').textContent = t('guide.step1Body');
        guideCards[0].querySelector('button').textContent = t('guide.openExecutive');
    }
    if (guideCards[1]) {
        guideCards[1].querySelector('p').textContent = t('guide.step2');
        guideCards[1].querySelector('h4').textContent = t('guide.step2Title');
        guideCards[1].querySelector('h4 + p').textContent = t('guide.step2Body');
    }
    if (guideCards[2]) {
        guideCards[2].querySelector('p').textContent = t('guide.step3');
        guideCards[2].querySelector('h4').textContent = t('guide.step3Title');
        guideCards[2].querySelector('h4 + p').textContent = t('guide.step3Body');
    }
    if (guideCards[3]) {
        guideCards[3].querySelector('p').textContent = t('guide.step4');
        guideCards[3].querySelector('h4').textContent = t('guide.step4Title');
        guideCards[3].querySelector('h4 + p').textContent = t('guide.step4Body');
        guideCards[3].querySelector('button').innerHTML = `<i class="fas fa-bolt"></i> ${escapeHtml(t('guide.createFirstWorkflow'))}`;
    }

    const onbAiBox = document.getElementById('onbLocalAiBox');
    if (onbAiBox) {
        const title = document.getElementById('onbLocalAiTitle');
        const body = document.getElementById('onbLocalAiBody');
        if (title) title.textContent = 'Local AI Setup';
        if (body) body.textContent = 'The app will use the recommended local model for this machine by default. You can fine-tune cloud, Ollama, and runtime settings later from Settings.';
    }
    const servicesInputs = {
        '#svcName': 'services.namePlaceholder',
        '#svcPrice': 'services.pricePlaceholder',
        '#svcDesc': 'services.descriptionPlaceholder',
        '#svcIcon': 'services.iconPlaceholder',
        '#svcDeliverables': 'services.deliverablesPlaceholder',
        '#svcIdealClient': 'services.idealClientPlaceholder'
    };
    Object.entries(servicesInputs).forEach(([selector, key]) => setPlaceholder(selector, key));
    const addServiceBtn = document.getElementById('addServiceBtn');
    if (addServiceBtn) {
        addServiceBtn.innerHTML = state.editingServiceId
            ? `<i class="fas fa-save"></i> ${escapeHtml(t('services.saveAction'))}`
            : `<i class="fas fa-plus"></i> ${escapeHtml(t('services.addAction'))}`;
    }
    setText('#cancelServiceEditBtn', 'common.cancel');

    setText('#guidedModalTitle', 'guided.title');
    const guidedDesc = document.querySelector('#guidedTaskModal .text-xs.text-gray-500');
    if (guidedDesc) guidedDesc.textContent = t('guided.body');
    setHtml('#guidedGenerateBtn', 'guided.generateButtonHtml');
    setHtml('#guidedAddTasksBtn', 'guided.addToCardButtonHtml');
    setHtml('#reopenBriefBtn', 'brief.reopenButtonHtml');
    setRawHtml('#dashboardSkillsView h3', `<i class="fas fa-brain text-emerald-400"></i> ${escapeHtml(t('skills.title'))}`);
    const skillsSubtitle = document.getElementById('skillsStatsLabel');
    if (skillsSubtitle && !state.activeDashboardDivId) skillsSubtitle.textContent = t('skills.subtitle');
    setHtml('#addSkillBtn', 'skills.addSkillButtonHtml');
    setHtml('#backfillSkillsBtn', 'skills.embedAllButtonHtml');
    document.querySelectorAll('.ai-bp-gen-btn').forEach((btn) => {
        const period = btn.dataset.period;
        const icon = period === 'daily'
            ? 'fa-bolt'
            : period === 'weekly'
                ? 'fa-calendar-week'
                : period === 'monthly'
                    ? 'fa-calendar-alt'
                    : 'fa-calendar';
        const label = period === 'daily' ? t('battle.generateDailyTasks') : t(`period.${period}`);
        btn.innerHTML = `<i class="fas ${icon}"></i> ${escapeHtml(label)}`;
    });
}
