// ====== ONBOARDING WIZARD ======
function openOnboarding() {
    document.getElementById('onboardingModal').classList.remove('hidden');
    const languageInput = document.getElementById('onbLanguage');
    if (languageInput) languageInput.value = 'en';
    const businessTypeInput = document.getElementById('onbBusinessType');
    if (businessTypeInput) businessTypeInput.value = state.onboardingBusinessType || 'web_ai_agency';
    state._onbAiSetup = getDesktopDefaultAiSetup();
    renderDesktopStatusPanel('desktopOnboardingStatus', { showAdvancedOllama: false, showRecommendationNote: false });
    renderOnboardingStep(1);
}

function syncOnboardingAiFields() {
    state._onbAiSetup = getDesktopDefaultAiSetup();
}

function renderOnboardingStep(step) {
    [1,2,3,4].forEach(s => document.getElementById(`onbStep${s}`).classList.add('hidden'));
    document.getElementById(`onbStep${step}`).classList.remove('hidden');
    document.getElementById('onboardingProgress').style.width = `${step * 25}%`;
}

async function onboardingNext1() {
    const name    = document.getElementById('onbOwnerName').value.trim();
    const company = document.getElementById('onbCompanyName').value.trim();
    const city    = document.getElementById('onbCity').value.trim();
    if (!name || !company) return showToast(t('toast.enterNameCompany'), 'warning');
    state._onbIdentity = {
        name,
        company,
        city,
        app_language: 'en'
    };
    state.settings = { ...(state.settings || {}), app_language: state._onbIdentity.app_language };
    applyLanguage();
    renderOnboardingStep(2);
    renderOnboardingServices();
}

function renderOnboardingServices() {
    const container = document.getElementById('onbServicesContainer');
    const selectedTemplate = BUSINESS_TYPE_SERVICE_TEMPLATES[state.onboardingBusinessType] || BUSINESS_TYPE_SERVICE_TEMPLATES.web_ai_agency;
    const descriptionEl = document.getElementById('onbBusinessTypeDescription');
    if (descriptionEl) descriptionEl.textContent = selectedTemplate.description;
    container.innerHTML = state.pendingServices.map((s, i) => `
        <div class="bg-white/5 border border-white/10 rounded-xl p-4 flex flex-col gap-2">
            <div class="flex items-center gap-3">
                <i class="fas ${s.icon} text-xl" style="color:var(--dash-accent,#6366f1)"></i>
                <input class="flex-1 bg-black/30 text-white border border-white/10 rounded-lg px-3 py-1.5 text-sm font-semibold focus:outline-none onb-svc-name" data-idx="${i}" value="${s.name}" placeholder="${escapeAttr(t('services.namePlaceholder'))}">
                <select class="bg-black/30 text-white border border-white/10 rounded-lg px-2 py-1.5 text-sm focus:outline-none onb-svc-currency" data-idx="${i}">
                    <option value="EUR" ${s.currency === 'EUR' ? 'selected' : ''}>EUR</option>
                    <option value="GBP" ${s.currency === 'GBP' ? 'selected' : ''}>GBP</option>
                    <option value="USD" ${s.currency === 'USD' ? 'selected' : ''}>USD</option>
                    <option value="CAD" ${s.currency === 'CAD' ? 'selected' : ''}>CAD</option>
                </select>
                <input class="w-24 bg-black/30 text-white border border-white/10 rounded-lg px-3 py-1.5 text-sm focus:outline-none onb-svc-price" data-idx="${i}" value="${s.price}" placeholder="${escapeAttr(t('services.pricePlaceholder'))}">
                <button onclick="removePendingService(${i})" class="text-red-400/50 hover:text-red-400 transition ml-1"><i class="fas fa-times"></i></button>
            </div>
            <input class="bg-black/20 text-gray-300 border border-white/5 rounded-lg px-3 py-1.5 text-xs focus:outline-none onb-svc-desc" data-idx="${i}" value="${s.description}" placeholder="${escapeAttr(t('services.descriptionPlaceholder'))}">
            <input class="bg-black/20 text-gray-300 border border-white/5 rounded-lg px-3 py-1.5 text-xs focus:outline-none onb-svc-client" data-idx="${i}" value="${s.ideal_client}" placeholder="${escapeAttr(t('services.idealClientPlaceholder'))}">
        </div>`).join('');

    // Sync inputs to state on change
    container.querySelectorAll('input, select').forEach(inp => {
        const handler = (e) => {
            const idx = parseInt(e.target.dataset.idx);
            if (e.target.classList.contains('onb-svc-name'))   state.pendingServices[idx].name = e.target.value;
            if (e.target.classList.contains('onb-svc-price'))  state.pendingServices[idx].price = e.target.value;
            if (e.target.classList.contains('onb-svc-currency')) state.pendingServices[idx].currency = e.target.value;
            if (e.target.classList.contains('onb-svc-desc'))   state.pendingServices[idx].description = e.target.value;
            if (e.target.classList.contains('onb-svc-client')) state.pendingServices[idx].ideal_client = e.target.value;
        };
        inp.addEventListener('input', handler);
        inp.addEventListener('change', handler);
    });
}

