"use client";

import { useState } from "react";
import Link from "next/link";
import {
    BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
    LineChart, Line, PieChart, Pie, Cell, Legend, AreaChart, Area
} from "recharts";
import {
    ArrowLeft, TrendingUp, TrendingDown, Users, Clock, AlertTriangle,
    CheckCircle2, Target, BarChart3, Filter, Zap, Globe, ChevronRight,
    ArrowUpRight, ArrowDownRight, Minus
} from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

// ─── Types ──────────────────────────────────────────────
interface KPIs {
    totalApplicants: number;
    activeCandidates: number;
    hiredThisMonth: number;
    avgTimeToHire: number;
    conversionRate: number;
    inInterview: number;
}

interface FunnelStage {
    name: string;
    color: string;
    currentCount: number;
    totalPassed: number;
    order: number;
}

interface TimeMetric {
    stage: string;
    color: string;
    order: number;
    avgDays: number;
    minDays: number;
    maxDays: number;
    count: number;
}

interface Bottleneck {
    stageName: string;
    stageColor: string;
    pipelineName: string;
    candidatesStuck: number;
    avgDaysStuck: number;
    severity: "low" | "medium" | "high" | "critical";
}

interface Source {
    source: string;
    total: number;
    hired: number;
    rejected: number;
    active: number;
    conversionRate: number;
    avgTimeToHire: number | null;
}

interface DropOff {
    total: number;
    breakdown: Array<{ status: string; count: number; percentage: number }>;
    withdrawnCount: number;
    withdrawnRate: number;
}

interface TrendPoint {
    month: string;
    applications: number;
    hired: number;
    rejected: number;
}

interface AnalyticsClientProps {
    kpis: KPIs | null;
    funnel: FunnelStage[];
    timeMetrics: TimeMetric[];
    bottlenecks: Bottleneck[];
    sources: Source[];
    dropOff: DropOff | null;
    trend: TrendPoint[];
}

// ─── Constants ──────────────────────────────────────────
const TABS = ["overview", "funnel", "time", "bottlenecks", "sources", "trends"] as const;
type Tab = (typeof TABS)[number];

const TAB_LABELS: Record<Tab, string> = {
    overview: "Overview",
    funnel: "Conversion Funnel",
    time: "Time Metrics",
    bottlenecks: "Bottlenecks",
    sources: "Source Analysis",
    trends: "Trends",
};

const PIE_COLORS = ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6", "#ec4899", "#06b6d4"];

const STATUS_LABELS: Record<string, string> = {
    pending: "Pending",
    reviewing: "Reviewing",
    interview: "Interview",
    offered: "Offered",
    hired: "Hired",
    rejected: "Rejected",
};

const SEVERITY_STYLES: Record<string, string> = {
    critical: "bg-red-100 text-red-700 border-red-200",
    high: "bg-orange-100 text-orange-700 border-orange-200",
    medium: "bg-yellow-100 text-yellow-700 border-yellow-200",
    low: "bg-slate-100 text-slate-600 border-slate-200",
};

// ─── Component ──────────────────────────────────────────
export function AnalyticsClient({ kpis, funnel, timeMetrics, bottlenecks, sources, dropOff, trend }: AnalyticsClientProps) {
    const [activeTab, setActiveTab] = useState<Tab>("overview");

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <Link
                        href="/dashboard/ats"
                        className="p-2 rounded-lg hover:bg-slate-100 text-slate-500 transition-colors"
                    >
                        <ArrowLeft className="h-5 w-5" />
                    </Link>
                    <div>
                        <h1 className="text-2xl font-bold text-slate-900">Pipeline Analytics</h1>
                        <p className="text-sm text-slate-500">Data-driven insights into your hiring process</p>
                    </div>
                </div>
            </div>

            {/* KPI Cards */}
            {kpis && <KPICards kpis={kpis} />}

            {/* Tab Navigation */}
            <div className="flex gap-1 p-1 rounded-xl bg-slate-100 overflow-x-auto">
                {TABS.map(tab => (
                    <button
                        key={tab}
                        onClick={() => setActiveTab(tab)}
                        className={`flex-shrink-0 px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === tab
                            ? "bg-white text-slate-900 shadow-sm"
                            : "text-slate-500 hover:text-slate-700"
                            }`}
                    >
                        {TAB_LABELS[tab]}
                    </button>
                ))}
            </div>

            {/* Tab Content */}
            <AnimatePresence mode="wait">
                <motion.div
                    key={activeTab}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    transition={{ duration: 0.2 }}
                >
                    {activeTab === "overview" && (
                        <OverviewTab funnel={funnel} timeMetrics={timeMetrics} bottlenecks={bottlenecks} trend={trend} />
                    )}
                    {activeTab === "funnel" && <FunnelTab funnel={funnel} />}
                    {activeTab === "time" && <TimeTab timeMetrics={timeMetrics} />}
                    {activeTab === "bottlenecks" && <BottleneckTab bottlenecks={bottlenecks} />}
                    {activeTab === "sources" && <SourceTab sources={sources} />}
                    {activeTab === "trends" && <TrendTab trend={trend} dropOff={dropOff} />}
                </motion.div>
            </AnimatePresence>
        </div>
    );
}

