// sp-tools-trader.js
export async function executeTraderTool(name, args, _ui, _state) {
    const { setStatus, addBotMessage, playAudioAlert } = _ui;
    const { config } = _state;
    switch (name) {
        case 'fetch_dex_data': {
            setStatus(`🪙 Fetching DEX data for: ${args.token}...`);
            try {
                const res = await fetch(`https://api.dexscreener.com/latest/dex/search?q=${encodeURIComponent(args.token)}`);
                const data = await res.json();
                const pairs = (data?.pairs || []).filter(p => !args.chain || p.chainId === args.chain).slice(0, 3);
                if (!pairs.length) return { display: `🪙 **No DEX data found:** ${args.token}`, result: `No pairs found on DexScreener for "${args.token}"` };
                const summary = pairs.map(p =>
                    `${p.baseToken.name} (${p.baseToken.symbol}) on ${p.chainId.toUpperCase()}\nPrice: ${p.priceUsd} | MC: ${p.fdv ? p.fdv.toLocaleString() : 'N/A'} | 24h Vol: ${(p.volume?.h24 || 0).toLocaleString()}\nLiq: ${(p.liquidity?.usd || 0).toLocaleString()} | 24h: ${p.priceChange?.h24 || 0}% | DEX: ${p.dexId}\nCA: ${p.baseToken.address}\nURL: ${p.url}`
                ).join('\n\n---\n');
                playAudioAlert('chirp');
                return { display: `🪙 **DEX Data:** ${args.token}`, result: summary };
            } catch (err) {
                return { display: `❌ **DEX data failed**`, result: err.message };
            }
        }

        case 'trending_tokens': {
            setStatus(`🔥 Fetching trending tokens${args.chain ? ` on ${args.chain}` : ''}...`);
            try {
                const res = await fetch('https://api.dexscreener.com/token-boosts/top/v1');
                const data = await res.json();
                const tokens = (Array.isArray(data) ? data : []).filter(t => !args.chain || t.chainId === args.chain).slice(0, 10);
                if (!tokens.length) return { display: `🔥 **No trending tokens found**`, result: `No trending tokens found.` };
                const summary = tokens.map((t, i) => `${i + 1}. ${t.description || t.tokenAddress} on ${t.chainId?.toUpperCase()}\n   Boosts: ${t.totalAmount || 'N/A'} | URL: ${t.url || 'N/A'}`).join('\n');
                return { display: `🔥 **Trending Tokens${args.chain ? ` on ${args.chain.toUpperCase()}` : ''}**`, result: summary };
            } catch (err) {
                return { display: `❌ **Trending tokens failed**`, result: err.message };
            }
        }

        case 'fetch_gas_fees': {
            setStatus('⛽ Fetching gas fees...');
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const chains = args.chains?.length ? args.chains.join(', ') : 'ethereum, base, arbitrum, solana';
                const res = await fetch('https://api.tavily.com/search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: config.tavilyKey, query: `current gas fees ${chains} gwei USD 2026`, search_depth: 'basic', include_answer: true }) });
                const data = await res.json();
                return { display: `⛽ **Gas Fees:** ${chains}`, result: `${data.answer || 'No answer'}\n\n${(data.results || []).slice(0, 3).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 6000) };
            } catch (err) {
                return { display: `❌ **Gas fees failed**`, result: err.message };
            }
        }

        case 'scan_contract': {
            setStatus(`🔍 Contract scan: ${args.address.slice(0, 12)}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `${args.address} ${args.chain || 'crypto'} contract audit honeypot rugpull LP lock holders`;
                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 }) });
                const data = await res.json();
                return { display: `🔍 **Contract Scan:** ${args.address.slice(0, 10)}...`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Contract scan failed**`, result: err.message };
            }
        }

        case 'scan_wallet': {
            setStatus(`👛 Wallet scan: ${args.address.slice(0, 12)}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `${args.address} wallet PnL smart money insider ${args.chain || 'crypto'} analysis`;
                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 }) });
                const data = await res.json();
                return { display: `👛 **Wallet Scan:** ${args.address.slice(0, 10)}...`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Wallet scan failed**`, result: err.message };
            }
        }

        case 'check_honeypot': {
            setStatus(`🍯 Honeypot check: ${args.address.slice(0, 12)}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `${args.address} honeypot check ${args.chain || ''} can you sell token rug`;
                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: 'basic', include_answer: true }) });
                const data = await res.json();
                return { display: `🍯 **Honeypot Check:** ${args.address.slice(0, 10)}...`, result: `${data.answer || 'No direct verdict found. Investigate manually on honeypot.is'}\n\n${(data.results || []).slice(0, 3).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 6000) };
            } catch (err) {
                return { display: `❌ **Honeypot check failed**`, result: err.message };
            }
        }

        case 'pump_fun_scan': {
            setStatus(`🎰 pump.fun scan: ${args.address}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `pump.fun ${args.address} bonding curve graduation top holders analysis`;
                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 }) });
                const data = await res.json();
                return { display: `🎰 **Pump.fun Scan:** ${args.address.slice(0, 12)}...`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Pump.fun scan failed**`, result: err.message };
            }
        }

        case 'track_whale_moves': {
            setStatus(`🐋 Whale tracking: ${args.token}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const minUsd = args.min_usd || 10000;
                const query = `${args.token} whale moves large transactions ${args.chain || 'crypto'} accumulation distribution ${minUsd}+ USD`;
                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 }) });
                const data = await res.json();
                return { display: `🐋 **Whale Moves:** ${args.token}`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Whale tracking failed**`, result: err.message };
            }
        }

        case 'defi_protocol_scan': {
            setStatus(`🔗 DeFi scan: ${args.protocol}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `${args.protocol} DeFi TVL APY audit risk exploit history DefiLlama 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 }) });
                const data = await res.json();
                return { display: `🔗 **DeFi Protocol:** ${args.protocol}`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **DeFi scan failed**`, result: err.message };
            }
        }

        case 'nft_collection_scan': {
            setStatus(`🖼️ NFT scan: ${args.collection}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `${args.collection} NFT floor price volume holders ${args.marketplace || 'opensea blur magic eden'} 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 }) });
                const data = await res.json();
                return { display: `🖼️ **NFT Collection:** ${args.collection}`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **NFT scan failed**`, result: err.message };
            }
        }

        case 'smart_money_tracker': {
            setStatus(`🧠 Smart money tracker${args.chain ? ` on ${args.chain}` : ''}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const tf = args.timeframe || '24h';
                const query = `smart money wallets buying ${args.chain || 'crypto'} ${tf} alpha wallets accumulation insider buys 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 }) });
                const data = await res.json();
                return { display: `🧠 **Smart Money Moves** (${tf})`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Smart money tracker failed**`, result: err.message };
            }
        }

        case 'crypto_news_sentiment': {
            setStatus(`📰 Crypto sentiment: ${args.query}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `${args.query} crypto twitter CT sentiment news FUD hype latest 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: 'basic', include_answer: true }) });
                const data = await res.json();
                return { display: `📰 **Crypto Sentiment:** ${args.query}`, result: `${data.answer || 'No direct answer.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Sentiment failed**`, result: err.message };
            }
        }

        case 'portfolio_pnl': {
            setStatus(`📊 Portfolio PnL: ${args.wallet.slice(0, 12)}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const query = `${args.wallet} wallet portfolio PnL ${args.chain || 'all chains'} realized unrealized gains zapper debank`;
                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 }) });
                const data = await res.json();
                return { display: `📊 **Portfolio PnL:** ${args.wallet.slice(0, 10)}...`, result: `${data.answer || 'No direct answer. Try Zapper.fi or DeBank for wallet PnL.'}\n\n${(data.results || []).slice(0, 3).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Portfolio PnL failed**`, result: err.message };
            }
        }

        case 'economic_calendar': {
            setStatus('📅 Fetching economic calendar...');
            if (!config.tavilyKey) {
                // Fallback: use public investing.com data without key
                return { display: `📅 **Economic Calendar** (no Tavily key)`, result: `⚠️ Add a Tavily key in Settings for live calendar data.\n\nUpcoming high-impact events to watch:\n- **FOMC Meeting** — watch fed funds rate decision\n- **CPI (Consumer Price Index)** — inflation print\n- **PPI (Producer Price Index)** — wholesale inflation\n- **NFP (Non-Farm Payrolls)** — jobs report (1st Friday of month)\n- **GDP** — quarterly growth print\n\nCheck investing.com/economic-calendar for exact dates.` };
            }
            try {
                const daysAhead = args.days_ahead || 7;
                const filter = args.filter || 'high-impact';
                const query = `economic calendar ${filter} events next ${daysAhead} days FOMC CPI PPI NFP GDP earnings dates 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, include_domains: ['investing.com', 'forexfactory.com', 'marketwatch.com', 'federalreserve.gov', 'bls.gov'] }) });
                const data = await res.json();
                if (data.error) throw new Error(data.error);
                const resultsText = (data.results || []).slice(0, 5).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n');
                return { display: `📅 **Economic Calendar** — next ${daysAhead} days`, result: `${data.answer || 'See results below.'}\n\n${resultsText}`.substring(0, 10000) };
            } catch (err) {
                return { display: `❌ **Calendar fetch failed**`, result: `Error: ${err.message}` };
            }
        }

        case 'fetch_stock_data': {
            setStatus(`📈 Fetching data for ${args.symbol}...`);
            try {
                // Yahoo Finance unofficial quote endpoint
                const res = await fetch(`https://query1.finance.yahoo.com/v8/finance/chart/${encodeURIComponent(args.symbol)}?interval=1d&range=5d`);
                const data = await res.json();
                const meta = data?.chart?.result?.[0]?.meta;
                if (!meta) throw new Error('No data returned');
                const price = meta.regularMarketPrice;
                const prev = meta.chartPreviousClose || meta.previousClose;
                const change = prev ? ((price - prev) / prev * 100).toFixed(2) : 'N/A';
                playAudioAlert('chirp');
                return { display: `📈 **${args.symbol}:** ${price}`, result: `Symbol: ${args.symbol}\nPrice: ${price}\nChange: ${change}%\n52W High: ${meta.fiftyTwoWeekHigh || 'N/A'}\n52W Low: ${meta.fiftyTwoWeekLow || 'N/A'}\nVolume: ${(meta.regularMarketVolume || 0).toLocaleString()}\nExchange: ${meta.exchangeName || 'N/A'}` };
            } catch (err) {
                return { display: `❌ **${args.symbol} data failed**`, result: `Could not fetch ${args.symbol}: ${err.message}` };
            }
        }

        case 'fetch_metal_prices': {
            setStatus('🥇 Fetching metal spot prices...');
            try {
                const metals = (args.metals?.length ? args.metals : ['gold', 'silver', 'platinum', 'copper']);
                const symbolMap = { gold: 'GC=F', silver: 'SI=F', platinum: 'PL=F', palladium: 'PA=F', copper: 'HG=F' };
                const results = await Promise.all(metals.map(async m => {
                    const sym = symbolMap[m.toLowerCase()];
                    if (!sym) return `${m}: unknown symbol`;
                    try {
                        const r = await fetch(`https://query1.finance.yahoo.com/v8/finance/chart/${sym}?interval=1d&range=2d`);
                        const d = await r.json();
                        const meta = d?.chart?.result?.[0]?.meta;
                        const price = meta?.regularMarketPrice;
                        const prev = meta?.chartPreviousClose;
                        const chg = prev ? ((price - prev) / prev * 100).toFixed(2) : 'N/A';
                        return `${m.toUpperCase()}: ${price} (${chg}%)`;
                    } catch { return `${m}: unavailable`; }
                }));
                // Gold/Silver Ratio
                const goldLine = results.find(r => r.startsWith('GOLD'));
                const silverLine = results.find(r => r.startsWith('SILVER'));
                let gsr = '';
                if (goldLine && silverLine) {
                    const gp = parseFloat(goldLine.match(/\$(\d+\.?\d*)/)?.[1]);
                    const sp = parseFloat(silverLine.match(/\$(\d+\.?\d*)/)?.[1]);
                    if (gp && sp) gsr = `\nGold/Silver Ratio (GSR): ${(gp / sp).toFixed(1)} — ${(gp / sp) > 80 ? 'Silver historically CHEAP vs gold' : 'Silver holding vs gold'}`;
                }
                playAudioAlert('chirp');
                return { display: `🥇 **Metal Spot Prices**`, result: results.join('\n') + gsr };
            } catch (err) {
                return { display: `❌ **Metal prices failed**`, result: err.message };
            }
        }

        case 'fetch_crypto_price': {
            setStatus(`🪙 Fetching crypto prices...`);
            try {
                const coins = (args.coins || ['bitcoin', 'solana']).map(c => c.toLowerCase().replace('btc', 'bitcoin').replace('sol', 'solana').replace('eth', 'ethereum'));
                const ids = coins.join(',');
                const res = await fetch(`https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd&include_24hr_change=true&include_market_cap=true&include_24hr_vol=true`);
                const data = await res.json();
                const lines = Object.entries(data).map(([id, d]) =>
                    `${id.toUpperCase()}: ${d.usd?.toLocaleString()} | 24h: ${d.usd_24h_change?.toFixed(2)}% | MCap: ${(d.usd_market_cap / 1e9)?.toFixed(1)}B | Vol: ${(d.usd_24h_vol / 1e6)?.toFixed(0)}M`
                );
                playAudioAlert('chirp');
                return { display: `🪙 **Crypto Prices**`, result: lines.join('\n') };
            } catch (err) {
                return { display: `❌ **Crypto prices failed**`, result: err.message };
            }
        }

        case 'analyze_chart': {
            if (!document.body.classList.contains('phoenix-mode')) {
                return {
                    display: `🔥 **Phoenix Upgrade Required**\n\nChirp! I'd love to analyze this chart for you, but you need the **Phoenix upgrade** to unlock my Eagle-Eye vision and visual pattern recognition!\n\n**Phoenix Tier Features:**\n- 📊 Advanced Chart Analysis\n- 🔬 Deep Research Mode\n- 🎒 Pidgey Backpack Storage\n- 🎨 Custom Image Gen\n\n*Click the **⬆️ Upgrade** button in the menu above to unlock everything!*`,
                    result: `⚠️ Chart analysis blocked - User does not have Phoenix Mode.`
                };
            }
            const hasPerm = await chrome.permissions.contains({ origins: ['<all_urls>'] });
            if (!hasPerm) {
                return {
                    display: `🔒 **Permission Required**\n\nChirp! To see and analyze your charts, I need you to go to **Settings** (Step 5) and check the box for **"Eagle-Eye Vision — Background Tab Research"**!`,
                    result: `Failed: User must enable Eagle-Eye Vision permission in Settings first.`
                };
            }
            setStatus('📊 Eagle-Eye chart analysis incoming...');
            return new Promise((resolve) => {
                chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
                    if (!tabs.length) {
                        resolve({ display: `❌ **Chart capture failed**`, result: `Screenshot failed: No active tab found.\n\n**Fix:** Click directly on your chart tab to make it active, then try again.` });
                        return;
                    }
                    const winId = tabs[0].windowId;
                    chrome.tabs.captureVisibleTab(winId, { format: 'jpeg', quality: 70 }, async (dataUrl) => {
                        if (chrome.runtime.lastError || !dataUrl) {
                            const errMsg = chrome.runtime.lastError?.message || 'No image data returned';
                            resolve({ display: `❌ **Chart capture failed**`, result: `Screenshot failed: ${errMsg}\n\n**Common Fixes:**\n1. Enable **"Background Tab Research"** in Settings.\n2. Click directly on your chart tab to make it active, then try again.` });
                        } else {
                            if (_ui.addToGallery) _ui.addToGallery(dataUrl, 'Chart Screenshot');
                            const assetStr = args.asset ? `for **${args.asset}**` : '';
                            const tfStr = args.timeframe ? `on the **${args.timeframe}** timeframe` : '';
                            
                            resolve({ 
                                display: `📊 **Expert Vision Active** — Analyzing ${assetStr} ${tfStr}...`, 
                                result: `[EXPERT VISION PROTOCOL ACTIVATED]
I have captured the high-resolution screenshot. 

Proceed with a professional technical analysis by looking at the pixels and extracting:
1. **Current Price & Trend:** Identify exact price and trend direction (Bullish/Bearish/Neutral).
2. **Key Levels:** Locate immediate Support/Resistance, horizontal S/R, and supply/demand zones.
3. **Indicators & Sentiment:** Look for RSI divergences, EMA/SMA crosses, or volume spikes.
4. **Pattern Matching:** Identify any formations (Flag, Head & Shoulders, SFP, Accumulation).
5. **Trade Setup:** Provide a suggested Entry, Stop Loss, and Take Profit based on the visual data.

**Report Format:** Use a structured breakdown with headers and concise points. Be surgical.`, 
                                imageData: dataUrl 
                            });
                        }
                    });
                });
            });
        }

        case 'ai_portfolio_analysis': {
            return {
                generate_html: `
                    <div style="background: linear-gradient(180deg, #0f172a 0%, #1e1b4b 100%); color: white; border-radius: 12px; padding: 16px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; box-shadow: 0 10px 25px rgba(0,0,0,0.5); border: 1px solid rgba(99, 102, 241, 0.3);">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                            <div style="display: flex; align-items: center; gap: 8px;">
                                <div style="background: #3b82f6; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; font-size: 14px;">🦅</div>
                                <span style="font-weight: 700; font-size: 14px; letter-spacing: 0.5px;">AI Position Analysis</span>
                            </div>
                            <span style="font-size: 11px; color: #94a3b8; background: rgba(255,255,255,0.1); padding: 4px 8px; border-radius: 12px;">Pidgey Trader</span>
                        </div>
                        
                        <div style="text-align: center; margin-bottom: 24px;">
                            <div style="font-size: 13px; color: #cbd5e1; margin-bottom: 4px;">Portfolio Valuation Est.</div>
                            <div style="font-size: 32px; font-weight: 800; letter-spacing: -1px; margin-bottom: 8px;">${args.estimated_value_usd ? '$' + args.estimated_value_usd.toLocaleString() : 'Analyzing...'}</div>
                            
                            <div style="display: inline-flex; align-items: center; gap: 6px; background: rgba(239, 68, 68, 0.2); color: #fca5a5; padding: 6px 12px; border-radius: 20px; font-size: 13px; font-weight: 600;">
                                <span>${args.pnl_percent || 'N/A'}%</span>
                                <span style="font-size: 11px; font-weight: 400; opacity: 0.8;">Open P&L</span>
                            </div>
                        </div>

                        <!-- Risk Bar -->
                        <div style="margin-bottom: 24px;">
                            <div style="display: flex; justify-content: space-between; font-size: 11px; color: #94a3b8; margin-bottom: 6px; text-transform: uppercase; font-weight: 700; letter-spacing: 0.5px;">
                                <span>Risk Profile</span>
                                <span style="color: #60a5fa;">${args.risk_rating || 'High / Aggressive'}</span>
                            </div>
                            <div style="height: 12px; background: rgba(0,0,0,0.5); border-radius: 6px; overflow: hidden; display: flex; box-shadow: inset 0 2px 4px rgba(0,0,0,0.5);">
                                <div style="width: ${args.conservative_percent || 0}%; background: #34d399;"></div>
                                <div style="width: ${args.moderate_percent || 0}%; background: #fbbf24;"></div>
                                <div style="width: ${args.aggressive_percent || 100}%; background: linear-gradient(90deg, #3b82f6, #8b5cf6);"></div>
                            </div>
                            <div style="display: flex; justify-content: space-between; font-size: 10px; color: #64748b; margin-top: 6px;">
                                <span>Stable (${args.conservative_percent || 0}%)</span>
                                <span>Aggressive (${args.aggressive_percent || 100}%)</span>
                            </div>
                        </div>

                        <!-- Restructure Advice Box -->
                        <div style="background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(59, 130, 246, 0.2); border-radius: 10px; padding: 14px;">
                            <div style="display: flex; align-items: center; gap: 6px; margin-bottom: 8px;">
                                <span style="font-size: 14px;">🧠</span>
                                <span style="font-size: 12px; font-weight: 700; color: #e2e8f0;">AI Restructuring Verdict</span>
                            </div>
                            <p style="font-size: 12px; color: #94a3b8; line-height: 1.5; margin: 0;">
                                ${args.restructure_advice || 'Your portfolio reflects a heavy growth approach which currently lacks defensive scaling. To achieve a balanced Sharpe ratio in current market conditions, consider rotating capital from high-beta assets into stable yield-bearing positions or increasing cash allocation.'}
                            </p>
                        </div>
                    </div>
                `,
                display: `📊 **Rendered AI Portfolio Analysis UI**`,
                result: `Successfully generated visual portfolio analysis for the user.`
            };
        }

        case 'risk_calculator': {
            const { account_size, risk_percent, entry_price, stop_price, target_price } = args;
            const riskDollars = account_size * (risk_percent / 100);
            const stopDistance = Math.abs(entry_price - stop_price);
            const positionSize = stopDistance > 0 ? (riskDollars / stopDistance) : 0;
            const shares = Math.floor(positionSize);
            let rrRatio = 'N/A', profitDollars = 'N/A';
            if (target_price) {
                const targetDistance = Math.abs(target_price - entry_price);
                const rr = targetDistance / stopDistance;
                rrRatio = rr.toFixed(2);
                profitDollars = `${(shares * targetDistance).toFixed(2)}`;
            }
            const warn = parseFloat(rrRatio) < 2 ? '\n⚠️ R:R below 2:1 — consider skipping this trade' : '';
            return { display: `🧮 **Risk Calculator**`, result: `Account: ${account_size.toLocaleString()}\nRisk: ${risk_percent}% = ${riskDollars.toFixed(2)}\nEntry: ${entry_price} | Stop: ${stop_price}\nStop Distance: ${stopDistance.toFixed(4)}\nPosition Size: ${shares} units\nMax Loss: ${riskDollars.toFixed(2)}${target_price ? `\nTarget: ${target_price}\nR:R Ratio: ${rrRatio}:1\nProfit if hit: ${profitDollars}` : ''}${warn}` };
        }

        case 'ticker_sentiment':
        case 'sector_rotation':
        case 'dxy_correlation':
        case 'btc_dominance':
        case 'onchain_metrics':
        case 'analyze_dex_chart': {
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            setStatus(`🔍 Fetching ${name.replace(/_/g, ' ')}...`);
            try {
                const queryMap = {
                    ticker_sentiment: `${args.symbol} stock sentiment Reddit WSB analyst rating bull bear 2026`,
                    sector_rotation: `sector rotation market ${args.period || 'today'} leading lagging ETF flows SPY QQQ XLE XLF XLK 2026`,
                    dxy_correlation: `DXY US dollar index ${(args.assets || []).join(' ')} correlation analysis 2026`,
                    btc_dominance: `bitcoin dominance BTC.D altcoin season chart current 2026`,
                    onchain_metrics: `${args.asset} on-chain ${(args.metrics || []).join(' ') || 'netflow MVRV funding rate'} analysis 2026`,
                    analyze_dex_chart: `${args.pair || ''} dex chart analysis ${args.platform || 'dexscreener'} price action volume`
                };
                const res = await fetch('https://api.tavily.com/search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: config.tavilyKey, query: queryMap[name], search_depth: 'advanced', include_answer: true }) });
                const data = await res.json();
                const label = name.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
                return { display: `📊 **${label}**`, result: `${data.answer || 'See results below.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **${name} failed**`, result: err.message };
            }
        }

        case 'scan_sec_filing': {
            setStatus(`📋 Fetching SEC filings for ${args.symbol}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const filingType = args.filing_type || 'latest';
                const res = await fetch('https://api.tavily.com/search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: config.tavilyKey, query: `${args.symbol} SEC filing ${filingType} EDGAR 10-K 10-Q 8-K insider 13-F 2026`, search_depth: 'advanced', include_answer: true, include_domains: ['sec.gov', 'edgar.sec.gov'] }) });
                const data = await res.json();
                return { display: `📋 **SEC Filing: ${args.symbol}** (${filingType})`, result: `${data.answer || 'See results.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **SEC filing failed**`, result: err.message };
            }
        }

        case 'fetch_futures_levels': {
            setStatus('📊 Fetching futures levels...');
            try {
                const contracts = args.contracts?.length ? args.contracts : ['ES', 'NQ', 'GC', 'SI', 'CL'];
                const symbolMap = { ES: 'ES=F', NQ: 'NQ=F', YM: 'YM=F', RTY: 'RTY=F', CL: 'CL=F', GC: 'GC=F', SI: 'SI=F', NG: 'NG=F', HG: 'HG=F' };
                const results = await Promise.all(contracts.map(async c => {
                    const sym = symbolMap[c.toUpperCase()] || `${c}=F`;
                    try {
                        const r = await fetch(`https://query1.finance.yahoo.com/v8/finance/chart/${sym}?interval=1d&range=2d`);
                        const d = await r.json();
                        const meta = d?.chart?.result?.[0]?.meta;
                        const price = meta?.regularMarketPrice;
                        const prev = meta?.chartPreviousClose;
                        const chg = prev ? ((price - prev) / prev * 100).toFixed(2) : '?';
                        return `**${c}** (${sym}): ${price} (${chg}%)`;
                    } catch { return `${c}: unavailable`; }
                }));
                playAudioAlert('chirp');
                return { display: `📊 **Futures Levels**`, result: results.join('\n') };
            } catch (err) {
                return { display: `❌ **Futures fetch failed**`, result: err.message };
            }
        }

        case 'monitor_price_alert': {
            setStatus(`🎯 Setting price alert for ${args.symbol} ${args.condition} ${args.price}...`);
            try {
                await sendToContentScript({ type: 'PIDGEY_MONITOR', targetElement: `.price, [data-symbol="${args.symbol}"]`, condition_operator: args.condition === 'above' ? '>' : '<', condition_value: args.price.toString(), actionElement: '', actionValue: '' });
                playAudioAlert('action');
                return { display: `🎯 **Price Alert Set:** ${args.symbol} ${args.condition} ${args.price}`, result: `Alert armed: notify when ${args.symbol} goes ${args.condition} ${args.price}` };
            } catch (err) {
                return { display: `❌ **Alert failed**`, result: `Could not set monitor: ${err.message}` };
            }
        }

        case 'read_options_chain': {
            setStatus(`📋 Reading options chain${args.symbol ? ` for ${args.symbol}` : ''}...`);
            if (!config.tavilyKey) return { display: `🔑 **Tavily Search Locked**`, result: `Chirp! I need a Tavily API key to fetch real-time market data or web results for you. Please add yours in **Settings (⚙️)** to unlock this power!` };
            try {
                const sym = args.symbol || 'SPY';
                const expiry = args.expiry || 'this week';
                const res = await fetch('https://api.tavily.com/search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: config.tavilyKey, query: `${sym} options chain ${expiry} unusual activity max pain open interest calls puts 2026`, search_depth: 'advanced', include_answer: true }) });
                const data = await res.json();
                return { display: `📋 **Options Chain: ${sym}** (${expiry})`, result: `${data.answer || 'See results.'}\n\n${(data.results || []).slice(0, 4).map(r => `[${r.title}](${r.url})\n${r.content}`).join('\n\n')}`.substring(0, 8000) };
            } catch (err) {
                return { display: `❌ **Options chain failed**`, result: err.message };
            }
        }


    }
}