function applySelectedBusinessTemplate() {
    const businessTypeInput = document.getElementById('onbBusinessType');
    const templateKey = businessTypeInput?.value || 'custom';
    state.onboardingBusinessType = templateKey;
    if (templateKey === 'custom') {
        renderOnboardingServices();
        showToast('Keeping your current custom services.', 'info');
        return;
    }
    state.pendingServices = cloneServiceTemplate(templateKey);
    renderOnboardingServices();
    showToast(`Loaded ${BUSINESS_TYPE_SERVICE_TEMPLATES[templateKey]?.label || 'business'} template.`, 'success');
}

function removePendingService(idx) {
    state.pendingServices.splice(idx, 1);
    renderOnboardingServices();
}

function addPendingService() {
    state.onboardingBusinessType = 'custom';
    const businessTypeInput = document.getElementById('onbBusinessType');
    if (businessTypeInput) businessTypeInput.value = 'custom';
    state.pendingServices.push({ name:'', price:'0', currency:'EUR', description:'', ideal_client:'', icon:'fa-star' });
    renderOnboardingServices();
}

async function onboardingFinish() {
    renderOnboardingStep(3);
    const logEl = document.getElementById('onbAiLog');
    logEl.innerHTML = '';
    const steps = [
        t('onboarding.log1', { company: state._onbIdentity.company }),
        t('onboarding.log2'),
        t('onboarding.log3'),
        t('onboarding.log4'),
        t('onboarding.log5')
    ];
    for (const s of steps) {
        logEl.innerHTML += `<div class="flex items-center gap-2 text-green-400"><i class="fas fa-circle-notch fa-spin text-xs"></i> ${s}</div>`;
        await new Promise(r => setTimeout(r, 600));
    }

    try {
        const aiSetup = state._onbAiSetup || getDesktopDefaultAiSetup();
        if (aiSetup.local_runtime === 'embedded') {
            logEl.innerHTML += `<div class="flex items-center gap-2 text-sky-300"><i class="fas fa-circle-notch fa-spin text-xs"></i> Installing the Apple Silicon local runtime...</div>`;
            await api.installLocalRuntime();
            logEl.innerHTML += `<div class="flex items-center gap-2 text-sky-300"><i class="fas fa-circle-notch fa-spin text-xs"></i> Downloading the recommended local model...</div>`;
            await api.pullLocalRuntimeModel(aiSetup.local_runtime_model);
        }
        await saveSettingsPatch({
            ai_provider: aiSetup.ai_provider,
            ai_model: aiSetup.ai_model,
            ai_api_key: aiSetup.ai_api_key,
            embedding_provider: aiSetup.embedding_provider,
            embedding_model: aiSetup.embedding_model,
            local_runtime: aiSetup.local_runtime,
            local_runtime_model: aiSetup.local_runtime_model
        });
        const result = await api.completeOnboarding({
            owner_name: state._onbIdentity.name,
            company_name: state._onbIdentity.company,
            city: state._onbIdentity.city,
            services: state.pendingServices,
            app_language: state._onbIdentity.app_language,
            ai_provider: aiSetup.ai_provider,
            ai_model: aiSetup.ai_model,
            ai_api_key: aiSetup.ai_api_key
        });
        state.settings = await api.getSettings();
        applyLanguage();
        const summary = result.skipped
            ? t('onboarding.summarySkipped')
            : result.ai_used
                ? t('onboarding.summaryAi', { vfps: result.vfps_updated, plans: result.battle_plans_created })
                : t('onboarding.summaryNoAi');
        logEl.innerHTML += `<div class="text-emerald-400 font-bold mt-2"><i class="fas fa-check-circle mr-2"></i>${summary}</div>`;
        if (result.ai_setup_message) {
            const toneClass = result.ai_used ? 'text-sky-300' : 'text-amber-300';
            logEl.innerHTML += `<div class="${toneClass} mt-2 text-sm">${escapeHtml(result.ai_setup_message)}</div>`;
        }
    } catch(e) {
        logEl.innerHTML += `<div class="text-red-400 mt-2"><i class="fas fa-triangle-exclamation mr-2"></i>${escapeHtml(t('onboarding.setupFailed', { error: e.message || t('common.unknownError') }))}</div>`;
        showToast(t('toast.onboardingFailed'), 'error');
        return;
    }

    await new Promise(r => setTimeout(r, 1000));
    renderOnboardingStep(4);
    document.getElementById('onbDoneCompany').textContent = state._onbIdentity.company;
    const summaryLine = document.querySelector('#onbStep4 .text-gray-300.mb-2');
    if (summaryLine) summaryLine.innerHTML = t('onboarding.doneWorkspace', { company: `<b id="onbDoneCompany" class="text-yellow-400">${escapeHtml(state._onbIdentity.company)}</b>` });
}