// ─── KPI Cards ──────────────────────────────────────────
function KPICards({ kpis }: { kpis: KPIs }) {
    const cards = [
        {
            label: "Total Applicants",
            value: kpis.totalApplicants,
            icon: Users,
            color: "text-blue-600 bg-blue-100",
        },
        {
            label: "Conversion Rate",
            value: `${kpis.conversionRate}%`,
            icon: Target,
            color: "text-green-600 bg-green-100",
        },
        {
            label: "Avg Time to Hire",
            value: kpis.avgTimeToHire > 0 ? `${kpis.avgTimeToHire}d` : "N/A",
            icon: Clock,
            color: "text-amber-600 bg-amber-100",
        },
        {
            label: "Hired This Month",
            value: kpis.hiredThisMonth,
            icon: CheckCircle2,
            color: "text-emerald-600 bg-emerald-100",
        },
        {
            label: "Active Candidates",
            value: kpis.activeCandidates,
            icon: Zap,
            color: "text-purple-600 bg-purple-100",
        },
        {
            label: "In Interview",
            value: kpis.inInterview,
            icon: BarChart3,
            color: "text-indigo-600 bg-indigo-100",
        },
    ];

    return (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {cards.map((card, i) => (
                <motion.div
                    key={card.label}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: i * 0.05 }}
                    className="bg-white rounded-xl border border-slate-200 p-4 hover:shadow-md transition-shadow"
                >
                    <div className={`h-9 w-9 rounded-lg flex items-center justify-center mb-3 ${card.color}`}>
                        <card.icon className="h-5 w-5" />
                    </div>
                    <p className="text-2xl font-bold text-slate-900">{card.value}</p>
                    <p className="text-xs text-slate-500 mt-0.5">{card.label}</p>
                </motion.div>
            ))}
        </div>
    );
}

