function getAiWelcomeMessage(div) {
    const divisionCopy = getDivisionCopy(div);
    if (getCurrentLanguage() === 'it') {
        return `Ciao! Sono il Direttore AI di ${divisionCopy.name}. Conosco il VFP della tua divisione: "${getDisplayVfp(div)}". Come posso ottimizzare il workflow o aiutarti con la strategia oggi?`;
    }
    if (getCurrentLanguage() === 'ro') {
        return `Salut! Sunt Directorul AI pentru ${divisionCopy.name}. Cunosc VFP-ul diviziei tale: "${getDisplayVfp(div)}". Cum pot optimiza workflow-ul sau ajuta cu strategia astăzi?`;
    }
    return `Hi! I am the AI Director for ${divisionCopy.name}. I know your division's VFP: "${getDisplayVfp(div)}". How can I optimize your workflow or help you write a strategy today?`;
}

function getAiSystemPrompt(div) {
    return `You are the Expert AI Director for: "${getDivisionCopy(div).name}". VFP: "${getDisplayVfp(div)}". Business: "${state.settings.company_name || 'the business'}" owned by "${state.settings.owner_name || 'the owner'}" in "${state.settings.city || 'the current market'}". Respond only in the current platform language (${getCurrentLanguage()}). Personalize all advice to the configured business and services. Give concise, highly tactical advice formatted with standard HTML tags (<b>, <br>).`;
}

function renderAIConversationTabs() {
    const tabs = document.getElementById('aiConversationTabs');
    if (!tabs) return;
    queueTranslationRefresh(state.aiConversations.map((conversation) => conversation.title));
    tabs.innerHTML = state.aiConversations.map((conversation) => `
        <button class="ai-conversation-tab ${conversation.id === state.activeConversationId ? 'active' : ''}" data-conversation-id="${conversation.id}">
            <span class="truncate">${escapeHtml(getCachedTranslation(conversation.title || t('ai.newConversation')))}</span>
            <span class="ai-conversation-count">${conversation.message_count || 0}</span>
            <i class="fas fa-times ai-conversation-delete" data-delete-conversation-id="${conversation.id}"></i>
        </button>
    `).join('');
}

function renderAIChatHistory() {
    const chatBox = document.getElementById('chatHistory');
    const div = state.divisions.find((entry) => entry.id === state.activeDashboardDivId);
    if (!chatBox || !div) return;

    if (!state.chatHistory.length) {
        chatBox.innerHTML = `
            <div class="flex items-start gap-4">
                <div class="w-10 h-10 rounded-full flex items-center justify-center shrink-0 shadow-lg" style="background: var(--dash-accent)">
                    <i class="fas fa-robot text-white"></i>
                </div>
                <div class="glass-panel p-4 rounded-2xl rounded-tl-sm bg-white/5 border border-white/10 text-gray-200 shadow-lg">
                    ${escapeHtml(getAiWelcomeMessage(div)).replace(/&quot;/g, '"').replace(/\n/g, '<br>')}
                </div>
            </div>
        `;
        return;
    }

    chatBox.innerHTML = state.chatHistory.map((message) => {
        if (message.role === 'user') {
            return `
                <div class="flex items-start gap-4 justify-end chat-message">
                    <div class="glass-panel p-4 rounded-2xl rounded-tr-sm text-white max-w-[80%] shadow-lg" style="background: var(--dash-accent)">
                        ${escapeHtml(message.content)}
                    </div>
                </div>
            `;
        }
        return `
            <div class="flex items-start gap-4 chat-message">
                <div class="w-10 h-10 rounded-full flex items-center justify-center shrink-0 shadow-lg" style="background: var(--dash-accent)">
                    <i class="fas fa-robot text-white"></i>
                </div>
                <div class="glass-panel p-4 rounded-2xl rounded-tl-sm bg-white/5 border border-white/20 text-gray-200 max-w-[85%] shadow-lg leading-relaxed">
                    ${formatAiReply(message.content)}
                </div>
            </div>
        `;
    }).join('');
}

async function openAIConversation(conversationId) {
    if (!conversationId) return;
    const data = await api.getAIConversation(conversationId);
    state.activeConversationId = conversationId;
    state.chatHistory = data.messages || [];
    renderAIConversationTabs();
    renderAIChatHistory();
    scrollToBottom();
}