async function launchFromOnboarding() {
    document.getElementById('onboardingModal').classList.add('hidden');
    state.settings = await api.getSettings();
    await bootApp();
    startLiveSyncLoop();
}

function openGuideModal() {
    const modal = document.getElementById('guideModal');
    if (!modal) return;
    modal.classList.remove('hidden');
    setTimeout(() => {
        modal.classList.remove('opacity-0');
        modal.querySelector('.glass-panel')?.classList.remove('scale-95');
    }, 10);
}

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

async function dismissGuideModal(showFeedback = false) {
    await saveSettingsPatch({ platform_tutorial_dismissed: 1 });
    closeGuideModal();
    if (showFeedback) showToast(t('guide.dismissedToast'), 'info');
}

// ====== DAILY BRIEFING ======
async function renderDailyBriefing(force = false) {
    const panel = document.getElementById('dailyBriefingPanel');
    const reopenBtn = document.getElementById('reopenBriefBtn');
    if (!panel) return;
    panel.innerHTML = `<div class="flex items-center gap-3 text-gray-400 text-sm"><i class="fas fa-spinner fa-spin"></i> ${escapeHtml(getCurrentLanguage() === 'it' ? 'Sto generando il briefing...' : getCurrentLanguage() === 'ro' ? 'Generez briefingul...' : 'Generating your briefing...')}</div>`;
    panel.classList.remove('hidden');
    reopenBtn?.classList.add('hidden');
    try {
        const b = await api.getDailyBriefing(force);
        const locale = getCurrentLanguage() === 'it' ? 'it-IT' : getCurrentLanguage() === 'ro' ? 'ro-RO' : 'en-GB';
        const day = new Date().toLocaleDateString(locale,{weekday:'long',day:'numeric',month:'long'});
        panel.innerHTML = `
            <div class="daily-brief-main">
                <div class="daily-brief-copy">
                    <p class="text-xs text-gray-400 uppercase tracking-wider">${day}</p>
                    <p class="text-white font-semibold text-sm mt-0.5">${escapeHtml(b.greeting)}</p>
                </div>
                <div class="daily-brief-priorities">
                    ${(b.priorities||[]).map((p,i) => `
                        <div class="daily-brief-chip bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-gray-200 flex items-center gap-2">
                            <span class="w-4 h-4 rounded-full bg-white/10 flex items-center justify-center text-[10px] font-bold text-white">${i+1}</span>
                            ${escapeHtml(p)}
                        </div>`).join('')}
                    <div class="daily-brief-focus bg-indigo-500/20 border border-indigo-500/30 rounded-lg px-3 py-1.5 text-xs text-indigo-200 flex items-center gap-2">
                        <i class="fas fa-hat-wizard text-indigo-400"></i>
                        ${escapeHtml(getCurrentLanguage() === 'it' ? 'Focus' : getCurrentLanguage() === 'ro' ? 'Focus' : 'Focus')}: <b>${escapeHtml(b.focus_division)}</b>
                    </div>
                </div>
            </div>
            <div class="daily-brief-actions">
                <button class="daily-brief-btn text-gray-400 hover:text-white transition p-2 rounded-lg hover:bg-white/5" data-brief-action="refresh" title="${escapeAttr(t('brief.refresh'))}"><i class="fas fa-sync text-xs"></i></button>
                <button class="daily-brief-btn text-gray-400 hover:text-white transition p-2 rounded-lg hover:bg-white/5" data-brief-action="dismiss" title="${escapeAttr(t('brief.dismiss'))}"><i class="fas fa-times text-xs"></i></button>
            </div>`;
    } catch(e) { panel.classList.add('hidden'); }
}

