// ==========================================
// SPY INTELLIGENCE ENGINE (The Brain)
// Features: IP Identity Matching, Wealth Scoring, Tech Audit
// Integration: Injects AI cards into #spy-insights-slot
// ==========================================

const DETECTIVE_ONLINE_MS = 5 * 60 * 1000;
const DETECTIVE_RECENT_MS = 30 * 60 * 1000;
const DETECTIVE_IP_MATCH_MS = 48 * 60 * 60 * 1000;

/**
 * Online or recently active visitors with IP-to-incomplete-order bridge (same rules as SpyIntelligence.matchIdentity).
 * Exported for Detective Brain aggregate stats without duplicating logic.
 */
export function enrichVisitorsForDetective(visitors, incompleteOrders) {
    const now = Date.now();
    const activeVisitors = [];
    Object.entries(visitors || {}).forEach(([id, v]) => {
        const isOnline = (now - (v.lastActive || 0)) < DETECTIVE_ONLINE_MS;
        if (!isOnline && (now - (v.lastActive || 0)) >= DETECTIVE_RECENT_MS) return;
        const meta = v.meta || {};
        let matchedProfile = null;
        const visitorIP = meta.ip;
        if (visitorIP && visitorIP !== 'Unknown' && visitorIP !== 'Hidden') {
            const orders = Object.values(incompleteOrders || {});
            matchedProfile = orders.find((o) =>
                o.meta?.ip === visitorIP
                && o.phone
                && (now - (o.capturedAt || 0)) < DETECTIVE_IP_MATCH_MS
            ) || null;
        }
        activeVisitors.push({
            id,
            ...v,
            isOnline,
            meta,
            wealthScore: v.wealthScore || meta.wealthScore || 0,
            wealthClass: (() => {
                let w = v.wealthClass || meta.wealthClass || 'Standard';
                if (String(w).includes('Middle Class')) w = 'Aspiring';
                return w;
            })(),
            identifiedProfile: matchedProfile || null,
        });
    });
    return activeVisitors;
}

export default class SpyIntelligence {
    constructor() {
        this.containerId = 'spy-insights-slot';
        this.container = null; 
        
        this.state = {
            visitors: {},
            incompleteOrders: {},
            insights: []
        };
        
        // Intelligence Configuration
        this.config = {
            onlineThreshold: 5 * 60 * 1000,      // 5 Minutes (Definition of "Online")
            ipMatchWindow: 48 * 60 * 60 * 1000,  // Look back 48 Hours for matching IP
            highIntentActions: ['checkout', 'purchase', 'add_to_cart', 'order', 'payment'],
            wealthThreshold: 80 // Score above 80 is "Elite"
        };
    }

    /**
     * Main Entry Point called from Dashboard.js
     * @param {Object} visitors - Raw visitor data
     * @param {Object} incompleteOrders - Raw incomplete order data
     */
    update(visitors, incompleteOrders) {
        // Attempt to find the slot created by visitor-spy.js
        this.container = document.getElementById(this.containerId);
        
        // If container doesn't exist yet (tab not loaded), stop
        if (!this.container) return;

        this.state.visitors = visitors || {};
        this.state.incompleteOrders = incompleteOrders || {};

        // 1. Data Fusion: Match IPs to find Phone Numbers (The "Bridge")
        const enrichedData = this.matchIdentity();

        // 2. Run Analysis Engines (The "Brain")
        this.state.insights = this.runAnalyzers(enrichedData);

        // 3. Render the Intelligence UI
        this.render();
    }

    // ============================================================
    // CORE LOGIC 1: IDENTITY MATCHER (IP BRIDGE)
    // ============================================================
    matchIdentity() {
        return enrichVisitorsForDetective(this.state.visitors, this.state.incompleteOrders);
    }

