import React, { useMemo, useState, useCallback } from 'react';
import * as XLSX from 'xlsx';
import { CombinedKPIs, FilterState } from '../types';
import { DownloadIcon } from './Icons';
import { StockBadge } from './StockBadge';
import { InColumnStockFilter } from './InColumnStockFilter';

interface AdsPerformanceProps {
    data: CombinedKPIs[];
    filters: FilterState;
    top50Ranking?: {
        eu: Map<string, number>;
        uk: Map<string, number>;
    };
    stockMap?: Map<string, number>;
    stockFilter: string[];
    onStockFilterChange: (newFilters: string[]) => void;
}

type SortKey = keyof CombinedKPIs | 'acos' | 'roas' | 'tacos' | 'ctr' | 'cpc' | 'cvrUnits';

// Top 50 Badge Component
const Top50Badge: React.FC<{ rank: number; label?: string; theme?: 'amber' | 'blue' | 'indigo' }> = ({ rank, label, theme = 'amber' }) => {
    const themeClasses = {
        amber: 'from-amber-500 to-orange-500 border-amber-400/50',
        blue: 'from-blue-500 to-cyan-500 border-blue-400/50',
        indigo: 'from-indigo-500 to-purple-500 border-indigo-400/50',
    };

    return (
        <span
            className={`inline-flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] font-black bg-gradient-to-r ${themeClasses[theme]} text-white shadow-sm border`}
            title={`Top ${rank} Best Seller 2025 ${label ? `(${label})` : ''}`}
        >
            <span className="mr-0.5">🏆</span>
            {label && <span className="mr-0.5 opacity-90">{label}</span>}
            {rank}
        </span>
    );
};

