// sp-tools-growth.js — Pidgey Growth: CRM, Mailing List, SEO & Content Tool Implementations

const CRM_FILE_KEY = '_file_pidgey_crm.json';
const MAILING_LIST_KEY = '_file_pidgey_mailing_lists.json';

async function loadCRM() {
    const data = await chrome.storage.local.get(CRM_FILE_KEY);
    if (data[CRM_FILE_KEY]) {
        try { return JSON.parse(data[CRM_FILE_KEY]); } catch { return []; }
    }
    return [];
}

async function saveCRM(contacts) {
    await chrome.storage.local.set({ [CRM_FILE_KEY]: JSON.stringify(contacts, null, 2) });
}

async function loadMailingLists() {
    const data = await chrome.storage.local.get(MAILING_LIST_KEY);
    if (data[MAILING_LIST_KEY]) {
        try { return JSON.parse(data[MAILING_LIST_KEY]); } catch { return {}; }
    }
    return {};
}

async function saveMailingLists(lists) {
    await chrome.storage.local.set({ [MAILING_LIST_KEY]: JSON.stringify(lists, null, 2) });
}

function phoenixCheck() {
    if (!document.body.classList.contains('phoenix-mode')) {
        return {
            display: `🔥 **Phoenix Upgrade Required**\n\nChirp! CRM & Mailing Lists need **Phoenix Mode** for persistent storage!\n\n*Click the **⬆️ Upgrade** button to unlock everything!*`,
            result: `⚠️ CRM/Mailing List blocked - User does not have Phoenix Mode.`
        };
    }
    return null;
}

function csvEscape(val) {
    if (val == null) return '';
    const s = String(val);
    if (s.includes(',') || s.includes('"') || s.includes('\n')) {
        return `"${s.replace(/"/g, '""')}"`;
    }
    return s;
}