// ====== GUIDED AI TASK MODAL ======
const DIVISION_QUESTIONS = {
    2: [{ key:'budget',     label:'Client budget range?',           ph:'e.g. €500-€2,000' },
        { key:'channel',    label:'Marketing channel to use?',      ph:'e.g. Cold email, Instagram, Google Ads' },
        { key:'goal',       label:'Main conversion goal?',          ph:'e.g. Book a discovery call' }],
    3: [{ key:'amount',     label:'Invoice amount?',                ph:'e.g. €1,500 deposit' },
        { key:'deadline',   label:'Payment deadline?',              ph:'e.g. Net 7 days' },
        { key:'method',     label:'Payment method?',                ph:'e.g. Bank transfer, Stripe' }],
    4: [{ key:'stack',      label:'Tech stack / platform?',         ph:'e.g. WordPress, Next.js, n8n' },
        { key:'deadline',   label:'Delivery deadline?',             ph:'e.g. 2 weeks' },
        { key:'notes',      label:'Special requirements or blockers?', ph:'e.g. Client wants CRM integration' }],
    5: [{ key:'scope',      label:'What needs testing?',            ph:'e.g. Full website, checkout flow' },
        { key:'device',     label:'Priority device/browser?',       ph:'e.g. iPhone Safari, Chrome' },
        { key:'blockers',   label:'Known issues to check?',         ph:'e.g. Form not sending emails' }],
    6: [{ key:'status',     label:'Client satisfaction level?',     ph:'e.g. Very happy, needs follow-up' },
        { key:'ask',        label:'What do you need from client?',   ph:'e.g. Google review, referral, renewal' },
        { key:'notes',      label:'Any open support tickets?',       ph:'e.g. Logo update requested' }],
    DEFAULT: [{ key:'goal',     label:'Main goal for this client right now?', ph:'e.g. Launch website by Friday' },
              { key:'context',  label:'Any important context or blockers?',   ph:'e.g. Client slow to respond' },
              { key:'priority', label:'Highest priority task?',               ph:'e.g. Get design approval' }]
};