// ─── Overview Tab ───────────────────────────────────────
function OverviewTab({ funnel, timeMetrics, bottlenecks, trend }: {
    funnel: FunnelStage[];
    timeMetrics: TimeMetric[];
    bottlenecks: Bottleneck[];
    trend: TrendPoint[];
}) {
    return (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Mini Funnel */}
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-sm font-semibold text-slate-700 mb-4 flex items-center gap-2">
                    <Filter className="h-4 w-4 text-blue-500" /> Conversion Funnel
                </h3>
                {funnel.length > 0 ? (
                    <div className="space-y-2">
                        {funnel.map((stage, i) => {
                            const maxPassed = Math.max(...funnel.map(s => s.totalPassed), 1);
                            const widthPct = Math.max((stage.totalPassed / maxPassed) * 100, 8);
                            return (
                                <div key={i} className="flex items-center gap-3">
                                    <span className="text-xs text-slate-500 w-28 truncate text-right">{stage.name}</span>
                                    <div className="flex-1 h-7 bg-slate-50 rounded-lg overflow-hidden">
                                        <motion.div
                                            initial={{ width: 0 }}
                                            animate={{ width: `${widthPct}%` }}
                                            transition={{ delay: i * 0.1, duration: 0.5 }}
                                            className="h-full rounded-lg flex items-center px-2"
                                            style={{ backgroundColor: stage.color + "30" }}
                                        >
                                            <span className="text-xs font-semibold" style={{ color: stage.color }}>{stage.totalPassed}</span>
                                        </motion.div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                ) : (
                    <EmptyState message="No funnel data yet" />
                )}
            </div>

            {/* Mini Trend Chart */}
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-sm font-semibold text-slate-700 mb-4 flex items-center gap-2">
                    <TrendingUp className="h-4 w-4 text-green-500" /> Hiring Trend (6 Months)
                </h3>
                {trend.length > 0 ? (
                    <ResponsiveContainer width="100%" height={200}>
                        <AreaChart data={trend}>
                            <defs>
                                <linearGradient id="colorApps" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.15} />
                                    <stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
                                </linearGradient>
                                <linearGradient id="colorHired" x1="0" y1="0" x2="0" y2="1">
                                    <stop offset="5%" stopColor="#10b981" stopOpacity={0.15} />
                                    <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
                                </linearGradient>
                            </defs>
                            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                            <XAxis dataKey="month" tick={{ fontSize: 11, fill: "#94a3b8" }} />
                            <YAxis tick={{ fontSize: 11, fill: "#94a3b8" }} />
                            <Tooltip contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0" }} />
                            <Area type="monotone" dataKey="applications" stroke="#3b82f6" fill="url(#colorApps)" strokeWidth={2} />
                            <Area type="monotone" dataKey="hired" stroke="#10b981" fill="url(#colorHired)" strokeWidth={2} />
                        </AreaChart>
                    </ResponsiveContainer>
                ) : (
                    <EmptyState message="No trend data yet" />
                )}
            </div>

            {/* Time-in-Stage */}
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-sm font-semibold text-slate-700 mb-4 flex items-center gap-2">
                    <Clock className="h-4 w-4 text-amber-500" /> Avg Days per Stage
                </h3>
                {timeMetrics.length > 0 ? (
                    <ResponsiveContainer width="100%" height={200}>
                        <BarChart data={timeMetrics} layout="vertical">
                            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                            <XAxis type="number" tick={{ fontSize: 11, fill: "#94a3b8" }} />
                            <YAxis dataKey="stage" type="category" tick={{ fontSize: 11, fill: "#64748b" }} width={100} />
                            <Tooltip contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0" }} />
                            <Bar dataKey="avgDays" radius={[0, 6, 6, 0]}>
                                {timeMetrics.map((entry, idx) => (
                                    <Cell key={idx} fill={entry.color} fillOpacity={0.7} />
                                ))}
                            </Bar>
                        </BarChart>
                    </ResponsiveContainer>
                ) : (
                    <EmptyState message="No time data yet" />
                )}
            </div>

            {/* Active Bottlenecks */}
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-sm font-semibold text-slate-700 mb-4 flex items-center gap-2">
                    <AlertTriangle className="h-4 w-4 text-red-500" /> Active Bottlenecks
                </h3>
                {bottlenecks.length > 0 ? (
                    <div className="space-y-2">
                        {bottlenecks.slice(0, 4).map((b, i) => (
                            <div key={i} className={`flex items-center justify-between p-3 rounded-lg border ${SEVERITY_STYLES[b.severity]}`}>
                                <div className="flex items-center gap-2">
                                    <div className="h-3 w-3 rounded-full" style={{ backgroundColor: b.stageColor }} />
                                    <span className="text-sm font-medium">{b.stageName}</span>
                                </div>
                                <div className="text-right">
                                    <span className="text-xs font-semibold">{b.candidatesStuck} stuck</span>
                                    <span className="text-xs ml-2">~{b.avgDaysStuck}d avg</span>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div className="flex flex-col items-center py-8 text-center">
                        <CheckCircle2 className="h-10 w-10 text-green-400 mb-2" />
                        <p className="text-sm text-slate-500">No bottlenecks detected!</p>
                        <p className="text-xs text-slate-400">Your pipeline is flowing smoothly</p>
                    </div>
                )}
            </div>
        </div>
    );
}

// ─── Funnel Tab ─────────────────────────────────────────
function FunnelTab({ funnel }: { funnel: FunnelStage[] }) {
    if (funnel.length === 0) return <EmptyState message="No pipeline data available yet. Candidates need to be in your hiring stages." />;

    const maxPassed = Math.max(...funnel.map(s => s.totalPassed), 1);

    return (
        <div className="bg-white rounded-xl border border-slate-200 p-6 space-y-6">
            <h3 className="text-lg font-semibold text-slate-800">Conversion Funnel</h3>
            <p className="text-sm text-slate-500">How candidates flow through each stage of your pipeline</p>

            {/* Visual Funnel */}
            <div className="max-w-xl mx-auto space-y-1">
                {funnel.map((stage, i) => {
                    const widthPct = Math.max((stage.totalPassed / maxPassed) * 100, 15);
                    const nextPassed = funnel[i + 1]?.totalPassed ?? 0;
                    const convRate = stage.totalPassed > 0 && i < funnel.length - 1
                        ? Math.round((nextPassed / stage.totalPassed) * 100)
                        : null;

                    return (
                        <div key={i} className="relative">
                            <motion.div
                                initial={{ width: 0 }}
                                animate={{ width: `${widthPct}%` }}
                                transition={{ delay: i * 0.12, duration: 0.6, ease: "easeOut" }}
                                className="mx-auto h-12 rounded-lg flex items-center justify-between px-4 cursor-default hover:scale-[1.01] transition-transform"
                                style={{
                                    backgroundColor: stage.color + "20",
                                    borderLeft: `4px solid ${stage.color}`,
                                }}
                            >
                                <span className="text-sm font-medium text-slate-700">{stage.name}</span>
                                <div className="flex items-center gap-3">
                                    <span className="text-sm font-bold" style={{ color: stage.color }}>
                                        {stage.totalPassed}
                                    </span>
                                    <span className="text-xs text-slate-400">
                                        ({stage.currentCount} active)
                                    </span>
                                </div>
                            </motion.div>
                            {convRate !== null && (
                                <div className="text-center py-0.5">
                                    <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${convRate >= 50 ? "bg-green-100 text-green-700" :
                                        convRate >= 25 ? "bg-amber-100 text-amber-700" :
                                            "bg-red-100 text-red-700"
                                        }`}>
                                        {convRate}% →
                                    </span>
                                </div>
                            )}
                        </div>
                    );
                })}
            </div>

            {/* Summary Table */}
            <div className="mt-8">
                <table className="w-full text-sm">
                    <thead>
                        <tr className="border-b border-slate-200">
                            <th className="text-left py-2 text-slate-500 font-medium">Stage</th>
                            <th className="text-right py-2 text-slate-500 font-medium">Total Passed</th>
                            <th className="text-right py-2 text-slate-500 font-medium">Currently In</th>
                            <th className="text-right py-2 text-slate-500 font-medium">Conversion</th>
                        </tr>
                    </thead>
                    <tbody>
                        {funnel.map((stage, i) => {
                            const nextPassed = funnel[i + 1]?.totalPassed ?? 0;
                            const convRate = stage.totalPassed > 0 && i < funnel.length - 1
                                ? Math.round((nextPassed / stage.totalPassed) * 100)
                                : null;
                            return (
                                <tr key={i} className="border-b border-slate-100">
                                    <td className="py-2.5 flex items-center gap-2">
                                        <div className="h-3 w-3 rounded-full" style={{ backgroundColor: stage.color }} />
                                        {stage.name}
                                    </td>
                                    <td className="text-right font-medium">{stage.totalPassed}</td>
                                    <td className="text-right text-slate-500">{stage.currentCount}</td>
                                    <td className="text-right">
                                        {convRate !== null ? (
                                            <span className={
                                                convRate >= 50 ? "text-green-600" :
                                                    convRate >= 25 ? "text-amber-600" : "text-red-600"
                                            }>{convRate}%</span>
                                        ) : <span className="text-slate-400">—</span>}
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

// ─── Time Tab ───────────────────────────────────────────
function TimeTab({ timeMetrics }: { timeMetrics: TimeMetric[] }) {
    if (timeMetrics.length === 0) return <EmptyState message="No time-in-stage data yet. Move candidates through stages to see timing analytics." />;

    return (
        <div className="space-y-6">
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-lg font-semibold text-slate-800 mb-1">Time-in-Stage Analysis</h3>
                <p className="text-sm text-slate-500 mb-6">Average days candidates spend in each stage</p>

                <ResponsiveContainer width="100%" height={350}>
                    <BarChart data={timeMetrics}>
                        <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                        <XAxis dataKey="stage" tick={{ fontSize: 12, fill: "#64748b" }} />
                        <YAxis tick={{ fontSize: 12, fill: "#94a3b8" }} label={{ value: "Days", angle: -90, position: "insideLeft", style: { fontSize: 11, fill: "#94a3b8" } }} />
                        <Tooltip
                            contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0" }}
                            formatter={(value: any) => [`${value} days`, "Average"]}
                        />
                        <Bar dataKey="avgDays" radius={[6, 6, 0, 0]}>
                            {timeMetrics.map((entry, idx) => (
                                <Cell key={idx} fill={entry.color} fillOpacity={0.75} />
                            ))}
                        </Bar>
                    </BarChart>
                </ResponsiveContainer>
            </div>

            {/* Detail Table */}
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <table className="w-full text-sm">
                    <thead>
                        <tr className="border-b border-slate-200">
                            <th className="text-left py-2 text-slate-500">Stage</th>
                            <th className="text-right py-2 text-slate-500">Avg Days</th>
                            <th className="text-right py-2 text-slate-500">Min</th>
                            <th className="text-right py-2 text-slate-500">Max</th>
                            <th className="text-right py-2 text-slate-500">Candidates</th>
                        </tr>
                    </thead>
                    <tbody>
                        {timeMetrics.map((m, i) => (
                            <tr key={i} className="border-b border-slate-100">
                                <td className="py-2.5 flex items-center gap-2">
                                    <div className="h-3 w-3 rounded-full" style={{ backgroundColor: m.color }} />
                                    {m.stage}
                                </td>
                                <td className="text-right font-semibold">{m.avgDays}d</td>
                                <td className="text-right text-slate-500">{m.minDays}d</td>
                                <td className="text-right text-slate-500">{m.maxDays}d</td>
                                <td className="text-right text-slate-500">{m.count}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

// ─── Bottleneck Tab ─────────────────────────────────────
function BottleneckTab({ bottlenecks }: { bottlenecks: Bottleneck[] }) {
    if (bottlenecks.length === 0) {
        return (
            <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
                <CheckCircle2 className="h-16 w-16 text-green-400 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-slate-800">No Bottlenecks Detected</h3>
                <p className="text-sm text-slate-500 mt-1">Your pipeline is flowing smoothly. Candidates are moving through stages on time.</p>
            </div>
        );
    }

    return (
        <div className="space-y-4">
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-lg font-semibold text-slate-800 mb-1">Bottleneck Report</h3>
                <p className="text-sm text-slate-500 mb-6">Stages where candidates are taking longer than expected</p>

                {bottlenecks.map((b, i) => (
                    <motion.div
                        key={i}
                        initial={{ opacity: 0, x: -20 }}
                        animate={{ opacity: 1, x: 0 }}
                        transition={{ delay: i * 0.08 }}
                        className={`p-4 rounded-xl border mb-3 ${SEVERITY_STYLES[b.severity]}`}
                    >
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <AlertTriangle className="h-5 w-5" />
                                <div>
                                    <p className="font-semibold">{b.stageName}</p>
                                    <p className="text-xs opacity-80">{b.pipelineName}</p>
                                </div>
                            </div>
                            <div className="text-right">
                                <p className="text-lg font-bold">{b.candidatesStuck}</p>
                                <p className="text-xs">candidates stuck</p>
                            </div>
                        </div>
                        <div className="mt-3 flex items-center gap-4 text-xs">
                            <span>Avg delay: <strong>{b.avgDaysStuck} days</strong></span>
                            <span className="px-2 py-0.5 rounded-full bg-white/50 font-semibold uppercase tracking-wider text-[10px]">
                                {b.severity}
                            </span>
                        </div>
                    </motion.div>
                ))}
            </div>
        </div>
    );
}

// ─── Source Tab ──────────────────────────────────────────
function SourceTab({ sources }: { sources: Source[] }) {
    if (sources.length === 0) return <EmptyState message="No source data available. Candidates need a 'source' field to track effectiveness." />;

    return (
        <div className="space-y-6">
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-lg font-semibold text-slate-800 mb-1">Source Effectiveness</h3>
                <p className="text-sm text-slate-500 mb-6">Which candidate sources produce the best hires</p>

                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    {/* Pie Chart */}
                    <ResponsiveContainer width="100%" height={280}>
                        <PieChart>
                            <Pie
                                data={sources}
                                dataKey="total"
                                nameKey="source"
                                cx="50%"
                                cy="50%"
                                outerRadius={100}
                                innerRadius={50}
                                label={({ name, percent }: any) => `${name} (${((percent ?? 0) * 100).toFixed(0)}%)`}
                                labelLine={false}
                            >
                                {sources.map((_, idx) => (
                                    <Cell key={idx} fill={PIE_COLORS[idx % PIE_COLORS.length]} />
                                ))}
                            </Pie>
                            <Tooltip contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0" }} />
                        </PieChart>
                    </ResponsiveContainer>

                    {/* Table */}
                    <div>
                        <table className="w-full text-sm">
                            <thead>
                                <tr className="border-b border-slate-200">
                                    <th className="text-left py-2 text-slate-500">Source</th>
                                    <th className="text-right py-2 text-slate-500">Volume</th>
                                    <th className="text-right py-2 text-slate-500">Hired</th>
                                    <th className="text-right py-2 text-slate-500">Conv %</th>
                                </tr>
                            </thead>
                            <tbody>
                                {sources.map((s, i) => (
                                    <tr key={i} className="border-b border-slate-100">
                                        <td className="py-2.5 flex items-center gap-2">
                                            <div className="h-3 w-3 rounded-full" style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length] }} />
                                            {s.source}
                                        </td>
                                        <td className="text-right">{s.total}</td>
                                        <td className="text-right font-medium text-green-600">{s.hired}</td>
                                        <td className="text-right">
                                            <span className={s.conversionRate >= 5 ? "text-green-600" : s.conversionRate >= 2 ? "text-amber-600" : "text-slate-500"}>
                                                {s.conversionRate}%
                                            </span>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    );
}

// ─── Trend Tab ──────────────────────────────────────────
function TrendTab({ trend, dropOff }: { trend: TrendPoint[]; dropOff: DropOff | null }) {
    return (
        <div className="space-y-6">
            {/* Trend Chart */}
            <div className="bg-white rounded-xl border border-slate-200 p-6">
                <h3 className="text-lg font-semibold text-slate-800 mb-1">Hiring Trend</h3>
                <p className="text-sm text-slate-500 mb-6">Applications and hires over the last 6 months</p>

                {trend.length > 0 ? (
                    <ResponsiveContainer width="100%" height={320}>
                        <LineChart data={trend}>
                            <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                            <XAxis dataKey="month" tick={{ fontSize: 12, fill: "#64748b" }} />
                            <YAxis tick={{ fontSize: 12, fill: "#94a3b8" }} />
                            <Tooltip contentStyle={{ borderRadius: "12px", border: "1px solid #e2e8f0" }} />
                            <Legend />
                            <Line type="monotone" dataKey="applications" stroke="#3b82f6" strokeWidth={2.5} dot={{ r: 4, fill: "#3b82f6" }} />
                            <Line type="monotone" dataKey="hired" stroke="#10b981" strokeWidth={2.5} dot={{ r: 4, fill: "#10b981" }} />
                            <Line type="monotone" dataKey="rejected" stroke="#ef4444" strokeWidth={2} strokeDasharray="5 5" dot={{ r: 3, fill: "#ef4444" }} />
                        </LineChart>
                    </ResponsiveContainer>
                ) : (
                    <EmptyState message="No trend data yet" />
                )}
            </div>

            {/* Drop-off Breakdown */}
            {dropOff && dropOff.total > 0 && (
                <div className="bg-white rounded-xl border border-slate-200 p-6">
                    <h3 className="text-lg font-semibold text-slate-800 mb-1">Application Status Breakdown</h3>
                    <p className="text-sm text-slate-500 mb-6">Distribution of {dropOff.total} total applications</p>

                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
                        {dropOff.breakdown.map((item, i) => (
                            <div key={i} className="bg-slate-50 rounded-lg p-3 text-center">
                                <p className="text-lg font-bold text-slate-800">{item.count}</p>
                                <p className="text-xs text-slate-500">{STATUS_LABELS[item.status] || item.status}</p>
                                <p className="text-xs text-slate-400 mt-0.5">{item.percentage}%</p>
                            </div>
                        ))}
                    </div>

                    {dropOff.withdrawnCount > 0 && (
                        <div className="mt-4 p-3 rounded-lg bg-amber-50 border border-amber-200 text-sm text-amber-700">
                            ⚠️ {dropOff.withdrawnCount} candidate{dropOff.withdrawnCount > 1 ? "s" : ""} withdrew ({dropOff.withdrawnRate}%)
                        </div>
                    )}
                </div>
            )}
        </div>
    );
}

// ─── Empty State ────────────────────────────────────────
function EmptyState({ message }: { message: string }) {
    return (
        <div className="flex flex-col items-center py-12 text-center bg-white rounded-xl border border-slate-200">
            <BarChart3 className="h-12 w-12 text-slate-300 mb-3" />
            <p className="text-sm text-slate-500">{message}</p>
        </div>
    );
}
