// sp-tools-reseller.js
export async function executeResellerTool(name, args, _ui, _state) {
    const { setStatus, addBotMessage, playAudioAlert } = _ui;
    const { config } = _state;
    switch (name) {
        case 'calculate_profit': {
            setStatus('💵 Calculating profit...');
            const sale = args.sale_price || 0;
            const cogs = args.cost_of_goods || 0;
            const oz = args.item_weight_oz || 8;
            const fees = { ebay: 0.1325, poshmark: 0.20, mercari: 0.10, depop: 0.10, facebook: 0 };
            const platform = args.platform?.toLowerCase() || 'ebay';
            const feeRate = fees[platform] || 0.13;
            const feeAmt = sale * feeRate;
            const paymentFee = platform === 'mercari' ? sale * 0.029 : 0;
            const shipping = oz <= 4 ? 3.50 : oz <= 8 ? 4.50 : oz <= 16 ? 5.50 : oz <= 32 ? 7.50 : 10.00;
            const shipCost = args.shipping_type === 'free' ? shipping : args.shipping_type === 'buyer' ? 0 : shipping;
            const profit = sale - cogs - feeAmt - paymentFee - shipCost;
            const margin = ((profit / sale) * 100).toFixed(1);
            const roi = cogs > 0 ? ((profit / cogs) * 100).toFixed(0) : 'N/A';
            const result = `💵 PROFIT CALCULATOR: ${platform.toUpperCase()}\n\nSale Price: ${sale.toFixed(2)}\n  – Cost of Goods: ${cogs.toFixed(2)}\n  – Platform Fee (${(feeRate * 100).toFixed(1)}%): ${feeAmt.toFixed(2)}\n${paymentFee > 0 ? `  – Payment Fee: ${paymentFee.toFixed(2)}\n` : ''}  – Shipping (est. ${oz}oz): ${shipCost.toFixed(2)}\n\n💰 NET PROFIT: ${profit.toFixed(2)}\n📊 Margin: ${margin}% | ROI: ${roi}%\n\n${profit > 10 ? '🟢 Worth listing!' : profit > 0 ? '🟡 Slim profit — price higher or find cheaper cogs' : '🔴 Would LOSE money — don\'t list at this price'}`;
            return { display: `💵 **Profit:** ${profit.toFixed(2)} on ${sale} sale`, result };
        }

        case 'shipping_calculator': {
            setStatus('📦 Calculating shipping...');
            const oz = args.weight_oz || 8;
            const lbs = oz / 16;
            const rates = [
                { service: 'USPS First Class (under 1lb)', max: 15.9, rate: oz <= 4 ? 3.50 : oz <= 8 ? 4.50 : oz <= 12 ? 5.00 : 5.50, eligible: oz < 16 },
                { service: 'USPS Ground Advantage', max: 999, rate: oz <= 8 ? 5.50 : lbs <= 2 ? 7.00 : lbs <= 5 ? 9.50 : lbs * 1.80 + 5, eligible: true },
                { service: 'USPS Priority Mail', max: 999, rate: oz <= 16 ? 8.00 : lbs <= 5 ? 11.00 : lbs * 2.10 + 6, eligible: true },
                { service: 'Poly Mailer (Poshmark/Mercari label)', max: 5, rate: 'Platform label — seller pays ~$6-7 flat', eligible: true }
            ].filter(r => r.eligible);
            const result = `📦 SHIPPING ESTIMATE\n\nItem Weight: ${oz}oz (${lbs.toFixed(2)}lbs)\n\n${rates.map(r => `${r.service}: ~${typeof r.rate === 'number' ? r.rate.toFixed(2) : r.rate}`).join('\n')}\n\n💡 PRO TIPS:\n- Under 1lb → USPS First Class is cheapest\n- Over 1lb → USPS Ground Advantage wins\n- Use prepaid platform labels (Poshmark/Mercari) for simplicity\n- Weigh with kitchen scale for accuracy — overestimating = lost profit\n- Buy poly mailers in bulk: Amazon 100-pack = pennies each`;
            return { display: `📦 **Shipping Estimate:** ${oz}oz item`, result };
        }


        case 'ebay_listing_analyzer': {
            setStatus('🦅 High-flying analysis of eBay listing...');
            if (!config.tavilyKey) {
                return { 
                    display: `🔑 **Tavily Search Locked**`,
                    result: `Chirp! I need a Tavily API key for live market analysis. For now, here's what to check on **${args.url}**:\n1. **SEO Title**: Use 80 chars.\n2. **Photos**: Use all 24 slots.\n3. **Price**: Check 'Sold' listings.\n4. **Description**: Use bullet points.`,
                };
            }
            
            try {
                const query = `ebay listing analysis optimization guide for ${args.url} market comps`;
                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: `🦅 **eBay Listing Insight** for ${args.url.substring(0, 30)}...`, 
                    result: `Listing Analysis:\n\n${data.answer || 'I found some insights for your listing.'}\n\nKey Insights:\n${(data.results || []).slice(0, 3).map(r => `- ${r.title}: ${r.content.substring(0, 200)}...`).join('\n')}` 
                };
            } catch (err) {
                return { display: `❌ Analysis failed`, result: err.message };
            }
        }

        case 'ebay_bulk_lister': {
            setStatus('📦 Preparing bulk listing strategy...');
            const itemsList = Array.isArray(args.items) ? args.items : [args.items];
            const strategy = itemsList.map(item => {
                const title = item.length > 50 ? item.substring(0, 80) : `${item} - Excellent Condition - Fast Shipping`;
                return `- **${item}**\n  - Proposed Title: ${title}\n  - Category: Research recommended\n  - Format: Buy It Now (Good 'til Cancelled)`;
            }).join('\n\n');
            
            return { 
                display: `📦 **eBay Bulk Strategy Ready** for ${itemsList.length} items.`, 
                result: `Bulk Strategy:\n\n${strategy}\n\n💡 **Pidgey Tip:** Use eBay's 'Bulk Edit' tool once these drafts are started to set shipping and returns for all items at once!` 
            };
        }

        case 'identify_item':
        case 'generate_listings':
        case 'condition_guide':
        case 'authenticity_check':
        case 'bundle_strategy':
        case 'background_removal':
        case 'research_sold_prices':
        case 'trending_items': {
            // research_sold_prices and trending_items always need Tavily
            if ((name === 'research_sold_prices' || name === 'trending_items') && !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!` };
            }

            // For non-Tavily-dependent tools, return structured guidance
            if (!config.tavilyKey) {
                const guides = {
                    identify_item: `🔍 ITEM IDENTIFICATION\n\nTo identify this item, look for:\n1. Brand tag (back/inner collar/sole)\n2. Style code or model number\n3. Material tags and country of manufacture\n4. Season/year codes (e.g. Nike style codes date items)\n5. Collab or limited edition tags\n\nShare a photo or paste any tag text and I'll help identify it!`,
                    condition_guide: `⭐ CONDITION GRADES for ${args.platform?.toUpperCase() || 'eBay/Poshmark/Mercari'}\n\nNew with Tags (NWT): Original tags attached, unworn\nLike New (NWT): Worn once or twice, no flaws\nVery Good: Minor wear only, no visible flaws in listing photos\nGood: Light pilling, minor marks — disclose all\nFair: Noticeable wear, price accordingly\nPoor: Heavy wear — list for parts/lot only\n\n💡 Accurate grading = fewer returns = better seller rating`,
                    authenticity_check: `🔐 AUTHENTICITY: ${args.brand}\n\nGeneral authentication red flags:\n- Misspelled brand name or logo\n- Off-center or uneven stitching\n- Wrong font on tags (compare to legit examples)\n- Too-cheap price for the brand\n- No hologram/serial number on high-end items\n- License plate / hang tags look printed vs. embossed\n\nFor ${args.brand}: Search "${args.brand} real vs fake guide" and check YouTube — brand-specific tells are best learned visually.`,
                    bundle_strategy: `📦 BUNDLE STRATEGY\n\nItems: ${args.items}\n\nBest bundle plays:\n1. Same brand + size = easy bundle sell\n2. Complete outfit or "look" = higher perceived value\n3. List individual + bundle — let buyer decide\n4. Bundle discount: offer 10-15% off bundles in bio\n5. Mercari: Bundle 2+ items → share combined listing\n6. Poshmark: Create a bundle for a specific buyer\n\n💡 Bundles move 3x faster and get 30-50% more per item`,
                    background_removal: `🖼️ BACKGROUND REMOVAL\n\nFREE OPTIONS:\n- remove.bg — best quality, 1 free/day, $1-2 per photo\n- Canva free background remover\n- PicsArt app (free tier)\n- iPhone/iPad: Long-press any photo → Copy Subject\n\nDIY CLEAN BACKGROUND:\n- White foam board ($2 at Dollar Tree)\n- Near a window for natural light (no flash)\n- Lay flat for shoes/folded items\n- Hang on white wall for clothing\n\n💡 Clean backgrounds = more professional = higher sell price`
                };
                if (guides[name]) return { display: `📋 **${name.replace(/_/g, ' ')}**`, result: guides[name] };
            }

            const queries = {
                identify_item: `identify ${args.description || args.image_context || 'vintage item'} brand model year value resell`,
                generate_listings: `${args.item} eBay Poshmark Mercari listing title SEO keywords ${args.key_features || ''}`,
                condition_guide: `${args.platform} condition grading standards ${args.category} seller guide`,
                authenticity_check: `${args.brand} ${args.item_type} authentic vs fake how to tell guide`,
                bundle_strategy: `${args.platform} bundle listing strategy ${args.items} resell tips`,
                background_removal: 'product photo background removal free tools reseller guide',
                research_sold_prices: `${args.item} sold price ${args.platform || 'ebay poshmark mercari'} ${args.condition || ''} 2025 2026 resell value`,
                trending_items: `trending resell items ${args.category || 'all categories'} ${args.platform || 'ebay poshmark'} 2026 hot sellers`
            };
            setStatus(`🏷️ Researching: ${name.replace(/_/g, ' ')}...`);
            try {
                const res = await fetch('https://api.tavily.com/search', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ api_key: config.tavilyKey, query: queries[name], search_depth: 'advanced', include_answer: true }) });
                const data = await res.json();
                return { display: `🏷️ **${name.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}**`, 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: `❌ **${name} failed**`, result: err.message };
            }
        }

        case 'ebay_price_sniper': {
            setStatus(`🎯 Setting price sniper for "${args.query}"...`);
            const query = args.query;
            const target = args.target_price;
            const interval = args.check_interval || 60;

            const result = [
                `🎯 EBAY PRICE SNIPER`,
                ``,
                `Query: ${query}`,
                `Target Price: $${target.toFixed(2)}`,
                `Check Interval: Every ${interval} minutes`,
                ``,
                `⚠️ Price monitoring is a background feature that requires the extension to stay active.`,
                ``,
                `In the meantime, here are quick ways to manually track:`,
                `1. **eBay Saved Search**: Go to eBay → Search "${query}" → Click "Save this search" → Enable email alerts`,
                `2. **Price filter**: Set max price to $${target.toFixed(2)} in search filters`,
                `3. **CamelCamelCamel** or **Keepa** for Amazon price tracking`,
                ``,
                `💡 Tip: Sort by "Newly Listed" and check a few times a day for the best snipes.`
            ].join('\n');

            return { display: `🎯 **Price Sniper:** "${query}" under $${target.toFixed(2)}`, result };
        }

    }
}