function openGuidedTaskModal(itemId, divId, clientName) {
    state.guidedTaskItemId = itemId;
    const questions = DIVISION_QUESTIONS[divId] || DIVISION_QUESTIONS.DEFAULT;
    const div = state.divisions.find(d => d.id === divId);

    document.getElementById('guidedModalTitle').textContent  = `AI Quick Brief`;
    document.getElementById('guidedModalClient').textContent = `${clientName} · ${div?.name || ''}`;
    document.getElementById('guidedTasksResult').classList.add('hidden');
    document.getElementById('guidedAddTasksBtn').classList.add('hidden');
    const generateBtn = document.getElementById('guidedGenerateBtn');
    generateBtn.classList.remove('hidden');
    generateBtn.innerHTML = '<i class="fas fa-magic"></i> Generate Tasks';
    generateBtn.disabled = false;

    document.getElementById('guidedQuestionsContainer').innerHTML = questions.map(q => `
        <div>
            <label class="block text-xs text-gray-400 mb-1 font-semibold uppercase tracking-wider">${q.label}</label>
            <input type="text" id="gq_${q.key}" placeholder="${q.ph}"
                class="w-full bg-black/30 text-white border border-white/10 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--dash-accent)] transition">
        </div>`).join('');

    const modal = document.getElementById('guidedTaskModal');
    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('.glass-panel').classList.remove('scale-95'); }, 10);
}

function closeGuidedTaskModal() {
    const m = document.getElementById('guidedTaskModal');
    const btn = document.getElementById('guidedGenerateBtn');
    if (btn) {
        btn.innerHTML = '<i class="fas fa-magic"></i> Generate Tasks';
        btn.disabled = false;
        btn.classList.remove('hidden');
    }
    m.classList.add('opacity-0');
    m.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => m.classList.add('hidden'), 300);
}

async function runGuidedTaskGeneration() {
    const btn = document.getElementById('guidedGenerateBtn');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Asking AI...';
    btn.disabled  = true;

    const answers = {};
    document.querySelectorAll('#guidedQuestionsContainer input').forEach(inp => {
        const key = inp.id.replace('gq_','');
        if (inp.value.trim()) answers[key] = inp.value.trim();
    });

    try {
        const data   = await api.guidedGenerateTasks(state.guidedTaskItemId, answers);
        const tasks  = data.tasks || [];
        document.getElementById('guidedTasksResult').innerHTML = tasks.map((t,i) => `
            <label class="flex items-start gap-3 bg-white/5 rounded-xl p-3 border border-white/5 cursor-pointer hover:bg-white/10 transition">
                <input type="checkbox" class="guided-task-cb mt-0.5 shrink-0" checked data-task="${escapeAttr(t)}">
                <span class="text-sm text-gray-200">${escapeHtml(t)}</span>
            </label>`).join('');
        document.getElementById('guidedTasksResult').classList.remove('hidden');
        document.getElementById('guidedAddTasksBtn').classList.remove('hidden');
        document.getElementById('guidedGenerateBtn').classList.add('hidden');
        showToast(`${tasks.length} tasks generated!`, 'success');
    } catch(e) {
        showToast('AI generation failed. Check your AI settings.', 'error');
        btn.innerHTML = '<i class="fas fa-magic"></i> Generate Tasks';
        btn.disabled  = false;
    }
}

async function addGuidedTasksToCard() {
    const selected = [...document.querySelectorAll('.guided-task-cb:checked')].map(cb => cb.dataset.task);
    if (selected.length === 0) return showToast('Select at least one task.', 'warning');
    // Tasks already saved by the server — just refresh board
    await refreshActiveAppState({ maintainFocus: true });
    closeGuidedTaskModal();
    showToast(`${selected.length} tasks added to card!`, 'success');
}

// ====== GUIDED BATTLE PLAN MODAL ======
const BP_QUESTIONS = {
    yearly:  [{ key:'vision',   label:"What's your #1 business goal this year?",      ph:'e.g. Reach €10k MRR' },
              { key:'weakness', label:'Biggest weakness to fix this year?',           ph:'e.g. No consistent lead flow' }],
    monthly: [{ key:'target',   label:"This month's revenue target?",                ph:'e.g. €3,000 new contracts' },
              { key:'worked',   label:'What worked last month?',                      ph:'e.g. Cold email campaign' },
              { key:'blocker',  label:"Biggest blocker this month?",                  ph:'e.g. Too many revisions eating time' }],
    weekly:  [{ key:'mustwin',   label:'The ONE thing you must accomplish this week?', ph:'e.g. Close the Rossi contract' },
              { key:'available', label:'Hours available this week?',                  ph:'e.g. 25 hours' }],
    daily:   [{ key:'yesterday',label:"What did you NOT finish yesterday?",           ph:'e.g. Client follow-up call' },
              { key:'energy',   label:'Energy level today (1-10)?',                  ph:'e.g. 8' },
              { key:'blocker',  label:'Any blocker for today?',                      ph:'e.g. Waiting on client assets' }]
};

