async function renderBattlePlan(divId, options = {}) {
    const div = state.divisions.find(d => d.id === divId);
    if (!div || !state.battlePlansData) return;
    const mergedOptions = {
        containerId: 'battlePlanGrid',
        aiButtonsSelector: '.ai-bp-gen-btn',
        ...options
    };

    const plans = state.battlePlansData.plans;
    queueTranslationRefresh(plans.map((plan) => plan.title));
    const periods = ['yearly', 'monthly', 'weekly', 'daily'];
    const container = document.getElementById(mergedOptions.containerId);
    if (!container) return;
    
    container.innerHTML = periods.map(p => {
        const colPlans = plans.filter(x => x.period === p);
        const title = t(`period.${p}`);
        let colorClass = 'text-blue-400';
        if(p === 'monthly') colorClass = 'text-green-400';
        if(p === 'weekly') colorClass = 'text-yellow-400';
        if(p === 'daily') colorClass = 'text-purple-400';

        return `
        <div class="glass-panel p-5 rounded-2xl border border-white/5 bg-black/40 shadow-xl flex flex-col">
            <h4 class="text-lg font-extrabold ${colorClass} mb-4 flex items-center justify-between border-b border-white/10 pb-2">
                ${escapeHtml(title)} ${escapeHtml(t('battle.goals'))}
                <button class="add-bp-btn text-white/50 hover:text-white transition" data-period="${p}"><i class="fas fa-plus-circle"></i></button>
            </h4>
            <div class="flex-1 flex flex-col gap-2 overflow-y-auto custom-scrollbar pr-2" style="max-height: 400px;">
                ${colPlans.map(plan => `
                    <div class="bg-white/5 border border-white/5 rounded-lg p-3 group relative hover:bg-white/10 transition">
                        <div class="flex items-start gap-2">
                            <input type="checkbox" class="bp-checkbox shrink-0 mt-1" ${plan.done ? 'checked' : ''} data-id="${plan.id}">
                            <span class="text-sm text-gray-200 ${plan.done ? 'line-through opacity-50' : ''}">${escapeHtml(getCachedTranslation(plan.title))}</span>
                        </div>
                        <button class="bp-delete-btn absolute top-2 right-2 text-red-500/50 hover:text-red-500 opacity-0 group-hover:opacity-100 transition" data-id="${plan.id}"><i class="fas fa-trash text-xs"></i></button>
                    </div>
                `).join('')}
                ${colPlans.length === 0 ? `<p class="text-xs text-gray-500 italic text-center mt-4">${escapeHtml(t('battle.noGoals'))}</p>` : ''}
            </div>
        </div>
        `;
    }).join('');

    container.querySelectorAll('.add-bp-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const p = e.currentTarget.dataset.period;
            customPrompt(t('battle.addGoalTitle', { period: t(`period.${p}`) }), t('battle.enterGoal'), async (title) => {
                await api.addBattlePlan({ division_id: divId, period: p, title: title });
                state.battlePlansData = await api.getBattlePlans(divId);
                renderBattlePlan(divId, mergedOptions);
                if (p === 'daily') await refreshActiveAppState({ maintainFocus: true });
            });
        });
    });

    container.querySelectorAll('.bp-checkbox').forEach(chk => {
        chk.addEventListener('change', async (e) => {
            await api.toggleBattlePlan(e.target.dataset.id, e.target.checked);
            state.battlePlansData = await api.getBattlePlans(divId);
            renderBattlePlan(divId, mergedOptions);
        });
    });

    container.querySelectorAll('.bp-delete-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const bpId = e.currentTarget.dataset.id;
            customConfirm(t('battle.deleteGoalConfirm'), async () => {
                await api.deleteBattlePlan(bpId);
                state.battlePlansData = await api.getBattlePlans(divId);
                renderBattlePlan(divId, mergedOptions);
            });
        });
    });

    // AI Battle Plan Generator — opens Guided Brief modal
    document.querySelectorAll(mergedOptions.aiButtonsSelector).forEach(btn => {
        const newBtn = btn.cloneNode(true);
        btn.parentNode.replaceChild(newBtn, btn);
        newBtn.addEventListener('click', (e) => {
            openGuidedBPModal(divId, e.currentTarget.dataset.period);
        });
    });
}