export async function executeGrowthTool(name, args, _ui, _state) {
    const { setStatus, playAudioAlert } = _ui;
    const { config } = _state;

    switch (name) {

        // ===================== CRM TOOLS =====================

        case 'growth_crm_add_contact': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📇 Adding contact to CRM...');

            const contacts = await loadCRM();
            const email = (args.email || `${(args.name || 'unknown').toLowerCase().replace(/\s+/g, '.')}@unknown`).toLowerCase().trim();

            const existing = contacts.find(c => c.email === email);
            if (existing) {
                return {
                    display: `⚠️ **Contact already exists:** ${existing.name}`,
                    result: `Contact with email ${email} already in CRM (stage: ${existing.stage}). Use growth_crm_update_contact to modify.`
                };
            }

            const now = new Date().toISOString();
            const contact = {
                id: `crm_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`,
                name: args.name || 'Unknown',
                email,
                company: args.company || '',
                phone: args.phone || '',
                url: args.url || '',
                source: args.source || 'other',
                stage: args.stage || 'lead',
                tags: args.tags ? args.tags.split(',').map(t => t.trim().toLowerCase()) : [],
                notes: args.notes ? [{ date: now, text: args.notes }] : [],
                created: now,
                updated: now
            };

            contacts.push(contact);
            await saveCRM(contacts);
            playAudioAlert('chirp');

            return {
                display: `📇 **Added to CRM:** ${contact.name} (${contact.stage})`,
                result: `Contact added:\n- Name: ${contact.name}\n- Email: ${contact.email}\n- Company: ${contact.company}\n- Source: ${contact.source}\n- Stage: ${contact.stage}\n- Tags: ${contact.tags.join(', ') || 'none'}\n\nTotal contacts in CRM: ${contacts.length}`
            };
        }

        case 'growth_crm_search': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('🔍 Searching CRM...');

            const contacts = await loadCRM();
            if (contacts.length === 0) {
                return { display: '📇 **CRM Empty**', result: 'No contacts in the CRM yet. Use growth_crm_add_contact to add leads.' };
            }

            let filtered = [...contacts];

            if (args.stage) {
                filtered = filtered.filter(c => c.stage === args.stage.toLowerCase());
            }
            if (args.source) {
                filtered = filtered.filter(c => c.source === args.source.toLowerCase());
            }
            if (args.tag) {
                const tag = args.tag.toLowerCase();
                filtered = filtered.filter(c => c.tags && c.tags.includes(tag));
            }
            if (args.query) {
                const q = args.query.toLowerCase();
                filtered = filtered.filter(c =>
                    (c.name || '').toLowerCase().includes(q) ||
                    (c.email || '').toLowerCase().includes(q) ||
                    (c.company || '').toLowerCase().includes(q) ||
                    (c.notes || []).some(n => n.text.toLowerCase().includes(q))
                );
            }

            if (filtered.length === 0) {
                return { display: '🔍 **No matches**', result: `No contacts matched your filters. Total CRM contacts: ${contacts.length}` };
            }

            const lines = filtered.slice(0, 25).map(c =>
                `**${c.name}** <${c.email}>\n  Company: ${c.company || '—'} | Stage: ${c.stage} | Source: ${c.source}\n  Tags: ${(c.tags || []).join(', ') || 'none'} | Added: ${c.created?.substring(0, 10) || '?'}`
            );

            return {
                display: `🔍 **Found ${filtered.length} contact(s)**`,
                result: `CRM Search Results (${filtered.length} of ${contacts.length} total):\n\n${lines.join('\n\n')}${filtered.length > 25 ? `\n\n... and ${filtered.length - 25} more. Use more specific filters.` : ''}`
            };
        }

        case 'growth_crm_update_contact': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('✏️ Updating CRM contact...');

            const contacts = await loadCRM();
            const email = (args.email || '').toLowerCase().trim();
            const idx = contacts.findIndex(c => c.email === email);

            if (idx === -1) {
                return { display: `❌ **Contact not found:** ${email}`, result: `No contact with email "${email}" in CRM.` };
            }

            const contact = contacts[idx];
            const changes = [];

            if (args.name) { contact.name = args.name; changes.push(`name → ${args.name}`); }
            if (args.company) { contact.company = args.company; changes.push(`company → ${args.company}`); }
            if (args.phone) { contact.phone = args.phone; changes.push(`phone → ${args.phone}`); }
            if (args.url) { contact.url = args.url; changes.push(`url → ${args.url}`); }
            if (args.stage) { contact.stage = args.stage.toLowerCase(); changes.push(`stage → ${args.stage}`); }
            if (args.tags) { contact.tags = args.tags.split(',').map(t => t.trim().toLowerCase()); changes.push(`tags replaced`); }
            if (args.add_tags) {
                const newTags = args.add_tags.split(',').map(t => t.trim().toLowerCase());
                contact.tags = [...new Set([...(contact.tags || []), ...newTags])];
                changes.push(`tags added: ${newTags.join(', ')}`);
            }
            if (args.notes) {
                if (!contact.notes) contact.notes = [];
                contact.notes.push({ date: new Date().toISOString(), text: args.notes });
                changes.push('note appended');
            }

            contact.updated = new Date().toISOString();
            contacts[idx] = contact;
            await saveCRM(contacts);

            return {
                display: `✏️ **Updated:** ${contact.name} (${contact.stage})`,
                result: `Changes: ${changes.join(', ')}\n\nCurrent state:\n- Name: ${contact.name}\n- Email: ${contact.email}\n- Stage: ${contact.stage}\n- Tags: ${(contact.tags || []).join(', ') || 'none'}`
            };
        }

        case 'growth_crm_pipeline_view': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📊 Building pipeline view...');

            const contacts = await loadCRM();
            if (contacts.length === 0) {
                return { display: '📇 **CRM Empty**', result: 'No contacts yet.' };
            }

            const stages = ['lead', 'contacted', 'warm', 'hot', 'converted', 'lost'];
            const pipeline = {};
            stages.forEach(s => pipeline[s] = []);
            contacts.forEach(c => {
                const s = (c.stage || 'lead').toLowerCase();
                if (pipeline[s]) pipeline[s].push(c);
                else pipeline['lead'].push(c);
            });

            const stageIcons = { lead: '🔵', contacted: '📨', warm: '🟡', hot: '🔴', converted: '🟢', lost: '⚫' };

            let result = `📊 CRM PIPELINE — ${contacts.length} Total Contacts\n${'═'.repeat(45)}\n\n`;
            const funnelLines = [];

            for (const stage of stages) {
                const count = pipeline[stage].length;
                const bar = '█'.repeat(Math.min(count, 30));
                funnelLines.push(`${stageIcons[stage]} ${stage.toUpperCase().padEnd(12)} │ ${String(count).padStart(3)} │ ${bar}`);

                if (args.show_details && count > 0) {
                    pipeline[stage].forEach(c => {
                        funnelLines.push(`   └─ ${c.name} <${c.email}> ${c.company ? '@ ' + c.company : ''}`);
                    });
                }
            }

            result += funnelLines.join('\n');

            const conversionRate = pipeline['converted'].length > 0
                ? ((pipeline['converted'].length / contacts.length) * 100).toFixed(1)
                : '0.0';
            result += `\n\n📈 Conversion Rate: ${conversionRate}% (${pipeline['converted'].length}/${contacts.length})`;

            return { display: `📊 **Pipeline:** ${contacts.length} contacts across ${stages.length} stages`, result };
        }

        case 'growth_crm_export': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📥 Exporting CRM to CSV...');

            let contacts = await loadCRM();

            if (args.stage_filter) contacts = contacts.filter(c => c.stage === args.stage_filter.toLowerCase());
            if (args.tag_filter) {
                const tag = args.tag_filter.toLowerCase();
                contacts = contacts.filter(c => (c.tags || []).includes(tag));
            }

            if (contacts.length === 0) {
                return { display: '📇 **Nothing to export**', result: 'No contacts match your filters.' };
            }

            const headers = ['Name', 'Email', 'Company', 'Phone', 'URL', 'Source', 'Stage', 'Tags', 'Notes', 'Created', 'Updated'];
            const rows = contacts.map(c => [
                csvEscape(c.name), csvEscape(c.email), csvEscape(c.company), csvEscape(c.phone),
                csvEscape(c.url), csvEscape(c.source), csvEscape(c.stage),
                csvEscape((c.tags || []).join('; ')),
                csvEscape((c.notes || []).map(n => `[${n.date?.substring(0, 10)}] ${n.text}`).join(' | ')),
                csvEscape(c.created?.substring(0, 10)), csvEscape(c.updated?.substring(0, 10))
            ].join(','));

            const csv = [headers.join(','), ...rows].join('\n');
            const finalFileName = `Pidgey_CRM_Export_${new Date().toISOString().substring(0, 10)}.csv`;
            const stashKey = `_file_${finalFileName.toLowerCase()}`;

            return new Promise((resolve) => {
                chrome.storage.local.set({ [stashKey]: '\ufeff' + csv }).then(() => {
                    playAudioAlert('chirp');
                    resolve({
                        display: `🎒 **CRM Packed!** ${contacts.length} contacts saved as CSV to your Backpack.`,
                        result: `Exported ${contacts.length} contacts securely into the Backpack as ${finalFileName}.`
                    });
                }).catch(err => {
                    resolve({ display: `❌ **Export failed**`, result: err.message });
                });
            });
        }

        // ===================== MAILING LIST TOOLS =====================

        case 'growth_mailing_list_add': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📬 Adding to mailing list...');

            const lists = await loadMailingLists();
            const listName = (args.list_name || 'main').toLowerCase().trim();
            const email = (args.email || '').toLowerCase().trim();

            if (!email || !email.includes('@')) {
                return { display: '❌ **Invalid email**', result: 'Please provide a valid email address.' };
            }

            if (!lists[listName]) lists[listName] = [];

            const existing = lists[listName].find(s => s.email === email);
            if (existing) {
                return {
                    display: `⚠️ **Already subscribed:** ${email} on "${listName}"`,
                    result: `${email} is already on the "${listName}" list (added ${existing.added?.substring(0, 10) || '?'}).`
                };
            }

            lists[listName].push({
                email,
                name: args.name || '',
                tags: args.tags ? args.tags.split(',').map(t => t.trim().toLowerCase()) : [],
                added: new Date().toISOString()
            });

            await saveMailingLists(lists);
            playAudioAlert('chirp');

            const totalOnList = lists[listName].length;
            return {
                display: `📬 **Added to "${listName}":** ${email}`,
                result: `${args.name || email} added to mailing list "${listName}". Total subscribers on this list: ${totalOnList}`
            };
        }

        case 'growth_mailing_list_view': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📬 Loading mailing lists...');

            const lists = await loadMailingLists();
            const listNames = Object.keys(lists);

            if (listNames.length === 0) {
                return { display: '📬 **No Mailing Lists**', result: 'No mailing lists created yet. Use growth_mailing_list_add to start building a list.' };
            }

            if (args.list_name) {
                const listName = args.list_name.toLowerCase().trim();
                const subscribers = lists[listName];
                if (!subscribers || subscribers.length === 0) {
                    return { display: `📬 **"${listName}" is empty**`, result: `No subscribers on this list.` };
                }
                const lines = subscribers.map((s, i) =>
                    `${i + 1}. **${s.name || '(no name)'}** <${s.email}> ${s.tags?.length ? `[${s.tags.join(', ')}]` : ''} — added ${s.added?.substring(0, 10) || '?'}`
                );
                return {
                    display: `📬 **"${listName}"** — ${subscribers.length} subscribers`,
                    result: `Mailing List: ${listName} (${subscribers.length} subscribers)\n\n${lines.join('\n')}`
                };
            }

            const summary = listNames.map(name =>
                `📋 **${name}** — ${lists[name].length} subscriber(s)`
            );
            const total = listNames.reduce((sum, n) => sum + lists[n].length, 0);

            return {
                display: `📬 **${listNames.length} Mailing List(s)** — ${total} total subscribers`,
                result: `Mailing Lists Overview:\n\n${summary.join('\n')}\n\nUse growth_mailing_list_view with list_name to see subscribers.`
            };
        }

        case 'growth_mailing_list_remove': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📬 Removing from list...');

            const lists = await loadMailingLists();
            const listName = (args.list_name || 'main').toLowerCase().trim();
            const email = (args.email || '').toLowerCase().trim();

            if (!lists[listName]) {
                return { display: `❌ **List not found:** "${listName}"`, result: `No mailing list named "${listName}".` };
            }

            const before = lists[listName].length;
            lists[listName] = lists[listName].filter(s => s.email !== email);
            const removed = before - lists[listName].length;

            if (removed === 0) {
                return { display: `⚠️ **Not found:** ${email}`, result: `${email} was not on the "${listName}" list.` };
            }

            await saveMailingLists(lists);
            return {
                display: `📬 **Removed:** ${email} from "${listName}"`,
                result: `Unsubscribed ${email} from "${listName}". Remaining: ${lists[listName].length}`
            };
        }

        case 'growth_mailing_list_export': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📥 Exporting mailing list...');

            const lists = await loadMailingLists();
            const listName = (args.list_name || 'main').toLowerCase().trim();
            const subscribers = lists[listName];

            if (!subscribers || subscribers.length === 0) {
                return { display: `📬 **Nothing to export**`, result: `"${listName}" list is empty or doesn't exist.` };
            }

            const headers = ['Email Address', 'First Name', 'Last Name', 'Tags'];
            const rows = subscribers.map(s => {
                const parts = (s.name || '').split(' ');
                const firstName = parts[0] || '';
                const lastName = parts.slice(1).join(' ') || '';
                return [csvEscape(s.email), csvEscape(firstName), csvEscape(lastName), csvEscape((s.tags || []).join('; '))].join(',');
            });

            const csv = [headers.join(','), ...rows].join('\n');
            const finalFileName = `Pidgey_MailingList_${listName}_${new Date().toISOString().substring(0, 10)}.csv`;
            const stashKey = `_file_${finalFileName.toLowerCase()}`;

            return new Promise((resolve) => {
                chrome.storage.local.set({ [stashKey]: '\ufeff' + csv }).then(() => {
                    playAudioAlert('chirp');
                    resolve({
                        display: `🎒 **Mailing List Packed!** "${listName}" — ${subscribers.length} subscribers stored in your Backpack.`,
                        result: `Exported ${subscribers.length} subscribers securely into the Backpack as ${finalFileName}.`
                    });
                }).catch(err => {
                    resolve({ display: `❌ **Export failed**`, result: err.message });
                });
            });
        }

        case 'growth_mailing_list_import_from_crm': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('📬 Importing CRM contacts to mailing list...');

            let contacts = await loadCRM();
            const lists = await loadMailingLists();
            const listName = (args.list_name || 'main').toLowerCase().trim();

            if (args.stage_filter) contacts = contacts.filter(c => c.stage === args.stage_filter.toLowerCase());
            if (args.tag_filter) {
                const tag = args.tag_filter.toLowerCase();
                contacts = contacts.filter(c => (c.tags || []).includes(tag));
            }
            if (args.source_filter) contacts = contacts.filter(c => c.source === args.source_filter.toLowerCase());

            if (contacts.length === 0) {
                return { display: '📬 **No matching contacts**', result: 'No CRM contacts match your filters.' };
            }

            if (!lists[listName]) lists[listName] = [];
            const existingEmails = new Set(lists[listName].map(s => s.email));
            let added = 0;

            for (const c of contacts) {
                if (!existingEmails.has(c.email)) {
                    lists[listName].push({
                        email: c.email,
                        name: c.name,
                        tags: c.tags || [],
                        added: new Date().toISOString()
                    });
                    existingEmails.add(c.email);
                    added++;
                }
            }

            await saveMailingLists(lists);
            playAudioAlert('chirp');

            return {
                display: `📬 **Imported ${added} contacts** to "${listName}"`,
                result: `Imported ${added} new contacts from CRM (${contacts.length - added} were already on the list).\n"${listName}" now has ${lists[listName].length} total subscribers.`
            };
        }

        // ===================== SEO & CONTENT TOOLS =====================

        case 'growth_seo_page_audit': {
            setStatus('🔍 Running SEO audit...');
            let htmlContent = '';
            let auditUrl = args.url || '';

            if (auditUrl) {
                try {
                    const res = await fetch(auditUrl);
                    htmlContent = await res.text();
                } catch (err) {
                    return { display: `❌ **Failed to fetch page**`, result: `Error: ${err.message}` };
                }
            } else {
                try {
                    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
                    auditUrl = tab.url;
                    const result = await chrome.scripting.executeScript({
                        target: { tabId: tab.id },
                        func: () => document.documentElement.outerHTML
                    });
                    htmlContent = result[0]?.result || '';
                } catch (err) {
                    return { display: `❌ **Cannot read page**`, result: `Error accessing tab: ${err.message}` };
                }
            }

            const getTag = (tag) => { const m = htmlContent.match(new RegExp(`<${tag}[^>]*>(.*?)</${tag}>`, 'is')); return m ? m[1].trim() : null; };
            const getMeta = (name) => { const m = htmlContent.match(new RegExp(`<meta[^>]*(?:name|property)=["']${name}["'][^>]*content=["']([^"']*)["']`, 'i')); return m ? m[1] : null; };
            const countTag = (tag) => (htmlContent.match(new RegExp(`<${tag}[\\s>]`, 'gi')) || []).length;

            const title = getTag('title') || '(missing)';
            const metaDesc = getMeta('description') || '(missing)';
            const ogTitle = getMeta('og:title');
            const ogDesc = getMeta('og:description');
            const ogImage = getMeta('og:image');
            const canonical = (htmlContent.match(/<link[^>]*rel=["']canonical["'][^>]*href=["']([^"']*)["']/i) || [])[1];
            const h1Count = countTag('h1');
            const h2Count = countTag('h2');
            const h3Count = countTag('h3');
            const imgCount = countTag('img');
            const imgNoAlt = (htmlContent.match(/<img(?![^>]*alt=["'][^"']+["'])[^>]*>/gi) || []).length;
            const internalLinks = (htmlContent.match(/href=["']\/[^"']*/gi) || []).length;
            const externalLinks = (htmlContent.match(/href=["']https?:\/\/[^"']*/gi) || []).length;

            const issues = [];
            if (title === '(missing)') issues.push('CRITICAL: No <title> tag');
            else if (title.length < 30) issues.push(`WARNING: Title too short (${title.length} chars, aim for 50-60)`);
            else if (title.length > 65) issues.push(`WARNING: Title too long (${title.length} chars, aim for 50-60)`);
            if (metaDesc === '(missing)') issues.push('CRITICAL: No meta description');
            else if (metaDesc.length < 120) issues.push(`WARNING: Meta description short (${metaDesc.length} chars, aim for 150-160)`);
            else if (metaDesc.length > 165) issues.push(`WARNING: Meta description too long (${metaDesc.length} chars)`);
            if (h1Count === 0) issues.push('CRITICAL: No H1 tag found');
            if (h1Count > 1) issues.push(`WARNING: Multiple H1 tags (${h1Count}). Use only one.`);
            if (!ogTitle) issues.push('WARNING: Missing og:title (social sharing)');
            if (!ogImage) issues.push('WARNING: Missing og:image (social sharing preview)');
            if (!canonical) issues.push('INFO: No canonical URL set');
            if (imgNoAlt > 0) issues.push(`WARNING: ${imgNoAlt} image(s) missing alt text`);

            const score = Math.max(0, 100 - (issues.filter(i => i.startsWith('CRITICAL')).length * 20) - (issues.filter(i => i.startsWith('WARNING')).length * 8) - (issues.filter(i => i.startsWith('INFO')).length * 2));

            const result = [
                `🔍 SEO AUDIT: ${auditUrl}`,
                `${'═'.repeat(50)}`,
                `Score: ${score}/100 ${score >= 80 ? '🟢' : score >= 50 ? '🟡' : '🔴'}`,
                ``,
                `--- PAGE META ---`,
                `Title: ${title} (${title.length} chars)`,
                `Meta Desc: ${metaDesc.substring(0, 80)}${metaDesc.length > 80 ? '...' : ''} (${metaDesc.length} chars)`,
                `Canonical: ${canonical || 'not set'}`,
                ``,
                `--- OPEN GRAPH ---`,
                `og:title: ${ogTitle || 'missing'}`,
                `og:description: ${ogDesc || 'missing'}`,
                `og:image: ${ogImage || 'missing'}`,
                ``,
                `--- STRUCTURE ---`,
                `H1: ${h1Count} | H2: ${h2Count} | H3: ${h3Count}`,
                `Images: ${imgCount} total, ${imgNoAlt} missing alt text`,
                `Links: ${internalLinks} internal, ${externalLinks} external`,
                ``,
                issues.length > 0 ? `--- ISSUES (${issues.length}) ---\n${issues.map(i => `• ${i}`).join('\n')}` : '✅ No major issues detected!',
            ].join('\n');

            return { display: `🔍 **SEO Score: ${score}/100** — ${auditUrl}`, result };
        }

        case 'growth_seo_keyword_research': {
            setStatus(`🔑 Researching keywords for "${args.seed_keyword}"...`);
            if (!config.tavilyKey) {
                return {
                    display: `🔑 **Tavily Search Locked**`,
                    result: `Chirp! I need a Tavily API key for keyword research.\n\nFree alternatives:\n- Google Keyword Planner (free with Google Ads account)\n- Ubersuggest (limited free)\n- AnswerThePublic.com for question-based keywords\n- AlsoAsked.com for PAA data`
                };
            }
            try {
                const niche = args.niche ? ` ${args.niche}` : '';
                const queries = [
                    `${args.seed_keyword}${niche} related keywords long tail SEO 2025 2026`,
                    `"people also ask" ${args.seed_keyword}${niche}`
                ];
                const results = await Promise.all(queries.map(q =>
                    fetch('https://api.tavily.com/search', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ api_key: config.tavilyKey, query: q, search_depth: 'advanced', include_answer: true, max_results: 8 })
                    }).then(r => r.json())
                ));

                const combined = results.map(r => r.answer || '').join('\n\n');
                const sources = results.flatMap(r => (r.results || []).slice(0, 4)).map(r => `[${r.title}](${r.url})`).join('\n');

                playAudioAlert('chirp');
                return {
                    display: `🔑 **Keyword Research:** "${args.seed_keyword}"`,
                    result: `🔑 KEYWORD RESEARCH: "${args.seed_keyword}"\n\n${combined}\n\nSources:\n${sources}`.substring(0, 10000)
                };
            } catch (err) {
                return { display: `❌ **Research failed**`, result: `Error: ${err.message}` };
            }
        }

        case 'growth_auto_vet_inquiry': {
            setStatus('🧠 Auto-Vetting Inquiry...');
            return {
                display: `🤖 **Auto-Vetted Inquiry**`,
                result: `INQUIRY RECEIVED:\n"${args.inquiry}"\n\nINSTRUCTIONS FOR PIDGEY:\nAct as an elite SDR Bot. Analyze the provided inquiry. Score it from 1-100 based on lead quality, urgency, and purchasing intent. Then, draft a personalized email reply that addresses their points, offers value, and moves them to the next stage in the pipeline. Output format:\n\n1. Lead Score: [score]/100\n2. Reasoning: [Brief explanation]\n3. Recommended Draft Reply:\n[Your Draft]`
            };
        }

        case 'growth_chirp_crm_sync': {
            const block = phoenixCheck();
            if (block) return block;
            setStatus('🔄 Syncing Tracked Chirp to CRM...');
            
            const trackingId = Date.now().toString(36) + Math.random().toString(36).substring(2, 7);
            const openPixel = `<img src="https://api.pidgeypost.io/track/open?chirpId=${trackingId}" width="1" height="1" style="display:none;" alt="" />`;
            const clickLink = `https://api.pidgeypost.io/track/click?chirpId=${trackingId}&url=${encodeURIComponent(args.url || 'https://pidgeyassist.com/')}`;
            
            return {
                display: `🔄 **Tracked Chirp Synced** (ID: ${trackingId})`,
                result: `Tracking and CRM Sync Complete for Chirp ID: ${trackingId}\n\n1. Append this tracking pixel to the bottom of the email HTML:\n\`\`\`html\n${openPixel}\n\`\`\`\n\n2. Wrap CTA links with this click-tracking URL format:\n${clickLink}\n\nLead interaction has been securely staged for 1-click CRM sync.`
            };
        }

        case 'growth_content_generator': {
            setStatus(`✍️ Generating ${args.content_type}...`);
            const type = args.content_type || 'blog_outline';
            const tone = args.tone || 'casual';
            const platform = args.platform || '';
            const keywords = args.keywords || '';

            const templates = {
                blog_outline: `Create a detailed blog post outline about "${args.topic}".\nTone: ${tone}\n${keywords ? `Include keywords: ${keywords}` : ''}\n\nFormat:\n- Compelling title (3 options)\n- Meta description (155 chars)\n- H2 sections with bullet points for key content\n- Intro hook\n- Conclusion with CTA\n- Suggested internal/external links`,

                social_caption: `Write 5 social media caption variations for ${platform || 'multiple platforms'} about "${args.topic}".\nTone: ${tone}\n${keywords ? `Include: ${keywords}` : ''}\n\nFor each:\n- The caption text\n- Suggested hashtags\n- Best posting time suggestion\n- Engagement hook (question, poll, or CTA)`,

                ad_copy: `Write ad copy variations for "${args.topic}".\nTone: ${tone}\nTarget: ${platform || 'general'}\n\nProvide:\n- 3 headline options (max 30 chars each)\n- 3 description options (max 90 chars each)\n- Primary CTA\n- Emotional hook angle`,

                email_subject_lines: `Generate 10 email subject lines for "${args.topic}".\nTone: ${tone}\n\nMix of:\n- Curiosity-driven\n- Urgency/scarcity\n- Question-based\n- Number/stat-based\n- Personalized (use [Name])`,

                headlines_ab: `Create 10 A/B test headline variations for "${args.topic}".\nTone: ${tone}\n\nInclude:\n- Control (standard)\n- Emotional variant\n- Question variant\n- Number/stat variant\n- Curiosity gap variant\n- Social proof variant\n\nFor each, explain the psychological trigger.`,

                landing_page_copy: `Write landing page copy for "${args.topic}".\nTone: ${tone}\n${keywords ? `SEO keywords: ${keywords}` : ''}\n\nInclude:\n- Hero headline + subheadline\n- 3 feature blocks with icons\n- Social proof section\n- FAQ (5 questions)\n- Final CTA with urgency`,

                press_release_outline: `Create a press release outline for "${args.topic}".\nTone: professional\n\nFormat:\n- Headline\n- Subheadline\n- Dateline + lead paragraph (who/what/when/where/why)\n- Body paragraphs\n- Quote from founder\n- Boilerplate\n- Contact info placeholder`
            };

            const prompt = templates[type] || templates['blog_outline'];

            return {
                display: `✍️ **Content Brief Generated:** ${type.replace(/_/g, ' ')}`,
                result: `Here is the creative brief template for: ${type}\nTopic: ${args.topic}\nTone: ${tone}\n${platform ? `Platform: ${platform}\n` : ''}${keywords ? `Keywords: ${keywords}\n` : ''}\n\nINSTRUCTIONS FOR YOU (PIDGEY):\nYou must now act as the copywriter. Use the template below to generate the actual final copy for the user. Do NOT explain what you are doing. Do NOT apologize. Just immediately output the requested content based on this outline:\n\n${prompt}`
            };
        }

        case 'growth_utm_link_builder': {
            setStatus('🔗 Building UTM link...');
            const params = new URLSearchParams();
            params.set('utm_source', args.source);
            params.set('utm_medium', args.medium);
            params.set('utm_campaign', args.campaign);
            if (args.term) params.set('utm_term', args.term);
            if (args.content) params.set('utm_content', args.content);

            const separator = args.base_url.includes('?') ? '&' : '?';
            const fullUrl = `${args.base_url}${separator}${params.toString()}`;

            const result = [
                `🔗 UTM LINK BUILDER`,
                ``,
                `Base URL: ${args.base_url}`,
                `Source: ${args.source}`,
                `Medium: ${args.medium}`,
                `Campaign: ${args.campaign}`,
                args.term ? `Term: ${args.term}` : null,
                args.content ? `Content: ${args.content}` : null,
                ``,
                `📋 FULL TRACKED URL:`,
                fullUrl,
                ``,
                `Paste this link into your ${args.medium} channel to track ${args.campaign} performance in Google Analytics.`
            ].filter(Boolean).join('\n');

            return { display: `🔗 **UTM Link Ready** (${args.source}/${args.campaign})`, result };
        }

        case 'growth_trending_topics': {
            setStatus(`📈 Scanning trending topics in ${args.niche}...`);
            if (!config.tavilyKey) {
                return {
                    display: `🔑 **Tavily Search Locked**`,
                    result: `Chirp! I need a Tavily API key for trend scanning.\n\nManual alternatives:\n- Reddit.com/r/popular + search your niche\n- trends.google.com\n- news.ycombinator.com (Hacker News)\n- producthunt.com/topics`
                };
            }
            try {
                const platforms = (args.platforms || 'reddit,twitter,hackernews,producthunt').split(',').map(p => p.trim());
                const domainMap = {
                    reddit: 'reddit.com', twitter: 'twitter.com', hackernews: 'news.ycombinator.com', producthunt: 'producthunt.com'
                };
                const domains = platforms.map(p => domainMap[p]).filter(Boolean);
                const query = `${args.niche} trending new launch discussion 2025 2026`;

                const res = await fetch('https://api.tavily.com/search', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        api_key: config.tavilyKey, query, search_depth: 'advanced',
                        include_answer: true, max_results: 10,
                        include_domains: domains
                    })
                });
                const data = await res.json();
                playAudioAlert('chirp');

                const topicList = (data.results || []).slice(0, 10).map((r, i) =>
                    `${i + 1}. [${r.title}](${r.url})\n   ${r.content?.substring(0, 150)}...`
                ).join('\n\n');

                return {
                    display: `📈 **Trending in "${args.niche}"** — ${(data.results || []).length} topics found`,
                    result: `📈 TRENDING TOPICS: "${args.niche}"\n\n${data.answer || ''}\n\n${topicList}`.substring(0, 10000)
                };
            } catch (err) {
                return { display: `❌ **Trend scan failed**`, result: `Error: ${err.message}` };
            }
        }
    }
}