function openGuidedBPModal(divId, period) {
    state.guidedBPPeriod = period;
    state.guidedBPDivId  = divId;
    const questions = BP_QUESTIONS[period] || [];
    const div = state.divisions.find(d => d.id === divId);
    const periodLabel = t(`period.${period}`);

    document.getElementById('guidedBPTitle').textContent  = t('guidedBP.title', { period: periodLabel });
    document.getElementById('guidedBPDiv').textContent    = div ? getDivisionCopy(div).name : '';
    document.getElementById('guidedBPResult').classList.add('hidden');
    document.getElementById('guidedBPAddBtn').classList.add('hidden');
    const generateBtn = document.getElementById('guidedBPGenBtn');
    generateBtn.classList.remove('hidden');
    generateBtn.innerHTML = `<i class="fas fa-magic"></i> ${escapeHtml(t('guidedBP.generateGoals'))}`;
    generateBtn.disabled = false;

    document.getElementById('guidedBPQuestionsContainer').innerHTML = questions.map(q => `
        <div>
            <label class="block text-xs text-gray-400 mb-1 font-semibold uppercase tracking-wider">${q.label}</label>
            <input type="text" id="gbpq_${q.key}" placeholder="${q.ph}"
                class="w-full bg-black/30 text-white border border-white/10 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--dash-accent)] transition">
        </div>`).join('');

    const modal = document.getElementById('guidedBPModal');
    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('.glass-panel').classList.remove('scale-95'); }, 10);
}

function closeGuidedBPModal() {
    const m = document.getElementById('guidedBPModal');
    const btn = document.getElementById('guidedBPGenBtn');
    if (btn) {
        btn.innerHTML = `<i class="fas fa-magic"></i> ${escapeHtml(t('guidedBP.generateGoals'))}`;
        btn.disabled = false;
        btn.classList.remove('hidden');
    }
    m.classList.add('opacity-0');
    m.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => m.classList.add('hidden'), 300);
}

async function runGuidedBPGeneration() {
    const btn = document.getElementById('guidedBPGenBtn');
    btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> ${escapeHtml(t('guidedBP.thinking'))}`;
    btn.disabled  = true;

    const answers = {};
    document.querySelectorAll('#guidedBPQuestionsContainer input').forEach(inp => {
        const key = inp.id.replace('gbpq_','');
        if (inp.value.trim()) answers[key] = inp.value.trim();
    });

    try {
        const data  = await api.guidedBattlePlan(state.guidedBPDivId, state.guidedBPPeriod, answers);
        const plans = data.plans || [];
        document.getElementById('guidedBPResult').innerHTML = plans.map((p,i) => `
            <div class="bg-white/5 rounded-xl p-3 border border-white/5 flex items-start gap-3">
                <i class="fas fa-chess-knight text-sm mt-0.5" style="color:var(--dash-accent)"></i>
                <span class="text-sm text-gray-200">${escapeHtml(p)}</span>
            </div>`).join('');
        document.getElementById('guidedBPResult').classList.remove('hidden');
        document.getElementById('guidedBPAddBtn').classList.remove('hidden');
        document.getElementById('guidedBPGenBtn').classList.add('hidden');
        showToast(t('guidedBP.generatedToast', { count: plans.length }), 'success');
    } catch(e) {
        showToast(t('guidedBP.generationFailed'), 'error');
        btn.innerHTML = `<i class="fas fa-magic"></i> ${escapeHtml(t('guidedBP.generateGoals'))}`;
        btn.disabled  = false;
    }
}

async function applyGuidedBPPlans() {
    // Plans are already saved server-side
    await refreshActiveAppState({ maintainFocus: true });
    closeGuidedBPModal();
    showToast(t('guidedBP.addedToast'), 'success');
}