async function loadAIConversations(divId, preferredConversationId = null) {
    const data = await api.getAIConversations(divId);
    state.aiConversations = data.conversations || [];

    if (!state.aiConversations.length) {
        const created = await api.createAIConversation(divId, t('ai.newConversation'));
        state.aiConversations = [{ ...created, message_count: 0 }];
        state.activeConversationId = created.id;
        state.chatHistory = [];
        renderAIConversationTabs();
        renderAIChatHistory();
        return;
    }

    const targetConversationId = preferredConversationId
        || (state.aiConversations.find((entry) => entry.id === state.activeConversationId)?.id)
        || state.aiConversations[0].id;
    renderAIConversationTabs();
    await openAIConversation(targetConversationId);
}

function initAI() {
    const aiInput = document.getElementById('aiInput');
    const sendBtn = document.getElementById('sendAiBtn');
    const tabs = document.getElementById('aiConversationTabs');
    const newConversationBtn = document.getElementById('newConversationBtn');

    const sendMsg = async () => {
        const text = aiInput.value.trim();
        if(!text || !state.activeDashboardDivId || !state.activeConversationId) return;
        
        aiInput.value = '';
        aiInput.style.height = '60px'; 

        const chatBox = document.getElementById('chatHistory');
        const div = state.divisions.find(d => d.id === state.activeDashboardDivId);
        const requestMessages = [{ role: 'system', content: getAiSystemPrompt(div) }, ...state.chatHistory, { role: 'user', content: text }];

        chatBox.innerHTML += `
            <div class="flex items-start gap-4 justify-end chat-message">
                <div class="glass-panel p-4 rounded-2xl rounded-tr-sm text-white max-w-[80%] shadow-lg" style="background: var(--dash-accent)">
                    ${escapeHtml(text)}
                </div>
            </div>
        `;
        scrollToBottom();

        const loadingId = 'loading-' + Date.now();
        chatBox.innerHTML += `
            <div class="flex items-start gap-4 chat-message" id="${loadingId}">
                <div class="w-10 h-10 rounded-full flex items-center justify-center shrink-0 shadow-lg" style="background: var(--dash-accent)">
                    <i class="fas fa-robot text-white"></i>
                </div>
                <div class="glass-panel p-4 rounded-2xl rounded-tl-sm bg-white/5 border border-white/10 text-gray-400 flex items-center gap-1">
                    <svg height="10" width="30" class="fill-current text-white">
                      <circle cx="5" cy="5" r="3" class="typing-dot" />
                      <circle cx="15" cy="5" r="3" class="typing-dot" />
                      <circle cx="25" cy="5" r="3" class="typing-dot" />
                    </svg>
                </div>
            </div>
        `;
        scrollToBottom();

        try {
            const data = await api.chat(requestMessages, state.activeDashboardDivId, state.activeConversationId);
            document.getElementById(loadingId)?.remove();
            chatBox.innerHTML += `
                <div class="flex items-start gap-4 chat-message">
                    <div class="w-10 h-10 rounded-full flex items-center justify-center shrink-0 shadow-lg" style="background: var(--dash-accent)">
                        <i class="fas fa-robot text-white"></i>
                    </div>
                    <div class="glass-panel p-4 rounded-2xl rounded-tl-sm bg-white/5 border border-white/20 text-gray-200 max-w-[85%] shadow-lg leading-relaxed">
                        ${formatAiReply(data.reply)}
                    </div>
                </div>
            `;
            state.chatHistory.push({ role: 'user', content: text });
            state.chatHistory.push({ role: 'assistant', content: data.reply });
            await loadAIConversations(state.activeDashboardDivId, state.activeConversationId);
            scrollToBottom();
        } catch (error) {
            document.getElementById(loadingId)?.remove();
            chatBox.innerHTML += `
                <div class="flex items-start gap-4 chat-message">
                    <div class="w-10 h-10 rounded-full bg-red-500 flex items-center justify-center shrink-0">
                        <i class="fas fa-exclamation-triangle text-white"></i>
                    </div>
                    <div class="glass-panel p-4 rounded-2xl rounded-tl-sm bg-red-500/10 border border-red-500/30 text-red-200">
                        ${escapeHtml(t('common.errorLabel', { error: error.message }))}
                    </div>
                </div>
            `;
            scrollToBottom();
        }
    };

    sendBtn.addEventListener('click', sendMsg);
    aiInput.addEventListener('keypress', (e) => {
        if(e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMsg();
        }
    });
    aiInput.addEventListener('input', function() {
        this.style.height = '60px';
        this.style.height = (this.scrollHeight) + 'px';
    });

    newConversationBtn?.addEventListener('click', async () => {
        if (!state.activeDashboardDivId) return;
        const created = await api.createAIConversation(state.activeDashboardDivId, t('ai.newConversation'));
        await loadAIConversations(state.activeDashboardDivId, created.id);
        aiInput.focus();
    });

    tabs?.addEventListener('click', async (event) => {
        const deleteBtn = event.target.closest('[data-delete-conversation-id]');
        if (deleteBtn) {
            const conversationId = Number(deleteBtn.dataset.deleteConversationId);
            customConfirm(t('ai.deleteConversationConfirm'), async () => {
                await api.deleteAIConversation(conversationId);
                if (state.activeConversationId === conversationId) state.activeConversationId = null;
                await loadAIConversations(state.activeDashboardDivId);
            });
            return;
        }

        const tab = event.target.closest('[data-conversation-id]');
        if (!tab) return;
        await openAIConversation(Number(tab.dataset.conversationId));
    });
}

