import React, { useState, useEffect, useCallback } from 'react';
import { useAdmin } from '../../context/AdminContext';
import '../../styles/intelligence-panel.css';

/**
 * IntelligencePanel — Campaign performance monitoring, optimization insights,
 * and post-campaign analysis. Manages its own data fetching.
 *
 * Attempts live API calls to /api/admin/reporting/*; falls back to
 * emulated data when the endpoint isn't wired up yet.
 */

// ─── Channel metadata ────────────────────────────────────────────────────────

const CHANNEL_META = {
    google_ads: { label: 'Google',  color: '#1a73e8', bg: '#e8f0fe' },
    meta:       { label: 'Meta',    color: '#7c3aed', bg: '#f3e8ff' },
    tiktok:     { label: 'TikTok',  color: '#ff0050', bg: '#fff0f0' },
};

const SEVERITY_META = {
    critical: { label: 'Critical', color: '#dc2626', bg: '#fef2f2', icon: '🔴' },
    warning:  { label: 'Warning',  color: '#d97706', bg: '#fffbeb', icon: '🟡' },
    info:     { label: 'Info',     color: '#2563eb', bg: '#eff6ff', icon: '🔵' },
};

// ─── Formatters ──────────────────────────────────────────────────────────────

const fmtCurrency = (v) => v == null ? '—' : '$' + Number(v).toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 });
const fmtNumber   = (v) => v == null ? '—' : Number(v).toLocaleString();
const fmtPct      = (v) => v == null ? '—' : Number(v).toFixed(2) + '%';
const fmtDec      = (v, d = 2) => v == null ? '—' : '$' + Number(v).toFixed(d);

// ─── Main Panel ──────────────────────────────────────────────────────────────

export default function IntelligencePanel({ activeTab }) {
    return (
        <div className="intel-panel">
            {activeTab === 'performance' && <PerformanceView />}
            {activeTab === 'insights'    && <InsightsView />}
            {activeTab === 'analysis'    && <AnalysisView />}
        </div>
    );
}


// ═════════════════════════════════════════════════════════════════════════════
//  PERFORMANCE VIEW
// ═════════════════════════════════════════════════════════════════════════════