    // ============================================================
    // CORE LOGIC 2: RULE ENGINES (ADVANCED)
    // ============================================================
    runAnalyzers(data) {
        let insights = [];
        let onlineCount = data.filter(v => v.isOnline).length;
        
        // Sort data: Elite users first
        data.sort((a, b) => b.wealthScore - a.wealthScore);

        // --- 1. The "Tycoon" (Elite Wealth Detected) ---
        // Logic: Wealth Score > 80 (iPhone Pro / Flagship Android)
        const tycoons = data.filter(v => v.isOnline && v.wealthScore >= this.config.wealthThreshold);
        
        if (tycoons.length > 0) {
            tycoons.forEach(v => {
                const gpuName = v.meta.gpu || 'High-End Device';
                // Shorten GPU name for display
                const shortGPU = gpuName.replace('Apple', '').replace('(TM)', '').replace('Renderer', '').trim();
                
                insights.push({
                    type: 'elite',
                    icon: 'fa-gem',
                    title: `💎 Elite Visitor Detected`,
                    message: `<strong>Score: ${v.wealthScore}/100</strong>. Using ${shortGPU}. <br>Purchasing Power: <span class="text-green-600 font-bold">Very High</span>.`,
                    actionText: v.identifiedProfile ? `Call: ${v.identifiedProfile.phone}` : 'Track Live',
                    actionLink: v.identifiedProfile ? `tel:${v.identifiedProfile.phone}` : '#',
                    bgClass: 'bg-slate-900 text-white border-purple-500 border', // Dark Premium Theme
                    textClass: 'text-gray-200',
                    btnClass: 'bg-purple-600 hover:bg-purple-700 text-white border-none',
                    isPulse: true
                });
            });
        }

        // --- 2. The "Closer" (Hot Lead with Phone Number) ---
        // Logic: Online + High Intent + Phone Found via IP Match (But not necessarily Elite)
        data.forEach(v => {
            if (v.isOnline && v.identifiedProfile && this.isHighIntent(v) && v.wealthScore < this.config.wealthThreshold) {
                insights.push({
                    type: 'critical',
                    icon: 'fa-phone-volume',
                    title: '🔥 Hot Lead Identified!',
                    message: `<strong>${v.identifiedProfile.name || 'Customer'}</strong> is stuck at checkout.<br>ISP: ${v.meta.isp}<br>Phone found via IP Match.`,
                    actionText: `Call: ${v.identifiedProfile.phone}`,
                    actionLink: `tel:${v.identifiedProfile.phone}`,
                    bgClass: 'bg-red-50 border-red-500 ring-1 ring-red-200',
                    textClass: 'text-red-800',
                    btnClass: 'bg-red-600 text-white hover:bg-red-700 animate-pulse'
                });
            }
        });

        // --- 3. The "Data Spender" (Premium Network User) ---
        // Logic: Using 4G/5G + No Data Saver (Has Disposable Income)
        const premiumNetUsers = data.filter(v => 
            v.isOnline && 
            v.meta.networkType === '4g' && 
            !v.meta.isDataSaver &&
            v.wealthScore < this.config.wealthThreshold // Don't duplicate if already Tycoon
        );

        if (premiumNetUsers.length > 0) {
            insights.push({
                type: 'opportunity',
                icon: 'fa-signal',
                title: 'Premium Data User',
                message: `<strong>${premiumNetUsers.length} visitor(s)</strong> browsing on expensive 4G data without Data Saver. Likely to convert.`,
                actionText: null,
                bgClass: 'bg-blue-50 border-blue-500 ring-1 ring-blue-200',
                textClass: 'text-blue-800',
                btnClass: ''
            });
        }

        // --- 4. The "Monitor" (Cart Abandonment Risk) ---
        // Logic: Online + High Intent + No Phone
        const stuckUsers = data.filter(v => v.isOnline && !v.identifiedProfile && this.isHighIntent(v));
        if (stuckUsers.length > 0) {
            insights.push({
                type: 'warning',
                icon: 'fa-cart-arrow-down',
                title: 'Cart Alert',
                message: `<strong>${stuckUsers.length} visitors</strong> have items in cart but haven't entered details yet.`,
                actionText: null,
                bgClass: 'bg-yellow-50 border-yellow-500 ring-1 ring-yellow-200',
                textClass: 'text-yellow-800',
                btnClass: ''
            });
        }

        // --- 5. Tech Glitch Detector (Low Battery) ---
        const dyingPhones = data.filter(v => 
            v.isOnline && 
            this.isHighIntent(v) && 
            parseInt(v.meta.batteryLevel) < 15 && 
            v.meta.isCharging === 'No'
        );

        if (dyingPhones.length > 0) {
            insights.push({
                type: 'technical',
                icon: 'fa-battery-quarter',
                title: 'Risk: Low Battery',
                message: `Visitor at checkout has <strong>${dyingPhones[0].meta.batteryLevel} battery</strong>. Might drop off.`,
                actionText: null,
                bgClass: 'bg-gray-100 border-gray-400 text-gray-600',
                textClass: 'text-gray-700',
                btnClass: ''
            });
        }

        // --- DEFAULT STATUS (If nothing exciting is happening) ---
        if (insights.length === 0) {
            insights.push({
                type: 'status',
                icon: 'fa-robot',
                title: 'AI Scanning Active',
                message: `Analyzing <strong>${onlineCount} online visitors</strong> using GPU Fingerprinting & IP Triangulation. No critical alerts.`,
                actionText: null,
                bgClass: 'bg-white border-gray-200',
                textClass: 'text-gray-500',
                isPulse: true
            });
        }

        return insights;
    }