function scrollToBottom() {
    const container = document.getElementById('chatContainer');
    container.scrollTop = container.scrollHeight;
}

// ====== MODALS INIT ======
function initModals() {
    const dockToggle = document.getElementById('topDockToggle');
    if (dockToggle) {
        dockToggle.addEventListener('click', () => {
            document.body.classList.toggle('dock-collapsed');
            dockToggle.setAttribute('aria-expanded', String(!document.body.classList.contains('dock-collapsed')));
        });
    }

    const briefPanel = document.getElementById('dailyBriefingPanel');
    const reopenBriefBtn = document.getElementById('reopenBriefBtn');
    if (briefPanel) {
        briefPanel.addEventListener('click', (event) => {
            const actionBtn = event.target.closest('[data-brief-action]');
            if (!actionBtn) return;
            const action = actionBtn.dataset.briefAction;
            if (action === 'refresh') {
                renderDailyBriefing(true);
            }
            if (action === 'dismiss') {
                briefPanel.classList.add('hidden');
                reopenBriefBtn?.classList.remove('hidden');
            }
        });
    }
    reopenBriefBtn?.addEventListener('click', () => {
        reopenBriefBtn.classList.add('hidden');
        renderDailyBriefing(true);
    });

    document.getElementById('closeSkillAppearanceModal')?.addEventListener('click', closeSkillAppearancePicker);
    document.getElementById('cancelSkillAppearanceBtn')?.addEventListener('click', closeSkillAppearancePicker);
    document.getElementById('skillIconSearch')?.addEventListener('input', renderSkillIconPicker);
    document.getElementById('skillColorGrid')?.addEventListener('click', (event) => {
        const btn = event.target.closest('[data-color]');
        if (!btn) return;
        const colorInput = document.getElementById('skillCustomColor');
        if (colorInput) colorInput.value = btn.dataset.color;
    });
    document.getElementById('skillIconGrid')?.addEventListener('click', (event) => {
        const btn = event.target.closest('[data-icon]');
        if (!btn) return;
        saveSkillAppearance(btn.dataset.icon);
    });
    document.getElementById('saveSkillColorBtn')?.addEventListener('click', async () => {
        if (!state.activeSkillAppearanceId) return;
        const color = document.getElementById('skillCustomColor')?.value || '#34d399';
        await api.updateSkill(state.activeSkillAppearanceId, { color });
        closeSkillAppearancePicker();
        showToast('Skill color updated.', 'success');
        renderSkills(state.activeDashboardDivId);
    });

    document.getElementById('aiProviderSelect')?.addEventListener('change', () => {
        const modelInput = document.getElementById('aiModelInput');
        if (modelInput) modelInput.value = '';
        syncDesktopRecommendedModels();
    });
    document.getElementById('settingsLocalRuntime')?.addEventListener('change', () => {
        const localRuntimeModel = document.getElementById('settingsLocalRuntimeModel');
        if (localRuntimeModel) localRuntimeModel.value = '';
        syncDesktopRecommendedModels();
    });
    document.getElementById('embeddingProviderSelect')?.addEventListener('change', () => {
        const modelInput = document.getElementById('embeddingModelInput');
        if (modelInput) modelInput.value = '';
        syncDesktopRecommendedModels();
    });
    document.getElementById('onbLanguage')?.addEventListener('change', () => {
        const input = document.getElementById('onbLanguage');
        if (input) input.value = 'en';
        state.settings = { ...(state.settings || {}), app_language: 'en' };
        applyLanguage();
    });

    // Add Item Modal
    document.getElementById('closeAddItemModal').addEventListener('click', closeAddItemModal);
    document.getElementById('cancelAddItemBtn').addEventListener('click', closeAddItemModal);
    
    document.getElementById('confirmAddItemBtn').addEventListener('click', async () => {
        const title = document.getElementById('addItemTitleInput').value.trim();
        const workDate = document.getElementById('addItemDateInput').value || getDashboardDefaultWorkDate();
        if (title && state.activeAddDivisionId) {
            await api.addItem(state.activeAddDivisionId, title, workDate);
            closeAddItemModal();
            await refreshActiveAppState({ maintainFocus: true });
        }
    });
    
    document.getElementById('addItemTitleInput').addEventListener('keypress', async (e) => {
        if (e.key === 'Enter') {
            document.getElementById('confirmAddItemBtn').click();
        }
    });

    document.getElementById('closeModal').addEventListener('click', closeInfoModal);
    document.getElementById('saveInfoBtn').addEventListener('click', async () => {
        const info = document.getElementById('modalTextarea').value;
        if (state.activeModalDivisionId) {
            await api.updateInfo(state.activeModalDivisionId, info);
            const div = state.divisions.find(d => d.id === state.activeModalDivisionId);
            if(div) div.info = info;
            closeInfoModal();
        }
    });

    document.getElementById('closeEditModal').addEventListener('click', closeEditItemModal);
    document.getElementById('deleteItemBtn').addEventListener('click', async () => {
        customConfirm(t('tasks.deleteConfirm'), async () => {
            await api.deleteItem(state.activeEditItemId);
            closeEditItemModal();
            await refreshActiveAppState({ maintainFocus: true });
        });
    });
    
    document.getElementById('copyMagicLinkBtn').addEventListener('click', () => {
        const linkInput = document.getElementById('magicLinkDisplay');
        navigator.clipboard.writeText(linkInput.value).then(() => {
            const btn = document.getElementById('copyMagicLinkBtn');
            btn.innerHTML = `<i class="fas fa-check"></i> ${escapeHtml(t('tasks.copied'))}`;
            btn.classList.remove('bg-emerald-600');
            btn.classList.add('bg-green-500');
            setTimeout(() => { btn.innerHTML = `<i class="fas fa-copy"></i> ${escapeHtml(t('common.copy'))}`; btn.classList.remove('bg-green-500'); btn.classList.add('bg-emerald-600'); }, 2000);
        });
    });
    
    document.getElementById('saveEditItemBtn').addEventListener('click', async () => {
        const title = document.getElementById('editItemTitleInput').value.trim();
        const workDate = document.getElementById('editItemDateInput').value || getTodayDateValue();
        if(title && state.activeEditItemId) {
            await api.updateItemMeta(state.activeEditItemId, { title, work_date: workDate });
            closeEditItemModal();
            await refreshActiveAppState({ maintainFocus: true });
        }
    });

    // Onboarding Guide Modal
    document.getElementById('openGuideBtn').addEventListener('click', openGuideModal);
    
    document.getElementById('closeGuideBtn').addEventListener('click', closeGuideModal);
    document.getElementById('guideSkipBtn').addEventListener('click', () => dismissGuideModal(true));
    document.querySelectorAll('.guide-open-division').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await dismissGuideModal(false);
            openDashboard(Number(btn.dataset.division));
        });
    });

    document.getElementById('guideStartActionBtn').addEventListener('click', () => {
        dismissGuideModal(false);
        setTimeout(() => addNewItem(2), 500); // 2 is Division 2 (Marketing)
    });

    // Services modal
    document.getElementById('openServicesBtn').addEventListener('click', openServicesModal);
    document.getElementById('closeServicesModal').addEventListener('click', closeServicesModal);
    document.getElementById('addServiceBtn').addEventListener('click', saveNewService);
    document.getElementById('cancelServiceEditBtn').addEventListener('click', resetServiceForm);
    document.getElementById('openServiceIconPickerBtn')?.addEventListener('click', openServiceIconPicker);

    // Guided Task modal
    document.getElementById('closeGuidedTaskModal').addEventListener('click', closeGuidedTaskModal);
    document.getElementById('guidedGenerateBtn').addEventListener('click', runGuidedTaskGeneration);
    document.getElementById('guidedAddTasksBtn').addEventListener('click', addGuidedTasksToCard);

    // Guided Battle Plan modal
    document.getElementById('closeGuidedBPModal').addEventListener('click', closeGuidedBPModal);
    document.getElementById('guidedBPGenBtn').addEventListener('click', runGuidedBPGeneration);
    document.getElementById('guidedBPAddBtn').addEventListener('click', applyGuidedBPPlans);
}

