// ====== SKILLS ENGINE ======
async function renderSkills(divId) {
    const container = document.getElementById('skillsContainer');
    const statsLabel = document.getElementById('skillsStatsLabel');
    container.innerHTML = `<div class="text-gray-500 text-sm">${escapeHtml(t('common.loading'))}</div>`;

    try {
        const data = await api.getSkills(divId);
        const { skills: skillTree, stats } = data;

        const pct = stats.total > 0 ? Math.round((stats.embedded / stats.total) * 100) : 0;
        queueTranslationRefresh(skillTree.flatMap((core) => [core.name, core.content, ...(core.sub_skills || []).flatMap((sub) => [sub.name, sub.content])]));
        statsLabel.textContent = t('skills.stats', { total: stats.total, pct });

        if (skillTree.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12 text-gray-500">
                    <i class="fas fa-brain text-4xl mb-4 block text-gray-600"></i>
                    <p class="text-lg font-semibold">${escapeHtml(t('skills.emptyTitle'))}</p>
                    <p class="text-sm mt-2">${escapeHtml(t('skills.emptyBody'))}</p>
                </div>`;
            return;
        }

        container.innerHTML = skillTree.map(core => `
            <div class="glass-panel p-6 rounded-2xl border border-emerald-500/20 bg-emerald-500/5">
                <!-- Core Skill Header -->
                <div class="flex items-start justify-between gap-4 mb-4">
                    <div class="flex items-center gap-4 flex-1">
                        <div class="w-14 h-14 rounded-xl skill-icon-chip border flex items-center justify-center text-2xl shrink-0 cursor-pointer hover:scale-110 transition" 
                             onclick="openSkillAppearancePicker(${core.id})" title="Click to change icon or color"
                             style="background:${escapeAttr((core.color || '#34d399') + '22')}; border-color:${escapeAttr(core.color || '#34d399')}55; color:${escapeAttr(core.color || '#34d399')};">
                            <i class="fas ${core.icon}"></i>
                        </div>
                        <div class="flex-1">
                            <h4 class="text-lg font-bold text-white flex items-center gap-2">${escapeHtml(getCachedTranslation(core.name))}</h4>
                            <div class="flex items-center gap-3 mt-1 text-[10px]">
                                <span class="text-emerald-400/60">${core.embedding ? `🧠 ${escapeHtml(t('memory.embedded'))}` : `⏳ ${escapeHtml(t('skills.pendingEmbed'))}`}</span>
                                <span class="text-gray-500">${escapeHtml(t('skills.usedCount', { count: core.use_count }))}</span>
                                ${core.tags ? `<span class="text-gray-600">${core.tags.split(',').map(t => `<span class="bg-white/5 px-1.5 py-0.5 rounded">${escapeHtml(t.trim())}</span>`).join(' ')}</span>` : ''}
                            </div>
                        </div>
                    </div>
                    <div class="flex gap-1.5 shrink-0">
                        <button onclick="editSkillInline(${core.id})" class="text-blue-400 hover:text-white bg-blue-500/10 px-3 py-1.5 rounded-lg text-xs transition" title="Edit"><i class="fas fa-edit"></i></button>
                        <button onclick="aiEditSkill(${core.id})" class="text-purple-400 hover:text-white bg-purple-500/10 px-3 py-1.5 rounded-lg text-xs transition" title="AI Edit"><i class="fas fa-magic"></i></button>
                        <button onclick="deleteSkillItem(${core.id})" class="text-red-400/50 hover:text-red-400 bg-red-500/10 px-2 py-1.5 rounded-lg text-xs transition" title="Delete"><i class="fas fa-trash"></i></button>
                    </div>
                </div>
                <!-- Core Skill Content -->
                <div class="bg-black/30 rounded-xl p-4 text-sm text-gray-300 leading-relaxed whitespace-pre-line border border-white/5 mb-4 skill-content" id="skill-content-${core.id}">${escapeHtml(getCachedTranslation(core.content))}</div>

                <!-- Sub-Skills -->
                ${core.sub_skills && core.sub_skills.length > 0 ? `
                    <div class="border-t border-white/5 pt-4 mt-2">
                        <p class="text-xs text-emerald-400/60 uppercase tracking-wider font-bold mb-3 flex items-center gap-2"><i class="fas fa-sitemap text-[10px]"></i> ${escapeHtml(t('skills.subSkillsCount', { count: core.sub_skills.length }))}</p>
                        <div class="flex flex-col gap-3">
                            ${core.sub_skills.map(sub => `
                                <div class="bg-black/20 rounded-xl p-4 border border-white/5 hover:border-emerald-500/20 transition group">
                                    <div class="flex items-start justify-between gap-3">
                                        <div class="flex items-center gap-3 flex-1">
                                            <div class="w-9 h-9 rounded-lg skill-icon-chip flex items-center justify-center cursor-pointer hover:scale-110 transition shrink-0" 
                                                 onclick="openSkillAppearancePicker(${sub.id})" title="Change icon or color"
                                                 style="background:${escapeAttr((sub.color || '#34d399') + '22')}; border:1px solid ${escapeAttr(sub.color || '#34d399')}55; color:${escapeAttr(sub.color || '#34d399')};">
                                                <i class="fas ${sub.icon} text-sm"></i>
                                            </div>
                                            <div class="flex-1">
                                                <h5 class="text-sm font-semibold text-white">${escapeHtml(getCachedTranslation(sub.name))}</h5>
                                                <span class="text-[10px] text-gray-500">${escapeHtml(t('skills.usedCompact', { count: sub.use_count, status: sub.embedding ? '🧠' : '⏳' }))}</span>
                                            </div>
                                        </div>
                                        <div class="flex gap-1 opacity-0 group-hover:opacity-100 transition shrink-0">
                                            <button onclick="editSkillInline(${sub.id})" class="text-blue-400 hover:text-white bg-blue-500/10 px-2 py-1 rounded text-[10px] transition"><i class="fas fa-edit"></i></button>
                                            <button onclick="aiEditSkill(${sub.id})" class="text-purple-400 hover:text-white bg-purple-500/10 px-2 py-1 rounded text-[10px] transition"><i class="fas fa-magic"></i></button>
                                            <button onclick="deleteSkillItem(${sub.id})" class="text-red-400/50 hover:text-red-400 bg-red-500/10 px-2 py-1 rounded text-[10px] transition"><i class="fas fa-trash"></i></button>
                                        </div>
                                    </div>
                                    <div class="mt-2 text-xs text-gray-400 leading-relaxed whitespace-pre-line skill-content" id="skill-content-${sub.id}">${escapeHtml(getCachedTranslation(sub.content))}</div>
                                </div>
                            `).join('')}
                        </div>
                    </div>` : ''}
                
                <!-- Add Sub-Skill Button -->
                <button onclick="addSubSkill(${core.id}, ${core.division_id})" class="mt-3 w-full py-2.5 bg-white/5 hover:bg-white/10 border border-white/5 rounded-xl text-xs text-gray-400 hover:text-white transition flex items-center justify-center gap-2">
                    <i class="fas fa-plus"></i> ${escapeHtml(t('skills.addSubSkill'))}
                </button>
            </div>
        `).join('');

    } catch(e) {
        container.innerHTML = `<div class="text-red-400 text-sm">${escapeHtml(t('skills.loadFailed'))}</div>`;
    }
}

function editSkillInline(skillId) {
    const el = document.getElementById(`skill-content-${skillId}`);
    if (!el) return;
    const current = el.textContent;
    el.innerHTML = `
        <textarea class="w-full bg-black/40 text-white border border-emerald-500/30 rounded-xl p-3 text-sm focus:outline-none min-h-[120px] resize-y">${current}</textarea>
        <div class="flex gap-2 mt-2 justify-end">
            <button onclick="cancelSkillEdit(${skillId}, '${encodeURIComponent(current)}')" class="text-gray-400 hover:text-white text-xs px-3 py-1.5 rounded-lg bg-white/5 transition">${escapeHtml(t('common.cancel'))}</button>
            <button onclick="saveSkillEdit(${skillId})" class="text-white text-xs px-4 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 transition font-bold">${escapeHtml(t('common.save'))}</button>
        </div>`;
}

function cancelSkillEdit(skillId, encodedContent) {
    const el = document.getElementById(`skill-content-${skillId}`);
    if (el) el.textContent = decodeURIComponent(encodedContent);
}

async function saveSkillEdit(skillId) {
    const el = document.getElementById(`skill-content-${skillId}`);
    const textarea = el.querySelector('textarea');
    if (!textarea) return;

    await api.updateSkill(skillId, { content: textarea.value.trim() });
    showToast(t('skills.updatedToast'), 'success');
    renderSkills(state.activeDashboardDivId);
}

async function aiEditSkill(skillId) {
    customPrompt(t('skills.aiEditorTitle'), t('skills.aiEditorPrompt'), async (instruction) => {
        showToast(t('skills.rewriting'), 'info');
        try {
            const data = await api.aiEditSkill(skillId, instruction);
            if (data.updated_content) {
                const el = document.getElementById(`skill-content-${skillId}`);
                if (el) el.textContent = data.updated_content;
                // Auto-save
                await api.updateSkill(skillId, { content: data.updated_content });
                showToast(t('skills.rewrittenToast'), 'success');
                renderSkills(state.activeDashboardDivId);
            }
        } catch(e) {
            showToast(t('skills.aiEditFailed'), 'error');
        }
    });
}

function openSkillAppearancePicker(skillId) {
    state.activeSkillAppearanceId = skillId;
    const modal = document.getElementById('skillAppearanceModal');
    const searchInput = document.getElementById('skillIconSearch');
    const colorInput = document.getElementById('skillCustomColor');
    if (!modal || !searchInput || !colorInput) return;
    searchInput.value = '';
    const selectedSkill = document.querySelector(`[onclick="openSkillAppearancePicker(${skillId})"]`);
    const inferredColor = selectedSkill?.style?.color || '#34d399';
    colorInput.value = inferredColor;
    renderSkillIconPicker();
    modal.classList.remove('hidden');
    setTimeout(() => {
        modal.classList.remove('opacity-0');
        modal.querySelector('.glass-panel')?.classList.remove('scale-95');
        searchInput.focus();
    }, 10);
}

function closeSkillAppearancePicker() {
    const modal = document.getElementById('skillAppearanceModal');
    if (!modal) return;
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel')?.classList.add('scale-95');
    setTimeout(() => modal.classList.add('hidden'), 250);
}

function renderSkillIconPicker() {
    const grid = document.getElementById('skillIconGrid');
    const searchInput = document.getElementById('skillIconSearch');
    const colorGrid = document.getElementById('skillColorGrid');
    if (!grid || !searchInput || !colorGrid) return;
    const query = searchInput.value.trim().toLowerCase();
    const filtered = SKILL_ICON_PRESETS.filter((entry) => {
        if (!query) return true;
        const haystack = `${entry.label} ${entry.icon} ${entry.keywords.join(' ')}`.toLowerCase();
        return haystack.includes(query);
    });

    grid.innerHTML = filtered.map((entry) => `
        <button class="skill-icon-option" type="button" data-icon="${entry.icon}" title="${escapeAttr(entry.label)}">
            <i class="fas ${entry.icon}"></i>
            <span>${escapeHtml(entry.label)}</span>
        </button>
    `).join('');

    colorGrid.innerHTML = SKILL_COLOR_PRESETS.map((color) => `
        <button class="skill-color-option" type="button" data-color="${color}" style="background:${color}"></button>
    `).join('');
}

async function saveSkillAppearance(icon) {
    const colorInput = document.getElementById('skillCustomColor');
    const color = colorInput?.value || '#34d399';
    if (!state.activeSkillAppearanceId || !icon) return;
    await api.updateSkill(state.activeSkillAppearanceId, { icon, color });
    closeSkillAppearancePicker();
    showToast(t('skills.appearanceUpdated'), 'success');
    renderSkills(state.activeDashboardDivId);
}

async function deleteSkillItem(skillId) {
    customConfirm(t('skills.deleteConfirm'), async () => {
        await api.deleteSkill(skillId);
        showToast(t('skills.deletedToast'), 'info');
        renderSkills(state.activeDashboardDivId);
    });
}

function addSubSkill(parentId, divisionId) {
    customPrompt(t('skills.newSubSkill'), t('skills.newSubSkillPrompt'), async (name) => {
        customPrompt(`${t('skills.subSkillPrefix')}: ${name}`, t('skills.subSkillContentPrompt'), async (content) => {
            await api.addSkill({
                division_id: divisionId,
                parent_id: parentId,
                name: name,
                content: content,
                icon: 'fa-puzzle-piece',
                color: '#60a5fa',
                tags: ''
            });
            showToast(t('skills.subSkillAddedToast', { name }), 'success');
            renderSkills(state.activeDashboardDivId);
        });
    });
}

// ====== MEMORY EXPLORER ======
function renderMemoryLogs(logs, stats, isSearch = false) {
    const container   = document.getElementById('memoryLogContainer');
    const statsLabel  = document.getElementById('memoryStatsLabel');

    if (stats) {
        const pct = stats.total > 0 ? Math.round((stats.embedded / stats.total) * 100) : 0;
        const embColor = pct === 100 ? 'text-green-400' : pct > 50 ? 'text-amber-400' : 'text-red-400';
        statsLabel.innerHTML = `<span class="${embColor}">${escapeHtml(t('memory.stats', { embedded: stats.embedded, total: stats.total, pct }))}</span>`;
    }

    if (!logs || logs.length === 0) {
        container.innerHTML = `<div class="text-gray-500 text-xs italic text-center py-6">${escapeHtml(t('memory.noLogs'))}</div>`;
        return;
    }

    const typeColors = {
        client_created: 'text-blue-400',
        client_moved: 'text-yellow-400',
        task_completed: 'text-green-400',
        battle_plan_achieved: 'text-purple-400',
        agent_action: 'text-amber-400',
        onboarding: 'text-indigo-300',
        service_added: 'text-cyan-400',
        service_updated: 'text-cyan-300',
        service_deleted: 'text-rose-300'
    };
    const typeIcons  = {
        client_created: 'fa-user-plus',
        client_moved: 'fa-arrows-alt',
        task_completed: 'fa-check-circle',
        battle_plan_achieved: 'fa-trophy',
        agent_action: 'fa-bolt',
        onboarding: 'fa-rocket',
        service_added: 'fa-briefcase',
        service_updated: 'fa-pen-to-square',
        service_deleted: 'fa-trash'
    };

    container.innerHTML = logs.map(log => {
        const color    = typeColors[log.type] || 'text-gray-400';
        const icon     = typeIcons[log.type]  || 'fa-circle';
        const score    = log.score > 0 ? `<span class="ml-auto text-[10px] font-mono bg-black/40 px-2 py-0.5 rounded text-amber-300">${(log.score * 100).toFixed(1)}% ${escapeHtml(t('memory.match'))}</span>` : '';
        const embBadge = log.embedded === 1 || log.embedding
            ? `<span class="text-[10px] text-green-400/60 flex items-center gap-1"><i class="fas fa-brain text-[8px]"></i>${escapeHtml(t('memory.embedded'))}</span>`
            : `<span class="text-[10px] text-gray-600 flex items-center gap-1"><i class="fas fa-circle text-[8px]"></i>${escapeHtml(t('memory.noVector'))}</span>`;
        return `
            <div class="memory-row bg-black/30 border border-white/5 rounded-xl p-3 flex items-start gap-3 hover:bg-white/5 transition">
                <i class="fas ${icon} ${color} mt-0.5 shrink-0 text-sm"></i>
                <div class="flex-1 min-w-0">
                    <p class="text-sm text-gray-200 leading-snug">${escapeHtml(log.content)}</p>
                    <div class="flex items-center gap-3 mt-1.5 flex-wrap">
                        <span class="text-[10px] ${color} font-semibold uppercase tracking-wider">${escapeHtml(t(`memory.type.${log.type}`))}</span>
                        <span class="text-[10px] text-gray-500">${new Date(log.timestamp).toLocaleString(getCurrentLanguage() === 'it' ? 'it-IT' : getCurrentLanguage() === 'ro' ? 'ro-RO' : 'en-GB')}</span>
                        ${embBadge}
                        ${score}
                    </div>
                </div>
                <button class="memory-delete-btn delete-memory-btn" data-id="${log.id}" title="${escapeAttr(t('memory.deleteTitle'))}">
                    <i class="fas fa-trash"></i>
                </button>
            </div>`;
    }).join('');

    container.querySelectorAll('.delete-memory-btn').forEach((btn) => {
        btn.addEventListener('click', (e) => {
            e.stopPropagation();
            deleteMemoryLog(btn.dataset.id);
        });
    });
}

async function renderMemoryExplorer() {
    document.getElementById('memoryLogContainer').innerHTML = `<div class="text-gray-500 text-xs italic">${escapeHtml(t('memory.loading'))}</div>`;
    try {
        const data = await api.getMemory();
        renderMemoryLogs(data.logs, data.stats);
    } catch(e) {
        document.getElementById('memoryLogContainer').innerHTML = `<div class="text-red-400 text-xs">${escapeHtml(t('memory.loadFailed'))}</div>`;
    }
}

async function searchMemoryUI() {
    const query = document.getElementById('memorySearchInput').value.trim();
    if (!query) { renderMemoryExplorer(); return; }

    document.getElementById('memoryLogContainer').innerHTML = `<div class="text-amber-400 text-xs flex items-center gap-2"><i class="fas fa-spinner fa-spin"></i> ${escapeHtml(t('memory.searching'))}</div>`;
    try {
        const data = await api.searchMemory(query, state.activeDashboardDivId);
        renderMemoryLogs(data.results, null, true);
        document.getElementById('memoryStatsLabel').innerHTML = `<span class="text-amber-300">${escapeHtml(t('memory.searchResult', { count: data.results.length, query }))}</span>`;
    } catch(e) {
        showToast(t('toast.memorySearchFailed'), 'error');
        renderMemoryExplorer();
    }
}

async function deleteMemoryLog(id) {
    customConfirm(t('toast.memoryDeleteConfirm'), async () => {
        await api.deleteMemory(id);
        if (document.getElementById('memorySearchInput').value.trim()) {
            await searchMemoryUI();
        } else {
            await renderMemoryExplorer();
        }
        showToast(t('memory.deleted'), 'success');
    });
}