function PerformanceView() {
    const { apiCall } = useAdmin();
    const [summary, setSummary] = useState(null);
    const [campaigns, setCampaigns] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [dateFrom, setDateFrom] = useState('');
    const [dateTo, setDateTo] = useState('');
    const [clientFilter, setClientFilter] = useState('');
    const [clients, setClients] = useState([]);
    const [emulated, setEmulated] = useState(false);

    // Load clients for filter dropdown
    useEffect(() => {
        (async () => {
            const r = await apiCall('/api/admin/clients/list', 'POST', {});
            if (r.ok && r.clients) setClients(r.clients);
        })();
    }, [apiCall]);

    const loadData = useCallback(async () => {
        setLoading(true);
        setError(null);
        setEmulated(false);

        try {
            const reportBody = {};
            if (dateFrom)     reportBody.dateFrom  = dateFrom;
            if (dateTo)       reportBody.dateTo    = dateTo;
            if (clientFilter) reportBody.clientId  = clientFilter;

            const [summaryRes, campaignsRes] = await Promise.all([
                apiCall('/api/admin/reporting/summary',   'POST', reportBody),
                apiCall('/api/admin/reporting/campaigns', 'POST', reportBody),
            ]);

            if (summaryRes.ok) {
                setSummary(summaryRes);
                setCampaigns(campaignsRes.ok ? campaignsRes : null);
            } else {
                // API not wired yet — use emulated data
                setSummary(EMULATED_SUMMARY);
                setCampaigns(EMULATED_CAMPAIGNS);
                setEmulated(true);
            }
        } catch {
            setSummary(EMULATED_SUMMARY);
            setCampaigns(EMULATED_CAMPAIGNS);
            setEmulated(true);
        }

        setLoading(false);
    }, [apiCall, dateFrom, dateTo, clientFilter]);

    useEffect(() => { loadData(); }, [loadData]);

    if (loading && !summary) {
        return <div className="intel-loading"><div className="spinner"></div><p>Loading performance data...</p></div>;
    }

    const s = summary || {};
    const campaignList = campaigns?.campaigns || [];

    return (
        <div className="intel-performance">
            {emulated && <EmulatedBanner />}

            {/* ── Filter Bar ── */}
            <div className="filter-bar">
                <div className="filter-group">
                    <label className="filter-label">From</label>
                    <input type="date" className="filter-input" value={dateFrom} onChange={e => setDateFrom(e.target.value)} />
                </div>
                <div className="filter-group">
                    <label className="filter-label">To</label>
                    <input type="date" className="filter-input" value={dateTo} onChange={e => setDateTo(e.target.value)} />
                </div>
                <div className="filter-group">
                    <label className="filter-label">Client</label>
                    <select className="filter-select" value={clientFilter} onChange={e => setClientFilter(e.target.value)}>
                        <option value="">All Clients</option>
                        {clients.map(c => <option key={c.clientId} value={c.clientId}>{c.clientName}</option>)}
                    </select>
                </div>
                <button className="btn-action" onClick={loadData} style={{ alignSelf: 'flex-end' }}>↻ Refresh</button>
            </div>

            {/* ── KPI Cards ── */}
            <div className="intel-kpi-grid">
                <KpiCard label="Active Campaigns" value={s.activeCampaigns} format="number" />
                <KpiCard label="Total Spend" value={s.totalSpend} format="currency" />
                <KpiCard label="Impressions" value={s.totalImpressions} format="number" />
                <KpiCard label="Clicks" value={s.totalClicks} format="number" />
                <KpiCard label="Conversions" value={s.totalConversions} format="number" />
                <KpiCard
                    label="Avg CTR"
                    value={s.totalImpressions > 0 ? (s.totalClicks / s.totalImpressions * 100) : 0}
                    format="pct"
                />
            </div>

            {/* ── Channel Breakdown ── */}
            {s.channelBreakdown && s.channelBreakdown.length > 0 && (
                <div className="intel-channel-breakdown">
                    <h3>Channel Breakdown</h3>
                    <div className="intel-channel-cards">
                        {s.channelBreakdown.map(ch => {
                            const meta = CHANNEL_META[ch.channel] || { label: ch.channel, color: '#6b7280', bg: '#f3f4f6' };
                            return (
                                <div key={ch.channel} className="intel-channel-card" style={{ borderTopColor: meta.color }}>
                                    <div className="intel-channel-header">
                                        <span className="intel-channel-badge" style={{ background: meta.bg, color: meta.color }}>{meta.label}</span>
                                        <span className="intel-channel-count">{ch.campaignCount} campaign{ch.campaignCount !== 1 ? 's' : ''}</span>
                                    </div>
                                    <div className="intel-channel-metrics">
                                        <div><span className="metric-val">{fmtCurrency(ch.spend)}</span><span className="metric-lbl">Spend</span></div>
                                        <div><span className="metric-val">{fmtNumber(ch.impressions)}</span><span className="metric-lbl">Impressions</span></div>
                                        <div><span className="metric-val">{fmtNumber(ch.clicks)}</span><span className="metric-lbl">Clicks</span></div>
                                        <div><span className="metric-val">{fmtNumber(ch.conversions)}</span><span className="metric-lbl">Conversions</span></div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {/* ── Campaign Performance Table ── */}
            <div className="intel-campaigns-table">
                <h3>Campaign Performance</h3>
                {campaignList.length === 0 ? (
                    <div className="empty-state">
                        <div className="empty-state-icon">📊</div>
                        <h3>No performance data yet</h3>
                        <p>Metrics will appear here once campaigns are running and the polling service collects data.</p>
                    </div>
                ) : (
                    <table className="data-table">
                        <thead>
                            <tr>
                                <th>Campaign</th>
                                <th>Client</th>
                                <th>Status</th>
                                <th>Channels</th>
                                <th style={{ textAlign: 'right' }}>Spend</th>
                                <th style={{ textAlign: 'right' }}>Impressions</th>
                                <th style={{ textAlign: 'right' }}>Clicks</th>
                                <th style={{ textAlign: 'right' }}>CTR</th>
                                <th style={{ textAlign: 'right' }}>CPC</th>
                                <th style={{ textAlign: 'right' }}>Conv.</th>
                                <th>Pacing</th>
                            </tr>
                        </thead>
                        <tbody>
                            {campaignList.map(c => (
                                <CampaignPerfRow key={c.initiativeId} campaign={c} />
                            ))}
                        </tbody>
                    </table>
                )}
            </div>
        </div>
    );
}


// ─── Campaign Performance Row ────────────────────────────────────────────────

function CampaignPerfRow({ campaign }) {
    const c = campaign;
    const channels = c.channels || [];
    const pacing = c.budgetPacing || 0;

    return (
        <tr>
            <td style={{ fontWeight: 500 }}>{c.name}</td>
            <td>{c.clientName || '—'}</td>
            <td><StatusBadge status={c.status} /></td>
            <td>
                <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                    {channels.map((ch, i) => {
                        const meta = CHANNEL_META[ch.channelType] || { label: ch.channelType, bg: '#f3f4f6', color: '#6b7280' };
                        return (
                            <span key={i} className="channel-badge" style={{ background: meta.bg, color: meta.color }}>
                                {meta.label}
                            </span>
                        );
                    })}
                </div>
            </td>
            <td style={{ textAlign: 'right' }}>{fmtCurrency(c.spend)}</td>
            <td style={{ textAlign: 'right' }}>{fmtNumber(c.impressions)}</td>
            <td style={{ textAlign: 'right' }}>{fmtNumber(c.clicks)}</td>
            <td style={{ textAlign: 'right' }}>{fmtPct(c.ctr)}</td>
            <td style={{ textAlign: 'right' }}>{fmtDec(c.cpc)}</td>
            <td style={{ textAlign: 'right' }}>{fmtNumber(c.conversions)}</td>
            <td><PacingBar pct={pacing} /></td>
        </tr>
    );
}


// ═════════════════════════════════════════════════════════════════════════════
//  INSIGHTS VIEW
// ═════════════════════════════════════════════════════════════════════════════

function InsightsView() {
    const { apiCall } = useAdmin();
    const [insights, setInsights] = useState(null);
    const [loading, setLoading] = useState(true);
    const [severityFilter, setSeverityFilter] = useState('');
    const [emulated, setEmulated] = useState(false);

    const loadData = useCallback(async () => {
        setLoading(true);
        setEmulated(false);

        const insightsBody = {};
        if (severityFilter) insightsBody.severity = severityFilter;

        const res = await apiCall('/api/admin/reporting/insights', 'POST', insightsBody);
        if (res.ok) {
            setInsights(res);
        } else {
            setInsights(EMULATED_INSIGHTS);
            setEmulated(true);
        }
        setLoading(false);
    }, [apiCall, severityFilter]);

    useEffect(() => { loadData(); }, [loadData]);

    const insightList = insights?.insights || [];
    const totalActive = insights?.totalActive ?? insightList.length;

    if (loading && !insights) {
        return <div className="intel-loading"><div className="spinner"></div><p>Loading insights...</p></div>;
    }

    return (
        <div className="intel-insights">
            {emulated && <EmulatedBanner />}

            <div className="intel-insights-header">
                <div className="intel-insights-summary">
                    <span className="intel-insights-count">{totalActive}</span>
                    <span>active insight{totalActive !== 1 ? 's' : ''}</span>
                </div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    <select className="filter-select" value={severityFilter} onChange={e => setSeverityFilter(e.target.value)}>
                        <option value="">All Severities</option>
                        <option value="critical">Critical</option>
                        <option value="warning">Warning</option>
                        <option value="info">Info</option>
                    </select>
                    <button className="btn-action" onClick={loadData}>↻ Refresh</button>
                </div>
            </div>

            {insightList.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-state-icon">✅</div>
                    <h3>All clear</h3>
                    <p>No active optimization recommendations at this time.</p>
                </div>
            ) : (
                <div className="intel-insights-list">
                    {insightList.map(insight => (
                        <InsightCard key={insight.insightId} insight={insight} />
                    ))}
                </div>
            )}
        </div>
    );
}


function InsightCard({ insight }) {
    const sev = SEVERITY_META[insight.severity] || SEVERITY_META.info;
    const [expanded, setExpanded] = useState(false);

    return (
        <div className="intel-insight-card" style={{ borderLeftColor: sev.color }}>
            <div className="intel-insight-top" onClick={() => setExpanded(!expanded)} style={{ cursor: 'pointer' }}>
                <div className="intel-insight-meta">
                    <span className="intel-insight-severity" style={{ background: sev.bg, color: sev.color }}>
                        {sev.icon} {sev.label}
                    </span>
                    <span className="intel-insight-type">{formatInsightType(insight.insightType)}</span>
                </div>
                <h4 className="intel-insight-title">{insight.title}</h4>
                <div className="intel-insight-context">
                    <span>{insight.clientName}</span>
                    <span>·</span>
                    <span>{insight.campaignName}</span>
                    <span className="intel-insight-expand">{expanded ? '▾' : '▸'}</span>
                </div>
            </div>
            {expanded && (
                <div className="intel-insight-body">
                    <p className="intel-insight-desc">{insight.description}</p>
                    {insight.recommendation && (
                        <div className="intel-insight-rec">
                            <strong>Recommendation:</strong> {insight.recommendation}
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}


// ═════════════════════════════════════════════════════════════════════════════
//  ANALYSIS VIEW
// ═════════════════════════════════════════════════════════════════════════════

function AnalysisView() {
    const { apiCall } = useAdmin();
    const [analysis, setAnalysis] = useState(null);
    const [loading, setLoading] = useState(true);
    const [emulated, setEmulated] = useState(false);

    const loadData = useCallback(async () => {
        setLoading(true);
        setEmulated(false);

        const res = await apiCall('/api/admin/reporting/analysis', 'POST', {});
        if (res.ok) {
            setAnalysis(res);
        } else {
            setAnalysis(EMULATED_ANALYSIS);
            setEmulated(true);
        }
        setLoading(false);
    }, [apiCall]);

    useEffect(() => { loadData(); }, [loadData]);

    const campaignList = analysis?.campaigns || [];

    if (loading && !analysis) {
        return <div className="intel-loading"><div className="spinner"></div><p>Loading analysis...</p></div>;
    }

    return (
        <div className="intel-analysis">
            {emulated && <EmulatedBanner />}

            <div className="panel-header">
                <h2>Post-Campaign Analysis ({campaignList.length})</h2>
                <button className="btn-action" onClick={loadData}>↻ Refresh</button>
            </div>

            {campaignList.length === 0 ? (
                <div className="empty-state">
                    <div className="empty-state-icon">📈</div>
                    <h3>No completed campaigns</h3>
                    <p>Post-campaign analysis will appear here once campaigns finish their run.</p>
                </div>
            ) : (
                <div className="intel-analysis-list">
                    {campaignList.map(c => (
                        <AnalysisCard key={c.initiativeId} campaign={c} />
                    ))}
                </div>
            )}
        </div>
    );
}


function AnalysisCard({ campaign }) {
    const c = campaign;
    const channels = c.channels || [];
    const [expanded, setExpanded] = useState(false);

    return (
        <div className="intel-analysis-card">
            <div className="intel-analysis-top" onClick={() => setExpanded(!expanded)} style={{ cursor: 'pointer' }}>
                <div className="intel-analysis-header">
                    <div>
                        <h4>{c.name}</h4>
                        <span className="text-muted">{c.clientName} · {c.objective}</span>
                    </div>
                    <span className="intel-analysis-expand">{expanded ? '▾' : '▸'}</span>
                </div>
                <div className="intel-analysis-kpis">
                    <div className="intel-analysis-kpi">
                        <span className="metric-val">{fmtCurrency(c.totalSpend)}</span>
                        <span className="metric-lbl">Spent of {fmtCurrency(c.totalBudget)}</span>
                    </div>
                    <div className="intel-analysis-kpi">
                        <span className="metric-val">{fmtNumber(c.totalImpressions)}</span>
                        <span className="metric-lbl">Impressions</span>
                    </div>
                    <div className="intel-analysis-kpi">
                        <span className="metric-val">{fmtNumber(c.totalClicks)}</span>
                        <span className="metric-lbl">Clicks</span>
                    </div>
                    <div className="intel-analysis-kpi">
                        <span className="metric-val">{fmtPct(c.ctr)}</span>
                        <span className="metric-lbl">CTR</span>
                    </div>
                    <div className="intel-analysis-kpi">
                        <span className="metric-val">{fmtNumber(c.totalConversions)}</span>
                        <span className="metric-lbl">Conversions</span>
                    </div>
                    <div className="intel-analysis-kpi">
                        <span className="metric-val">{fmtDec(c.costPerConversion)}</span>
                        <span className="metric-lbl">Cost/Conv.</span>
                    </div>
                </div>
                {/* Budget utilization bar */}
                <div className="intel-analysis-budget">
                    <PacingBar pct={c.budgetUtilization || 0} label="Budget Utilization" showLabel />
                </div>
            </div>

            {expanded && channels.length > 0 && (
                <div className="intel-analysis-channels">
                    <h5>Channel Performance</h5>
                    <table className="data-table">
                        <thead>
                            <tr>
                                <th>Channel</th>
                                <th style={{ textAlign: 'right' }}>Allocated</th>
                                <th style={{ textAlign: 'right' }}>Actual Spend</th>
                                <th style={{ textAlign: 'right' }}>Impressions</th>
                                <th style={{ textAlign: 'right' }}>Clicks</th>
                                <th style={{ textAlign: 'right' }}>Conv.</th>
                            </tr>
                        </thead>
                        <tbody>
                            {channels.map((ch, i) => {
                                const meta = CHANNEL_META[ch.channel] || { label: ch.channel, bg: '#f3f4f6', color: '#6b7280' };
                                return (
                                    <tr key={i}>
                                        <td>
                                            <span className="channel-badge" style={{ background: meta.bg, color: meta.color }}>
                                                {meta.label}
                                            </span>
                                        </td>
                                        <td style={{ textAlign: 'right' }}>{ch.allocatedPct != null ? ch.allocatedPct + '%' : '—'}</td>
                                        <td style={{ textAlign: 'right' }}>{fmtCurrency(ch.spend)}</td>
                                        <td style={{ textAlign: 'right' }}>{fmtNumber(ch.impressions)}</td>
                                        <td style={{ textAlign: 'right' }}>{fmtNumber(ch.clicks)}</td>
                                        <td style={{ textAlign: 'right' }}>{fmtNumber(ch.conversions)}</td>
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            )}
        </div>
    );
}


// ═════════════════════════════════════════════════════════════════════════════
//  SHARED COMPONENTS
// ═════════════════════════════════════════════════════════════════════════════

function KpiCard({ label, value, format = 'number' }) {
    let display = '—';
    if (value != null) {
        if (format === 'currency') display = fmtCurrency(value);
        else if (format === 'pct') display = fmtPct(value);
        else display = fmtNumber(value);
    }

    return (
        <div className="intel-kpi-card">
            <div className="intel-kpi-value">{display}</div>
            <div className="intel-kpi-label">{label}</div>
        </div>
    );
}

function StatusBadge({ status }) {
    const s = (status || '').toLowerCase();
    let className = 'status-default';
    if (s === 'active' || s === 'launched') className = 'status-active';
    else if (s === 'staged' || s === 'pending' || s === 'draft') className = 'status-pending';
    else if (s === 'paused') className = 'status-warning';
    else if (s === 'error') className = 'status-error';
    else if (s === 'completed' || s === 'ended') className = 'status-inactive';
    return <span className={`status-badge ${className}`}>{status || '—'}</span>;
}

function PacingBar({ pct, label, showLabel }) {
    const clamped = Math.min(Math.max(pct, 0), 100);
    const barColor = clamped > 95 ? '#dc2626' : clamped > 75 ? '#d97706' : '#16a34a';

    return (
        <div className="intel-pacing">
            {showLabel && label && <span className="intel-pacing-label">{label}</span>}
            <div className="intel-pacing-track">
                <div className="intel-pacing-fill" style={{ width: clamped + '%', background: barColor }} />
            </div>
            <span className="intel-pacing-pct">{clamped.toFixed(0)}%</span>
        </div>
    );
}

function EmulatedBanner() {
    return (
        <div className="intel-emulated-banner">
            <strong>Preview Mode</strong> — Showing emulated data. Deploy the <code>spAdminReporting</code> stored procedure
            and connect the metrics polling service to see live campaign data.
        </div>
    );
}


// ─── Helpers ─────────────────────────────────────────────────────────────────

function formatInsightType(type) {
    if (!type) return '';
    return type.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}


// ═════════════════════════════════════════════════════════════════════════════
//  EMULATED DATA
//  Used when the reporting API endpoints aren't connected yet.
// ═════════════════════════════════════════════════════════════════════════════

const EMULATED_SUMMARY = {
    ok: true,
    activeCampaigns: 4,
    totalSpend: 12480,
    totalImpressions: 847200,
    totalClicks: 18430,
    totalConversions: 312,
    channelBreakdown: [
        { channel: 'google_ads', campaignCount: 3, spend: 6240, impressions: 412000, clicks: 9800, conversions: 186 },
        { channel: 'meta',       campaignCount: 3, spend: 4120, impressions: 325000, clicks: 6230, conversions: 98 },
        { channel: 'tiktok',     campaignCount: 2, spend: 2120, impressions: 110200, clicks: 2400, conversions: 28 },
    ],
};

const EMULATED_CAMPAIGNS = {
    ok: true,
    totalCount: 4,
    campaigns: [
        {
            initiativeId: 1, name: 'Spring Product Launch', clientName: 'Acme Corp', objective: 'conversions',
            status: 'active', totalBudget: 5000, budgetPeriod: 'monthly', spend: 3820, impressions: 312000,
            clicks: 7200, ctr: 2.31, cpc: 0.53, conversions: 142, budgetPacing: 76.4,
            channels: [
                { channelType: 'google_ads', status: 'active', allocationPct: 50, spend: 1910, impressions: 156000, clicks: 3900, conversions: 82 },
                { channelType: 'meta', status: 'active', allocationPct: 30, spend: 1146, impressions: 112000, clicks: 2300, conversions: 42 },
                { channelType: 'tiktok', status: 'active', allocationPct: 20, spend: 764, impressions: 44000, clicks: 1000, conversions: 18 },
            ],
        },
        {
            initiativeId: 2, name: 'Brand Awareness Q1', clientName: 'TechStart Inc', objective: 'awareness',
            status: 'active', totalBudget: 3000, budgetPeriod: 'monthly', spend: 2860, impressions: 285000,
            clicks: 4800, ctr: 1.68, cpc: 0.60, conversions: 64, budgetPacing: 95.3,
            channels: [
                { channelType: 'google_ads', status: 'active', allocationPct: 40, spend: 1144, impressions: 114000, clicks: 2100, conversions: 32 },
                { channelType: 'meta', status: 'active', allocationPct: 60, spend: 1716, impressions: 171000, clicks: 2700, conversions: 32 },
            ],
        },
        {
            initiativeId: 3, name: 'Summer Sale Traffic', clientName: 'Acme Corp', objective: 'traffic',
            status: 'active', totalBudget: 4000, budgetPeriod: 'monthly', spend: 3480, impressions: 168000,
            clicks: 4230, ctr: 2.52, cpc: 0.82, conversions: 76, budgetPacing: 87.0,
            channels: [
                { channelType: 'google_ads', status: 'active', allocationPct: 60, spend: 2088, impressions: 100800, clicks: 2800, conversions: 52 },
                { channelType: 'meta', status: 'active', allocationPct: 40, spend: 1392, impressions: 67200, clicks: 1430, conversions: 24 },
            ],
        },
        {
            initiativeId: 4, name: 'TikTok Gen-Z Push', clientName: 'FreshBrand Co', objective: 'engagement',
            status: 'active', totalBudget: 2500, budgetPeriod: 'monthly', spend: 2320, impressions: 82200,
            clicks: 2200, ctr: 2.68, cpc: 1.05, conversions: 30, budgetPacing: 92.8,
            channels: [
                { channelType: 'tiktok', status: 'active', allocationPct: 70, spend: 1624, impressions: 57540, clicks: 1600, conversions: 22 },
                { channelType: 'meta', status: 'active', allocationPct: 30, spend: 696, impressions: 24660, clicks: 600, conversions: 8 },
            ],
        },
    ],
};

const EMULATED_INSIGHTS = {
    ok: true,
    totalActive: 4,
    insights: [
        {
            insightId: 1, initiativeId: 2, campaignName: 'Brand Awareness Q1', clientName: 'TechStart Inc',
            insightType: 'budget_pacing', severity: 'critical', status: 'active',
            title: 'Budget nearly exhausted — 95% spent with 8 days remaining',
            description: 'At the current spend rate of ~$102/day, the remaining $140 budget will be depleted in approximately 1.4 days. The campaign end date is 8 days away.',
            recommendation: 'Consider increasing the monthly budget to $3,800 to maintain delivery through the end date, or pause the campaign and restart next period.',
            createdAt: new Date().toISOString(),
        },
        {
            insightId: 2, initiativeId: 4, campaignName: 'TikTok Gen-Z Push', clientName: 'FreshBrand Co',
            insightType: 'underperformer', severity: 'warning', status: 'active',
            title: 'Meta channel underperforming vs. TikTok allocation',
            description: 'The Meta channel is consuming 30% of budget but delivering only 27% of conversions with a higher CPC ($1.16 vs $1.01). TikTok is outperforming on engagement metrics.',
            recommendation: 'Consider shifting 10% of Meta allocation to TikTok to improve overall conversion efficiency for this audience segment.',
            createdAt: new Date().toISOString(),
        },
        {
            insightId: 3, initiativeId: 1, campaignName: 'Spring Product Launch', clientName: 'Acme Corp',
            insightType: 'optimization', severity: 'info', status: 'active',
            title: 'Google Ads CPC trending down — opportunity to increase volume',
            description: 'Over the past 7 days, Google Ads CPC has decreased from $0.61 to $0.49 while maintaining conversion rate. This suggests room to increase daily spend cap.',
            recommendation: 'Increase Google Ads daily budget by 15% to capture additional conversions while CPC remains favorable.',
            createdAt: new Date().toISOString(),
        },
        {
            insightId: 4, initiativeId: 3, campaignName: 'Summer Sale Traffic', clientName: 'Acme Corp',
            insightType: 'reallocation', severity: 'info', status: 'active',
            title: 'Channel allocation aligns well with performance data',
            description: 'The current 60/40 Google/Meta split is delivering proportional results. Google is slightly outperforming on conversions per dollar, consistent with search-intent traffic campaigns.',
            recommendation: 'No changes recommended. Current allocation is performing within expected parameters.',
            createdAt: new Date().toISOString(),
        },
    ],
};

const EMULATED_ANALYSIS = {
    ok: true,
    campaigns: [
        {
            initiativeId: 100, name: 'Holiday Campaign 2024', clientName: 'Acme Corp', objective: 'conversions',
            totalBudget: 8000, startDate: '2024-11-15', endDate: '2024-12-31',
            totalSpend: 7640, totalImpressions: 524000, totalClicks: 12800, totalConversions: 384,
            ctr: 2.44, cpc: 0.60, costPerConversion: 19.90, budgetUtilization: 95.5,
            channels: [
                { channel: 'google_ads', allocatedPct: 50, spend: 3820, impressions: 262000, clicks: 7200, conversions: 228 },
                { channel: 'meta', allocatedPct: 35, spend: 2674, impressions: 196000, clicks: 4200, conversions: 118 },
                { channel: 'tiktok', allocatedPct: 15, spend: 1146, impressions: 66000, clicks: 1400, conversions: 38 },
            ],
        },
        {
            initiativeId: 101, name: 'Back to School Drive', clientName: 'TechStart Inc', objective: 'traffic',
            totalBudget: 3500, startDate: '2024-08-01', endDate: '2024-09-15',
            totalSpend: 3320, totalImpressions: 198000, totalClicks: 5600, totalConversions: 89,
            ctr: 2.83, cpc: 0.59, costPerConversion: 37.30, budgetUtilization: 94.9,
            channels: [
                { channel: 'google_ads', allocatedPct: 55, spend: 1826, impressions: 108900, clicks: 3200, conversions: 56 },
                { channel: 'meta', allocatedPct: 45, spend: 1494, impressions: 89100, clicks: 2400, conversions: 33 },
            ],
        },
    ],
};