    // Helper: Determine Intent
    isHighIntent(visitor) {
        if (!visitor.logs) return false;
        const logs = Object.values(visitor.logs);
        return logs.some(l => 
            this.config.highIntentActions.some(action => 
                (l.action || '').toLowerCase().includes(action) || 
                (l.page || '').toLowerCase().includes(action)
            )
        );
    }

    // ============================================================
    // UI RENDERER
    // ============================================================
    render() {
        if (!this.container) return;

        // Ensure container is visible
        this.container.classList.remove('hidden');
        
        // Generate Cards HTML
        const cardsHtml = this.state.insights.map(insight => `
            <div class="flex-shrink-0 w-full md:w-[22rem] p-4 rounded-xl border-l-4 shadow-sm ${insight.bgClass} relative overflow-hidden group transition-all duration-300 transform hover:-translate-y-1">
                <div class="flex items-start gap-3 relative z-10">
                    <div class="mt-1 h-10 w-10 rounded-full bg-white/20 backdrop-blur-md flex items-center justify-center shadow-inner text-lg ${insight.textClass}">
                        <i class="fa-solid ${insight.icon} ${insight.isPulse ? 'animate-pulse' : ''}"></i>
                    </div>
                    <div class="flex-grow">
                        <h4 class="font-bold text-sm ${insight.textClass} uppercase tracking-wide flex items-center gap-2">
                            ${insight.title}
                        </h4>
                        <p class="text-xs mt-1.5 font-medium opacity-90 leading-relaxed ${insight.textClass}">${insight.message}</p>
                        
                        ${insight.actionText ? `
                            <a href="${insight.actionLink}" class="mt-3 inline-flex items-center gap-2 px-4 py-2 rounded-lg text-xs font-bold shadow-sm transition-all transform hover:scale-105 ${insight.btnClass}">
                                ${insight.actionText} <i class="fa-solid fa-arrow-right"></i>
                            </a>
                        ` : ''}
                    </div>
                </div>
                <!-- Decorative Background Icon -->
                <i class="fa-solid ${insight.icon} absolute -bottom-6 -right-6 text-9xl opacity-5 pointer-events-none transform rotate-12"></i>
            </div>
        `).join('');

        // Inject into Slot with a nice Header
        this.container.innerHTML = `
            <div class="p-4 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-white">
                <div class="flex justify-between items-center mb-3">
                    <h3 class="text-xs font-extrabold text-gray-500 uppercase flex items-center gap-2 tracking-widest">
                        <i class="fa-solid fa-brain text-indigo-500"></i> AI Intelligence Feed
                    </h3>
                    <span class="text-[10px] bg-indigo-100 text-indigo-700 px-2 py-0.5 rounded font-bold">LIVE</span>
                </div>
                <div class="flex flex-col md:flex-row gap-4 overflow-x-auto pb-2 scrollbar-hide">
                    ${cardsHtml}
                </div>
            </div>
        `;
    }
}