function openInfoModal(divId) {
    const div = state.divisions.find(d => d.id === divId);
    if (!div) return;
    const divisionCopy = getDivisionCopy(div);
    state.activeModalDivisionId = divId;
    document.getElementById('modalTitle').textContent = `${divisionCopy.name} ${t('common.info')}`;
    document.getElementById('modalTextarea').value = getDisplayInfo(div);
    
    const modal = document.getElementById('infoModal');
    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('.glass-panel').classList.remove('scale-95'); }, 10);
}

function closeInfoModal() {
    const modal = document.getElementById('infoModal');
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => { modal.classList.add('hidden'); state.activeModalDivisionId = null; }, 300);
}

function openEditItemModal(item) {
    state.activeEditItemId = item.id;
    document.getElementById('editItemTitleInput').value = item.title;
    document.getElementById('editItemDateInput').value = item.work_date || getTodayDateValue();
    
    // Find the item to get its magic_link
    let foundItem = null;
    for (const div of getVisibleDivisions()) {
        foundItem = div.items.find(i => i.id === item.id);
        if (foundItem) break;
    }
    if (!foundItem) {
        for (const div of state.divisions) {
            foundItem = div.items.find(i => i.id === item.id);
            if (foundItem) break;
        }
    }
    
    if (!foundItem) {
        foundItem = item;
    }

    const magicInput = document.getElementById('magicLinkDisplay');
    if (magicInput) {
        magicInput.value = t('common.generating');
    }
    
    const modal = document.getElementById('editItemModal');
    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('.glass-panel').classList.remove('scale-95'); }, 10);

    resolvePortalLinkForItem(foundItem);
}

async function resolvePortalLinkForItem(item) {
    const magicInput = document.getElementById('magicLinkDisplay');
    if (!magicInput || !item) return;
    try {
        const division = state.divisions.find((div) => div.id === item.division_id) || null;
        const todos = Array.isArray(item.todos)
            ? item.todos
            : ((state.itemTodos && state.itemTodos[item.id]) ? state.itemTodos[item.id] : []);
        if (state.authSession?.access_token && state.cloudConfig?.cloudApiUrl) {
            const publicUrl = await syncPortalProjectSnapshot(item, division, todos);
            magicInput.value = publicUrl;
            return;
        }
        if (item.magic_link) {
            const publicBase = (state.cloudConfig?.publicAppUrl || 'https://orgboard.iacovici.it').replace(/\/$/, '');
            magicInput.value = `${publicBase}/portal.html?legacy=${item.magic_link}`;
            return;
        }
        magicInput.value = t('common.generating');
    } catch (error) {
        magicInput.value = `Portal sync failed: ${error.message || 'unknown error'}`;
    }
}

function closeEditItemModal() {
    const modal = document.getElementById('editItemModal');
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => { modal.classList.add('hidden'); state.activeEditItemId = null; }, 300);
}