// ====== TRAINING ENGINE ======
async function renderTraining(divId) {
    const div = state.divisions.find(d => d.id === divId);
    if (!div || !state.trainingsData) return;

    const modules = state.trainingsData.trainings;
    queueTranslationRefresh(modules.map((m) => m.title));
    const container = document.getElementById('trainingContent');
    
    if(modules.length === 0) {
        container.innerHTML = `<p class="text-gray-500 text-center italic mt-10">${escapeHtml(t('training.empty'))}</p>`;
    } else {
        container.innerHTML = modules.map((m, i) => `
            <div class="glass-panel p-6 rounded-2xl border border-white/5 bg-black/40 hover:bg-white/5 transition-all cursor-pointer flex items-center justify-between gap-5 group tr-module-btn" data-id="${m.id}">
                <div class="flex items-center gap-5 min-w-0 flex-1">
                    <div class="w-12 h-12 rounded-xl flex items-center justify-center text-xl text-white shadow-lg transition-transform group-hover:scale-110 group-hover:rotate-3 shrink-0" style="background: var(--dash-accent)">
                        <i class="fas ${m.icon}"></i>
                    </div>
                    <div class="min-w-0 flex-1">
                        <h4 class="text-lg font-bold text-white mb-1 leading-snug break-words">${escapeHtml(t('training.module', { number: i + 1 }))}: ${escapeHtml(getTrainingTitleDisplay(m))}</h4>
                        <p class="text-sm text-gray-400 leading-snug">${escapeHtml(t('training.clickRead'))}</p>
                    </div>
                </div>
                <div class="flex items-center gap-4 shrink-0">
                    <span class="text-xs font-semibold text-gray-500 bg-black/50 px-3 py-1 rounded-full whitespace-nowrap"><i class="far fa-clock mr-1"></i> ${escapeHtml(normalizeTranslatableText(m.read_time) || '10 min')}</span>
                    <button class="w-10 h-10 rounded-full border border-white/10 flex items-center justify-center text-gray-400 group-hover:text-white group-hover:border-white/30 transition-all shrink-0">
                        <i class="fas fa-book-reader text-sm"></i>
                    </button>
                </div>
            </div>
        `).join('');

        document.querySelectorAll('.tr-module-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const mod = modules.find(x => x.id == btn.dataset.id);
                queueTranslationRefresh([mod.content]);
                document.getElementById('trReaderTitle').textContent = getTrainingTitleDisplay(mod);
                document.getElementById('trReaderTime').textContent = normalizeTranslatableText(mod.read_time) || '10 min';
                document.getElementById('trReaderContent').innerHTML = getTrainingContentDisplay(mod);
                const modal = document.getElementById('trainingReaderModal');
                modal.classList.remove('hidden');
                setTimeout(() => modal.classList.remove('opacity-0', 'scale-95'), 10);
            });
        });
    }

    // AI SOP Generator Feature
    const genBtn = document.getElementById('generateSopBtn');
    // Remove old listeners by cloning
    const newBtn = genBtn.cloneNode(true);
    genBtn.parentNode.replaceChild(newBtn, genBtn);
    
    newBtn.addEventListener('click', async () => {
        customPrompt(t('training.aiGeneratorTitle'), t('training.aiGeneratorPrompt'), async (topic) => {
            newBtn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> ${escapeHtml(t('common.generating'))}`;
            newBtn.disabled = true;

            const promptStr = `Write a comprehensive, HTML formatted Standard Operating Procedure (SOP) for the topic: "${topic}". Business: "${state.settings.company_name || 'the business'}". Services context should follow the configured catalog. Make it actionable, step-by-step. Use h3, p, and b tags only.`;
            try {
                const res = await api.chat([{ role: 'system', content: 'You are an expert operations manager.' }, { role: 'user', content: promptStr }], divId);
                await api.addTraining({
                    division_id: divId, title: topic.trim(), content: res.reply, read_time: '10 min', icon: 'fa-file-alt'
                });
                state.trainingsData = await api.getTrainings(divId);
                renderTraining(divId);
            } catch(e) {
                showToast(t('training.generateFail'), "error");
            }
            newBtn.innerHTML = `<i class="fas fa-magic"></i> ${escapeHtml(t('training.generate'))}`;
            newBtn.disabled = false;
        });
    });
}

document.getElementById('closeTrReaderModal').addEventListener('click', () => {
    const modal = document.getElementById('trainingReaderModal');
    modal.classList.add('opacity-0', 'scale-95');
    setTimeout(() => modal.classList.add('hidden'), 300);
});