const AdsPerformance: React.FC<AdsPerformanceProps> = ({ data, filters, top50Ranking, stockMap, stockFilter, onStockFilterChange }) => {
    const [searchTerm, setSearchTerm] = useState('');
    const [showOnlyTop50, setShowOnlyTop50] = useState(false);
    const [top50Mode, setTop50Mode] = useState<'eu' | 'uk'>('eu');
    const [sortConfig, setSortConfig] = useState<{ key: SortKey; direction: 'asc' | 'desc' }>({
        key: 'cost',
        direction: 'desc'
    });

    // Detect comparison mode: exactly 2 weeks, 2 months, or 2 years
    const comparisonConfig = useMemo(() => {
        let periods: string[] = [];
        let type: 'week' | 'month' | 'year' | null = null;

        if (filters.week.length === 2) {
            periods = [...filters.week].sort((a, b) => {
                const wA = parseInt(a.replace('W', ''));
                const wB = parseInt(b.replace('W', ''));
                return wA - wB;
            });
            type = 'week';
        } else if (filters.month.length === 2) {
            // Simple sort for abbreviated months might be tricky without year, 
            // but usually users pick consecutive ones.
            periods = [...filters.month];
            type = 'month';
        } else if (filters.year.length === 2) {
            periods = [...filters.year].sort();
            type = 'year';
        }

        if (type && periods.length === 2) {
            return { type, prev: periods[0], curr: periods[1] };
        }
        return null;
    }, [filters]);

    // 1. Aggregate and Compare data by ASIN
    const aggregatedByAsin = useMemo(() => {
        const map = new Map<string, { curr: CombinedKPIs; prev?: CombinedKPIs }>();

        data.forEach(item => {
            const asin = item.asin.trim().toUpperCase();
            const periodVal = comparisonConfig?.type === 'week' ? `W${item.week}` :
                comparisonConfig?.type === 'month' ? item.month :
                    comparisonConfig?.type === 'year' ? item.year.toString() : null;

            const isCurrent = !comparisonConfig || periodVal === comparisonConfig.curr;
            const isPrevious = comparisonConfig && periodVal === comparisonConfig.prev;

            if (!map.has(asin)) {
                // Initialize with empty record if it's new
                const defaultRec: CombinedKPIs = { ...item, salesTotal: 0, unitsTotal: 0, salesAds: 0, unitsAds: 0, cost: 0, clicks: 0, impressions: 0, conversions: 0, salesOrganic: 0 };
                map.set(asin, {
                    curr: isCurrent ? { ...item } : { ...defaultRec },
                    prev: isPrevious ? { ...item } : undefined
                });
            } else {
                const entry = map.get(asin)!;
                const target = isCurrent ? entry.curr : (isPrevious ? (entry.prev || (entry.prev = { ...item, salesTotal: 0, unitsTotal: 0, salesAds: 0, unitsAds: 0, cost: 0, clicks: 0, impressions: 0, conversions: 0, salesOrganic: 0 })) : null);

                if (target) {
                    target.salesTotal += item.salesTotal;
                    target.unitsTotal += item.unitsTotal;
                    target.salesAds += item.salesAds;
                    target.unitsAds += item.unitsAds;
                    target.cost += item.cost;
                    target.clicks += item.clicks;
                    target.impressions += item.impressions;
                    target.conversions += item.conversions;
                    target.salesOrganic += item.salesOrganic;
                    target.glanceViews = (target.glanceViews || 0) + (item.glanceViews || 0);
                }
            }
        });

        return Array.from(map.values()).map(({ curr, prev }) => {
            const calcMetrics = (item: CombinedKPIs) => ({
                ...item,
                acos: item.salesAds > 0 ? (item.cost / item.salesAds) * 100 : 0,
                tacos: item.salesTotal > 0 ? (item.cost / item.salesTotal) * 100 : 0,
                roas: item.cost > 0 ? item.salesAds / item.cost : 0,
                ctr: item.impressions > 0 ? (item.clicks / item.impressions) * 100 : 0,
                cpc: item.clicks > 0 ? item.cost / item.clicks : 0,
                cvrUnits: item.clicks > 0 ? (item.conversions / item.clicks) * 100 : 0,
            });

            const currFinal = calcMetrics(curr);
            const prevFinal = prev ? calcMetrics(prev) : undefined;

            return {
                ...currFinal,
                prevData: prevFinal
            };
        });
    }, [data, comparisonConfig]);

    // 2. Global Totals
    const totals = useMemo(() => {
        const sum = (items: any[]) => items.reduce((acc, curr) => ({
            salesTotal: acc.salesTotal + curr.salesTotal,
            salesAds: acc.salesAds + curr.salesAds,
            salesOrganic: acc.salesOrganic + curr.salesOrganic,
            cost: acc.cost + curr.cost,
            impressions: acc.impressions + curr.impressions,
            clicks: acc.clicks + curr.clicks,
            conversions: acc.conversions + curr.conversions,
            glanceViews: acc.glanceViews + (curr.glanceViews || 0),
        }), { salesTotal: 0, salesAds: 0, salesOrganic: 0, cost: 0, impressions: 0, clicks: 0, conversions: 0, glanceViews: 0 });

        const currTotals = sum(aggregatedByAsin);
        const prevTotals = comparisonConfig ? sum(aggregatedByAsin.map(a => a.prevData).filter(Boolean)) : null;

        return { curr: currTotals, prev: prevTotals };
    }, [aggregatedByAsin, comparisonConfig]);

    const calculateDerived = (t: any) => ({
        acos: t.salesAds > 0 ? (t.cost / t.salesAds) * 100 : 0,
        tacos: t.salesTotal > 0 ? (t.cost / t.salesTotal) * 100 : 0,
        roas: t.cost > 0 ? t.salesAds / t.cost : 0,
        ctr: t.impressions > 0 ? (t.clicks / t.impressions) * 100 : 0,
        cpc: t.clicks > 0 ? t.cost / t.clicks : 0,
        cvr: t.clicks > 0 ? (t.conversions / t.clicks) * 100 : 0,
        cvrGv: t.glanceViews > 0 ? (t.conversions / t.glanceViews) * 100 : 0,
    });

    const currMetrics = calculateDerived(totals.curr);
    const prevMetrics = totals.prev ? calculateDerived(totals.prev) : null;

    // 3. Filter and Sort
    const filteredAndSorted = useMemo(() => {
        let result = aggregatedByAsin;

        // Top 50 Filter
        if (showOnlyTop50 && top50Ranking) {
            result = result.filter(item => {
                const asin = item.asin.trim().toUpperCase();
                if (top50Mode === 'eu') {
                    return top50Ranking.eu.has(asin);
                } else {
                    return top50Ranking.uk.has(asin);
                }
            });
        }

        // Search Filter
        result = result.filter(item =>
            item.asin.toLowerCase().includes(searchTerm.toLowerCase()) ||
            item.sku.toLowerCase().includes(searchTerm.toLowerCase()) ||
            item.title.toLowerCase().includes(searchTerm.toLowerCase())
        );

        // Sort: by ranking when Top 50 is active, otherwise by sortConfig
        if (showOnlyTop50 && top50Ranking) {
            result.sort((a, b) => {
                const asinA = a.asin.trim().toUpperCase();
                const asinB = b.asin.trim().toUpperCase();
                const rankA = top50Mode === 'eu'
                    ? (top50Ranking.eu.get(asinA) || 999)
                    : (top50Ranking.uk.get(asinA) || 999);
                const rankB = top50Mode === 'eu'
                    ? (top50Ranking.eu.get(asinB) || 999)
                    : (top50Ranking.uk.get(asinB) || 999);
                return rankA - rankB;
            });
        } else {
            result.sort((a, b) => {
                const valA = a[sortConfig.key] as number;
                const valB = b[sortConfig.key] as number;
                return sortConfig.direction === 'asc' ? valA - valB : valB - valA;
            });
        }

        return result;
    }, [aggregatedByAsin, searchTerm, sortConfig, showOnlyTop50, top50Ranking, top50Mode]);

    const handleSort = (key: SortKey) => {
        setSortConfig(prev => ({
            key,
            direction: prev.key === key && prev.direction === 'desc' ? 'asc' : 'desc'
        }));
    };

    const handleExportExcel = useCallback(() => {
        const exportData = filteredAndSorted.map(row => {
            const rowData: any = {
                ASIN: row.asin,
                SKU: row.sku,
                Title: row.title,
                'Total Sales': Math.round(row.salesTotal),
                'Ads Sales': Math.round(row.salesAds),
                'Organic Sales': Math.round(row.salesOrganic),
                'Ad Spend': Math.round(row.cost),
                Impressions: row.impressions,
                Clicks: row.clicks,
                Orders: row.conversions,
                CPC: Number(row.cpc.toFixed(2)),
                'CTR (%)': Number(row.ctr.toFixed(2)),
                'CVR (%)': Number(row.cvrUnits.toFixed(2)),
                'ACOS (%)': Number(row.acos.toFixed(2)),
                ROAS: Number(row.roas.toFixed(2)),
                'TACOS (%)': Number(row.tacos.toFixed(2)),
                'Glance Views': row.glanceViews || 0,
            };

            if (row.prevData) {
                rowData['Prev Total Sales'] = Math.round(row.prevData.salesTotal);
                rowData['Prev Ads Sales'] = Math.round(row.prevData.salesAds);
                rowData['Prev Ad Spend'] = Math.round(row.prevData.cost);
                rowData['Growth Sales (%)'] = row.prevData.salesTotal > 0 ? Number((((row.salesTotal - row.prevData.salesTotal) / row.prevData.salesTotal) * 100).toFixed(1)) : 0;
            }

            return rowData;
        });

        const ws = XLSX.utils.json_to_sheet(exportData);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Ads Performance');
        XLSX.writeFile(wb, `Ads_Performance_Export_${new Date().toISOString().slice(0, 10)}.xlsx`);
    }, [filteredAndSorted]);

    const formatCurrency = (val: number) =>
        `$${Math.round(val).toLocaleString('de-DE')}`;

    const formatNumber = (val: number) =>
        Math.round(val).toLocaleString('de-DE');

    const formatPercent = (val: number) =>
        `${val.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}%`;

    return (
        <div className="flex flex-col gap-6 animate-fade-in p-6 bg-[#0B0E14] min-h-screen text-slate-300">
            {/* Header */}
            <div className="flex justify-between items-end">
                <div>
                    <h1 className="text-2xl font-bold text-white mb-1">Performance Overview</h1>
                    <div className="flex items-center gap-2 text-xs text-slate-400">
                        <span className="w-2 h-2 rounded-full bg-emerald-500"></span>
                        <span>
                            {aggregatedByAsin.length} products •
                            {comparisonConfig ? ` Comparison: ${comparisonConfig.prev} vs ${comparisonConfig.curr}` : ' Direct Overview'}
                        </span>
                    </div>
                </div>
            </div>

            {/* Summary Grid */}
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 xl:grid-cols-13 gap-4 bg-[#141820] p-4 rounded-xl border border-white/5 shadow-xl">
                <SummaryCard label="TOTAL SALES" value={totals.curr.salesTotal} prevValue={totals.prev?.salesTotal} format="currency" color="text-emerald-400" />
                <SummaryCard label="ADS SALES" value={totals.curr.salesAds} prevValue={totals.prev?.salesAds} format="currency" color="text-orange-400" />
                <SummaryCard label="ORGANIC SALES" value={totals.curr.salesOrganic} prevValue={totals.prev?.salesOrganic} format="currency" color="text-blue-400" />
                <SummaryCard label="AD SPEND" value={totals.curr.cost} prevValue={totals.prev?.cost} format="currency" color="text-indigo-400" />
                <SummaryCard label="IMPR." value={totals.curr.impressions} prevValue={totals.prev?.impressions} format="number" />
                <SummaryCard label="CLICKS" value={totals.curr.clicks} prevValue={totals.prev?.clicks} format="number" />
                <SummaryCard label="ADS ORDERS" value={totals.curr.conversions} prevValue={totals.prev?.conversions} format="number" />
                <SummaryCard label="CPC" value={currMetrics.cpc} prevValue={prevMetrics?.cpc} format="number" prefix="$" decimals={2} inverse />
                <SummaryCard label="CTR" value={currMetrics.ctr} prevValue={prevMetrics?.ctr} format="percent" />
                <SummaryCard label="CVR" value={currMetrics.cvr} prevValue={prevMetrics?.cvr} format="percent" />
                <SummaryCard label="ACOS" value={currMetrics.acos} prevValue={prevMetrics?.acos} format="percent" inverse />
                <SummaryCard label="ROAS" value={currMetrics.roas} prevValue={prevMetrics?.roas} format="number" decimals={2} color="text-blue-300" />
                <SummaryCard label="TACOS" value={currMetrics.tacos} prevValue={prevMetrics?.tacos} format="percent" inverse />
                <SummaryCard label="GV" value={totals.curr.glanceViews} prevValue={totals.prev?.glanceViews} format="number" color="text-teal-400" />
                <SummaryCard label="CVR (GV)" value={currMetrics.cvrGv} prevValue={prevMetrics?.cvrGv} format="percent" color="text-teal-300" />
            </div>

            {/* Table Section */}
            <div className="bg-[#141820] rounded-xl border border-white/10 overflow-hidden shadow-2xl flex-1 flex flex-col">
                <div className="p-4 border-b border-white/5 flex justify-between items-center bg-[#1A1F29]">
                    <div>
                        <h2 className="text-sm font-bold text-white uppercase tracking-wider">Product Inventory</h2>
                        <p className="text-[10px] text-slate-400 mt-0.5">
                            {comparisonConfig ? `Comparing ${comparisonConfig.curr} vs ${comparisonConfig.prev}` : 'Displaying total data for selected filters.'}
                        </p>
                    </div>
                    <div className="flex items-center gap-4">
                        {/* Top 50 Filter Toggle */}
                        {top50Ranking && (
                            (top50Ranking.eu.size || 0) > 0 ||
                            (top50Ranking.uk.size || 0) > 0
                        ) && (
                                <div className="flex bg-slate-950/50 p-1 rounded-xl border border-white/10 shadow-sm">
                                    <button
                                        onClick={() => setShowOnlyTop50(!showOnlyTop50)}
                                        className={`flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-bold transition-all ${showOnlyTop50
                                            ? 'bg-gradient-to-r from-amber-500 to-orange-500 text-white shadow-lg shadow-amber-500/20'
                                            : 'text-slate-400 hover:text-amber-400'
                                            }`}
                                    >
                                        <span className="text-sm">🏆</span>
                                        Top 50
                                    </button>

                                    {showOnlyTop50 && (
                                        <div className="flex ml-1 p-0.5 bg-slate-900 rounded-lg border border-white/5">
                                            <button
                                                onClick={() => setTop50Mode('eu')}
                                                className={`px-2 py-1 rounded-md text-[10px] font-black uppercase tracking-widest transition-all ${top50Mode === 'eu' ? 'bg-indigo-500 text-white shadow-sm' : 'text-slate-500 hover:text-slate-300'}`}
                                            >
                                                EU
                                            </button>
                                            <button
                                                onClick={() => setTop50Mode('uk')}
                                                className={`px-2 py-1 rounded-md text-[10px] font-black uppercase tracking-widest transition-all ${top50Mode === 'uk' ? 'bg-blue-500 text-white shadow-sm' : 'text-slate-500 hover:text-slate-300'}`}
                                            >
                                                UK
                                            </button>
                                        </div>
                                    )}
                                </div>
                            )}
                        <input
                            type="text"
                            placeholder="Search..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="bg-[#0B0E14] border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white focus:outline-none focus:ring-1 focus:ring-indigo-500 w-48"
                        />
                        <button
                            onClick={handleExportExcel}
                            className="flex items-center gap-2 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 text-slate-200 rounded-lg text-xs font-bold border border-white/10 transition-all shadow-lg active:scale-95"
                            title="Export to Excel"
                        >
                            <DownloadIcon />
                            <span>Export</span>
                        </button>
                    </div>
                </div>

                <div className="overflow-x-auto flex-1 custom-scrollbar">
                    <table className="w-full text-left border-collapse text-[11px]">
                        <thead className="sticky top-0 z-20 bg-[#1A1F29] shadow-sm">
                            <tr className="border-b border-white/5">
                                <th className="p-4 font-black text-slate-400 uppercase tracking-widest min-w-[250px]">
                                    <div className="flex items-center gap-2">
                                        <span>PRODUCT</span>
                                        <InColumnStockFilter
                                            currentFilters={stockFilter}
                                            onFilterChange={onStockFilterChange}
                                        />
                                    </div>
                                </th>
                                <SortableHeader label="TOTAL SALES" sortKey="salesTotal" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="ADS SALES" sortKey="salesAds" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="ORGANIC SALES" sortKey="salesOrganic" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="AD SPEND" sortKey="cost" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="IMPR." sortKey="impressions" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="CLICKS" sortKey="clicks" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="ADS ORDERS" sortKey="conversions" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="CPC" sortKey="cpc" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="CTR" sortKey="ctr" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="CVR" sortKey="cvrUnits" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="ACOS" sortKey="acos" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="ROAS" sortKey="roas" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="TACOS" sortKey="tacos" activeSort={sortConfig} onSort={handleSort} />
                                <SortableHeader label="GV" sortKey="glanceViews" activeSort={sortConfig} onSort={handleSort} />
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-white/[0.03]">
                            {filteredAndSorted.map((row: any) => {
                                const asin = row.asin.trim().toUpperCase();
                                const ranks: { rank: number; label: string; theme: 'amber' | 'blue' | 'indigo' }[] = [];

                                if (top50Ranking) {
                                    const euRank = top50Ranking.eu.get(asin);
                                    const ukRank = top50Ranking.uk.get(asin);
                                    if (euRank) ranks.push({ rank: euRank, label: 'EU', theme: 'indigo' });
                                    if (ukRank) ranks.push({ rank: ukRank, label: 'UK', theme: 'blue' });
                                }

                                return (
                                    <tr key={row.id} className="hover:bg-white/[0.02] transition-colors group">
                                        <td className="p-4 py-3">
                                            <div className="flex flex-col gap-0.5">
                                                <div className="flex items-center gap-2">
                                                    {ranks.map((r, i) => (
                                                        <Top50Badge key={i} rank={r.rank} label={r.label} theme={r.theme} />
                                                    ))}
                                                    <span className="text-white font-bold text-sm tracking-tight">{row.asin}</span>
                                                </div>
                                                <span className="text-[10px] uppercase font-black text-indigo-400 tracking-tighter">SKU: {row.sku}</span>
                                                <div className="flex items-start gap-2">
                                                    <span className="text-[10px] text-slate-400 truncate max-w-[200px] leading-tight" title={row.title}>{row.title}</span>
                                                    {stockMap && (
                                                        <StockBadge stock={stockMap.get(row.sku?.replace(/(DE|EN)$/i, ''))} />
                                                    )}
                                                </div>
                                            </div>
                                        </td>
                                        <TableCell value={row.salesTotal} prevValue={row.prevData?.salesTotal} format="currency" />
                                        <TableCell value={row.salesAds} prevValue={row.prevData?.salesAds} format="currency" />
                                        <TableCell value={row.salesOrganic} prevValue={row.prevData?.salesOrganic} format="currency" />
                                        <TableCell value={row.cost} prevValue={row.prevData?.cost} format="currency" />
                                        <TableCell value={row.impressions} prevValue={row.prevData?.impressions} format="number" />
                                        <TableCell value={row.clicks} prevValue={row.prevData?.clicks} format="number" />
                                        <TableCell value={row.conversions} prevValue={row.prevData?.conversions} format="number" />
                                        <TableCell value={row.cpc} prevValue={row.prevData?.cpc} format="number" prefix="$" inverse />
                                        <TableCell value={row.ctr} prevValue={row.prevData?.ctr} format="percent" />
                                        <TableCell value={row.cvrUnits} prevValue={row.prevData?.cvrUnits} format="percent" />
                                        <TableCell value={row.acos} prevValue={row.prevData?.acos} format="percent" inverse />
                                        <TableCell value={row.roas} prevValue={row.prevData?.roas} format="number" highlight />
                                        <TableCell value={row.tacos} prevValue={row.prevData?.tacos} format="percent" inverse />
                                        <TableCell value={row.glanceViews || 0} prevValue={row.prevData?.glanceViews} format="number" />
                                    </tr>
                                );
                            })}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
};

const SummaryCard = ({
    label,
    value,
    prevValue,
    format,
    prefix = "",
    decimals = 0,
    color = "text-white",
    inverse = false
}: {
    label: string;
    value: number;
    prevValue?: number;
    format: 'currency' | 'number' | 'percent';
    prefix?: string;
    decimals?: number;
    color?: string;
    inverse?: boolean
}) => {
    const growth = prevValue !== undefined && prevValue > 0
        ? ((value - prevValue) / prevValue) * 100
        : null;

    const formatVal = (v: number) => {
        if (format === 'currency') return `$${Math.round(v).toLocaleString('de-DE')}`;
        if (format === 'percent') return v.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "%";
        return prefix + v.toLocaleString('de-DE', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
    };

    return (
        <div className="flex flex-col items-center justify-center p-2 border-r last:border-r-0 border-white/5 w-full min-w-[80px]">
            <span className={`${color} text-[10px] font-black tracking-widest mb-1 text-center leading-tight uppercase`}>{label}</span>
            <div className="flex flex-col items-center">
                <span className="text-sm font-bold text-white transition-all">{formatVal(value)}</span>
                {prevValue !== undefined && (
                    <div className="flex flex-col items-center mt-0.5">
                        <span className="text-[9px] text-slate-400 font-medium whitespace-nowrap">
                            Prev: <span className="text-indigo-300 font-bold">{formatVal(prevValue)}</span>
                        </span>
                        {growth !== null && (
                            <span className={`text-[9px] font-black ${(growth > 0 ? !inverse : inverse) ? 'text-emerald-400' : 'text-rose-500'}`}>
                                {growth > 0 ? '↑' : '↓'} {Math.abs(growth).toFixed(1)}%
                            </span>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
};

const TableCell = ({ value, prevValue, format, prefix = "", inverse = false, highlight = false }: { value: number; prevValue?: number; format: 'currency' | 'number' | 'percent'; prefix?: string; inverse?: boolean; highlight?: boolean }) => {
    const growth = prevValue !== undefined && prevValue > 0 ? ((value - prevValue) / prevValue) * 100 : null;

    const formatVal = (v: number) => {
        if (format === 'currency') return Math.round(v).toLocaleString('de-DE');
        if (format === 'number') {
            if (prefix === "$") {
                return "$" + v.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            } else {
                return prefix + Math.round(v).toLocaleString('de-DE');
            }
        }
        return v.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + "%";
    };

    return (
        <td className="p-4 text-right">
            <div className="flex flex-col items-end">
                <span className={`font-bold ${highlight ? 'text-blue-300' : 'text-white'}`}>{formatVal(value)}</span>
                {prevValue !== undefined && (
                    <div className="flex flex-col items-end scale-[0.85] origin-right opacity-80 mt-0.5">
                        <span className="text-[9px] text-slate-400 font-medium whitespace-nowrap">
                            Prev: <span className="text-indigo-300 font-bold">{formatVal(prevValue)}</span>
                        </span>
                        {growth !== null && (
                            <span className={`text-[10px] font-black ${(growth > 0 ? !inverse : inverse) ? 'text-emerald-400' : 'text-rose-400'}`}>
                                {growth > 0 ? '+' : ''}{growth.toFixed(1)}%
                            </span>
                        )}
                    </div>
                )}
            </div>
        </td>
    );
}

const SortableHeader = ({ label, sortKey, activeSort, onSort }: {
    label: string;
    sortKey: SortKey;
    activeSort: { key: SortKey; direction: 'asc' | 'desc' };
    onSort: (key: SortKey) => void;
}) => {
    const isActive = activeSort.key === sortKey;
    return (
        <th
            onClick={() => onSort(sortKey)}
            className={`p-4 font-black text-slate-400 uppercase tracking-widest text-right cursor-pointer hover:text-white transition-colors group min-w-[100px] whitespace-nowrap`}
        >
            <div className="flex items-center justify-end gap-1.5">
                <span className="text-[10px]">{label}</span>
                <span className={`text-[10px] flex flex-col leading-[0.5] transition-opacity ${isActive ? 'opacity-100' : 'opacity-0 group-hover:opacity-40'}`}>
                    <span className={isActive && activeSort.direction === 'asc' ? 'text-indigo-400' : ''}>▴</span>
                    <span className={isActive && activeSort.direction === 'desc' ? 'text-indigo-400' : ''}>▾</span>
                </span>
            </div>
        </th>
    );
};

export default AdsPerformance;
