"use client";

import { useMemo, useState, type ReactNode } from "react";
import Link from "next/link";
import { motion, AnimatePresence } from "motion/react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  Legend,
} from "recharts";
import {
  ArrowLeft,
  BarChart3,
  Building2,
  CalendarCheck,
  ChevronRight,
  Clock,
  TrendingDown,
  TrendingUp,
  Users,
  UserRound,
  Briefcase,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { DatePicker } from "@/components/ui/date-picker";
import { AppSpinner } from "@/components/ui/app-loader";
import { easeOutExpo, staggerContainer, staggerItem } from "@/lib/motion";
import { useManagerAnalytics } from "@/hooks/use-manager-analytics";
import { AnalyticsChartTooltip } from "@/components/ui/analytics-chart-tooltip";
import { DesignationPerformancePanel } from "@/components/dashboard/designation-performance";
import { cn } from "@/lib/utils";
import { DASHBOARD_DEFAULT_DATE_FROM, DASHBOARD_DEFAULT_DATE_TO } from "@/lib/date-utils";

const CHART_COLORS = [
  "hsl(var(--chart-1))",
  "hsl(var(--chart-2))",
  "hsl(var(--chart-3))",
  "hsl(var(--chart-4))",
  "hsl(var(--chart-5))",
];

type Level = "overview" | "department" | "lead" | "designation";

type DrillState = {
  level: Level;
  department?: string;
  leadId?: string;
  leadName?: string;
  position?: string;
};

function ChartCard({
  title,
  subtitle,
  children,
  className,
}: {
  title: string;
  subtitle?: string;
  children: ReactNode;
  className?: string;
}) {
  return (
    <motion.section
      variants={staggerItem}
      className={cn(
        "rounded-xl border border-border bg-card overflow-visible",
        className,
      )}
    >
      <div className="px-4 py-3 border-b border-border">
        <h3 className="text-sm font-semibold text-foreground">{title}</h3>
        {subtitle ? (
          <p className="text-xs text-muted-foreground mt-0.5">{subtitle}</p>
        ) : null}
      </div>
      <div className="p-4 overflow-visible">{children}</div>
    </motion.section>
  );
}

function ScoreCard({
  label,
  value,
  hint,
  icon,
  tone = "default",
}: {
  label: string;
  value: string;
  hint?: string;
  icon: ReactNode;
  tone?: "default" | "good" | "warn";
}) {
  return (
    <div className="rounded-xl border border-border bg-card p-4">
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-xs text-muted-foreground">{label}</p>
          <p
            className={cn(
              "mt-1 text-2xl font-semibold tabular-nums tracking-tight",
              tone === "good" && "text-emerald-600 dark:text-emerald-300",
              tone === "warn" && "text-amber-600 dark:text-amber-300",
              tone === "default" && "text-foreground",
            )}
          >
            {value}
          </p>
          {hint ? (
            <p className="mt-1 text-xs text-muted-foreground">{hint}</p>
          ) : null}
        </div>
        <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
          {icon}
        </div>
      </div>
    </div>
  );
}

function performanceTone(score: number) {
  if (score >= 80) return "good" as const;
  if (score > 0 && score < 70) return "warn" as const;
  return "default" as const;
}

function RankingCard({
  title,
  items,
  onSelect,
}: {
  title: string;
  items: { key: string; label: string; score: number; meta?: string }[];
  onSelect?: (key: string) => void;
}) {
  return (
    <ChartCard title={title}>
      {items.length === 0 ? (
        <p className="text-sm text-muted-foreground py-6 text-center">
          No scored groups in this period.
        </p>
      ) : (
        <ul className="space-y-2">
          {items.map((item, i) => (
            <li key={item.key}>
              <button
                type="button"
                onClick={() => onSelect?.(item.key)}
                disabled={!onSelect}
                className={cn(
                  "w-full flex items-center gap-3 rounded-lg border border-border px-3 py-2.5 text-left transition-colors",
                  onSelect && "hover:bg-muted/60 cursor-pointer",
                  !onSelect && "cursor-default",
                )}
              >
                <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-primary/10 text-xs font-semibold text-primary">
                  {i + 1}
                </span>
                <span className="min-w-0 flex-1">
                  <span className="block truncate text-sm font-medium text-foreground">
                    {item.label}
                  </span>
                  {item.meta ? (
                    <span className="block truncate text-xs text-muted-foreground">
                      {item.meta}
                    </span>
                  ) : null}
                </span>
                <span
                  className={cn(
                    "text-sm font-semibold tabular-nums",
                    performanceTone(item.score) === "good" &&
                      "text-emerald-600 dark:text-emerald-300",
                    performanceTone(item.score) === "warn" &&
                      "text-amber-600 dark:text-amber-300",
                  )}
                >
                  {item.score.toFixed(1)}
                </span>
                {onSelect ? (
                  <ChevronRight className="h-4 w-4 text-muted-foreground" />
                ) : null}
              </button>
            </li>
          ))}
        </ul>
      )}
    </ChartCard>
  );
}

export function ManagerAnalytics() {
  const [dateFrom, setDateFrom] = useState(DASHBOARD_DEFAULT_DATE_FROM);
  const [dateTo, setDateTo] = useState(DASHBOARD_DEFAULT_DATE_TO);
  const [drill, setDrill] = useState<DrillState>({ level: "overview" });
  const { data, loading, error, reload } = useManagerAnalytics(
    dateFrom,
    dateTo,
  );

  const departmentLeads = useMemo(() => {
    if (!data || !drill.department) return [];
    return data.byLead.filter(
      (l) =>
        l.departments?.includes(drill.department) ||
        l.lead?.department === drill.department,
    );
  }, [data, drill.department]);

  const leadDesignations = useMemo(() => {
    if (!data || !drill.leadId) return [];
    const lead = data.byLead.find((l) => l.key === drill.leadId);
    if (!lead) return [];
    const memberIdSet = new Set(lead.memberIds || []);
    const positions = new Set(
      data.employees
        .filter((e) => memberIdSet.has(e.id))
        .map((e) => (e.position || "").trim())
        .filter(Boolean),
    );
    return data.byDesignation.filter((d) => positions.has(d.key));
  }, [data, drill.leadId]);

  const designationEmployees = useMemo(() => {
    if (!data || !drill.position || !drill.leadId) return [];
    const lead = data.byLead.find((l) => l.key === drill.leadId);
    const memberIdSet = new Set(lead?.memberIds || []);
    return data.employees
      .filter(
        (e) =>
          memberIdSet.has(e.id) && (e.position || "").trim() === drill.position,
      )
      .sort((a, b) => b.overallScore - a.overallScore);
  }, [data, drill.position, drill.leadId]);

  const designationPeople = useMemo(() => {
    if (!data) return [];
    return data.employees
      .filter((e) => e.hasData && e.role !== "MANAGER")
      .map((e) => ({
        id: e.id,
        name: e.name,
        position: e.position,
        overallScore: e.overallScore,
        grade: e.grade,
        totalHours: e.totalHours,
        hasData: e.hasData,
      }));
  }, [data]);

  const breadcrumbs = useMemo(() => {
    const crumbs: { label: string; onClick?: () => void }[] = [
      {
        label: "Analytics",
        onClick: () => setDrill({ level: "overview" }),
      },
    ];
    if (drill.department) {
      crumbs.push({
        label: drill.department,
        onClick: () =>
          setDrill({ level: "department", department: drill.department }),
      });
    }
    if (drill.leadId && drill.leadName) {
      crumbs.push({
        label: drill.leadName,
        onClick: () =>
          setDrill({
            level: "lead",
            department: drill.department,
            leadId: drill.leadId,
            leadName: drill.leadName,
          }),
      });
    }
    if (drill.position) {
      crumbs.push({ label: drill.position });
    }
    return crumbs;
  }, [drill]);

  if (loading && !data) {
    return (
      <div className="flex min-h-[50vh] flex-col items-center justify-center gap-3">
        <AppSpinner className="h-6 w-6 text-primary" />
        <p className="text-sm text-muted-foreground">
          Building manager analytics…
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-xl border border-border bg-card p-8 text-center space-y-3">
        <BarChart3 className="mx-auto h-8 w-8 text-muted-foreground" />
        <p className="text-sm text-muted-foreground">{error}</p>
        <Button onClick={reload} variant="outline" size="sm">
          Try again
        </Button>
      </div>
    );
  }

  if (!data) return null;

  const deptChart = data.byDepartment.map((d) => ({
    name: d.label.length > 14 ? `${d.label.slice(0, 12)}…` : d.label,
    fullName: d.label,
    overall: d.avgOverall,
    attendance: d.avgAttendance,
    headcount: d.headcount,
  }));

  const performanceHealth = (() => {
    const buckets = {
      strong: {
        key: "strong",
        label: "Strong (80+)",
        count: 0,
        fill: "hsl(142 50% 42%)",
      },
      onTrack: {
        key: "onTrack",
        label: "On track (70–79)",
        count: 0,
        fill: CHART_COLORS[0],
      },
      coaching: {
        key: "coaching",
        label: "Needs coaching (60–69)",
        count: 0,
        fill: "hsl(38 80% 48%)",
      },
      atRisk: {
        key: "atRisk",
        label: "At risk (<60)",
        count: 0,
        fill: "hsl(0 62% 50%)",
      },
    };
    for (const e of data.employees.filter((x) => x.hasData)) {
      const s = e.overallScore;
      if (s >= 80) buckets.strong.count += 1;
      else if (s >= 70) buckets.onTrack.count += 1;
      else if (s >= 60) buckets.coaching.count += 1;
      else buckets.atRisk.count += 1;
    }
    const total = Object.values(buckets).reduce((s, b) => s + b.count, 0) || 1;
    return Object.values(buckets).map((b) => ({
      ...b,
      pct: Math.round((b.count / total) * 1000) / 10,
    }));
  })();

  return (
    <div className="space-y-5">
      <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
        <div className="space-y-2 min-w-0">
          <div className="flex items-center gap-2 text-xs text-muted-foreground flex-wrap">
            {breadcrumbs.map((crumb, i) => (
              <span
                key={`${crumb.label}-${i}`}
                className="inline-flex items-center gap-2"
              >
                {i > 0 ? <ChevronRight className="h-3.5 w-3.5" /> : null}
                {crumb.onClick ? (
                  <button
                    type="button"
                    onClick={crumb.onClick}
                    className="hover:text-foreground transition-colors"
                  >
                    {crumb.label}
                  </button>
                ) : (
                  <span className="text-foreground font-medium">
                    {crumb.label}
                  </span>
                )}
              </span>
            ))}
          </div>
          <div>
            <h1 className="text-xl font-semibold tracking-tight text-foreground">
              Manager Analytics
            </h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              Scoped to{" "}
              {data.meta.managedDepartments.length
                ? data.meta.managedDepartments.join(", ")
                : "your managed teams"}
              . Drill Department → Team Lead → Designation → People.
            </p>
          </div>
        </div>

        <div className="flex flex-wrap items-center gap-2">
          {drill.level !== "overview" ? (
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                if (drill.level === "designation") {
                  setDrill({
                    level: "lead",
                    department: drill.department,
                    leadId: drill.leadId,
                    leadName: drill.leadName,
                  });
                } else if (drill.level === "lead") {
                  setDrill({
                    level: "department",
                    department: drill.department,
                  });
                } else {
                  setDrill({ level: "overview" });
                }
              }}
            >
              <ArrowLeft className="h-4 w-4 mr-1.5" />
              Back
            </Button>
          ) : null}
          <DatePicker value={dateFrom} onChange={setDateFrom} max={dateTo} />
          <span className="text-xs text-muted-foreground">to</span>
          <DatePicker value={dateTo} onChange={setDateTo} min={dateFrom} />
          {loading ? <AppSpinner className="h-4 w-4 text-primary" /> : null}
        </div>
      </div>

      <AnimatePresence mode="wait">
        <motion.div
          key={
            drill.level +
            (drill.department || "") +
            (drill.leadId || "") +
            (drill.position || "")
          }
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          exit={{ opacity: 0, y: -6 }}
          transition={{ duration: 0.25, ease: easeOutExpo }}
          className="space-y-5"
        >
          {drill.level === "overview" && (
            <motion.div
              variants={staggerContainer}
              initial="initial"
              animate="animate"
              className="space-y-5"
            >
              <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                <ScoreCard
                  label="Avg overall"
                  value={data.overview.avgOverall.toFixed(1)}
                  hint={`${data.overview.scoredCount} scored of ${data.overview.headcount}`}
                  icon={<TrendingUp className="h-4 w-4" />}
                  tone={performanceTone(data.overview.avgOverall)}
                />
                <ScoreCard
                  label="Attendance"
                  value={`${data.overview.avgAttendance.toFixed(1)}%`}
                  hint="Average present rate"
                  icon={<CalendarCheck className="h-4 w-4" />}
                />
                <ScoreCard
                  label="Hours logged"
                  value={`${data.overview.totalHours.toFixed(0)}h`}
                  hint={`${data.overview.hoursUtilization.toFixed(0)}% of expected`}
                  icon={<Clock className="h-4 w-4" />}
                />
                <ScoreCard
                  label="Departments"
                  value={String(data.overview.departmentCount)}
                  hint={`${data.overview.leadCount} team leads`}
                  icon={<Building2 className="h-4 w-4" />}
                />
              </div>

              <div className="grid gap-4 xl:grid-cols-3">
                <ChartCard
                  title="Department performance"
                  subtitle="Click a department to drill in"
                  className="xl:col-span-2"
                >
                  {deptChart.length === 0 ? (
                    <p className="text-sm text-muted-foreground py-10 text-center">
                      No department data in range.
                    </p>
                  ) : (
                    <div className="h-72">
                      <ResponsiveContainer width="100%" height="100%">
                        <BarChart
                          data={deptChart}
                          margin={{ top: 8, right: 8, left: 0, bottom: 8 }}
                        >
                          <CartesianGrid
                            strokeDasharray="3 3"
                            className="stroke-border"
                          />
                          <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                          <YAxis domain={[0, 100]} tick={{ fontSize: 11 }} />
                          <Tooltip
                            content={
                              <AnalyticsChartTooltip
                                labelFormatter={(_, payload) =>
                                  String(payload?.[0]?.payload?.fullName || "")
                                }
                                valueFormatter={(v) =>
                                  typeof v === "number" ? v.toFixed(1) : v
                                }
                              />
                            }
                          />
                          <Legend />
                          <Bar
                            dataKey="overall"
                            name="Overall"
                            fill={CHART_COLORS[0]}
                            radius={[6, 6, 0, 0]}
                            cursor="pointer"
                            onClick={(entry: any) => {
                              const full =
                                entry?.payload?.fullName || entry?.fullName;
                              if (full) {
                                setDrill({
                                  level: "department",
                                  department: full,
                                });
                              }
                            }}
                          />
                          <Bar
                            dataKey="attendance"
                            name="Attendance"
                            fill={CHART_COLORS[1]}
                            radius={[6, 6, 0, 0]}
                          />
                        </BarChart>
                      </ResponsiveContainer>
                    </div>
                  )}
                </ChartCard>

                <ChartCard
                  title="Performance health"
                  subtitle="How many people are strong, on track, need coaching, or at risk"
                >
                  {performanceHealth.every((b) => b.count === 0) ? (
                    <p className="text-sm text-muted-foreground py-10 text-center">
                      No scored employees yet.
                    </p>
                  ) : (
                    <div className="space-y-4 py-2">
                      <div className="flex h-4 w-full overflow-hidden rounded-full bg-muted">
                        {performanceHealth
                          .filter((b) => b.count > 0)
                          .map((b) => (
                            <div
                              key={b.key}
                              className="h-full"
                              style={{
                                width: `${b.pct}%`,
                                backgroundColor: b.fill,
                              }}
                              title={`${b.label}: ${b.count}`}
                            />
                          ))}
                      </div>
                      <ul className="space-y-2">
                        {performanceHealth.map((b) => (
                          <li
                            key={b.key}
                            className="flex items-center justify-between rounded-lg border border-border px-3 py-2 text-sm"
                          >
                            <span className="inline-flex items-center gap-2">
                              <span
                                className="h-2.5 w-2.5 rounded-sm"
                                style={{ backgroundColor: b.fill }}
                              />
                              {b.label}
                            </span>
                            <span className="font-semibold tabular-nums">
                              {b.count}{" "}
                              <span className="font-normal text-muted-foreground">
                                ({b.pct}%)
                              </span>
                            </span>
                          </li>
                        ))}
                      </ul>
                      <p className="text-xs text-muted-foreground">
                        Prioritize coaching for At risk and Needs coaching
                        groups first.
                      </p>
                    </div>
                  )}
                </ChartCard>
              </div>

              <div className="grid gap-4 lg:grid-cols-2">
                <RankingCard
                  title="High-performing departments"
                  items={data.overview.highPerformingDepartments.map((d) => ({
                    key: d.key,
                    label: d.label,
                    score: d.avgOverall,
                    meta: `${d.headcount} people · ${d.scoredCount} scored`,
                  }))}
                  onSelect={(key) =>
                    setDrill({ level: "department", department: key })
                  }
                />
                <RankingCard
                  title="Departments needing attention"
                  items={data.overview.underperformingDepartments.map((d) => ({
                    key: d.key,
                    label: d.label,
                    score: d.avgOverall,
                    meta: `${d.headcount} people · ${d.scoredCount} scored`,
                  }))}
                  onSelect={(key) =>
                    setDrill({ level: "department", department: key })
                  }
                />
              </div>

              <div className="grid gap-4 lg:grid-cols-2">
                <RankingCard
                  title="Top performers"
                  items={data.overview.topPerformers.map((e) => ({
                    key: e.id,
                    label: e.name,
                    score: e.overallScore,
                    meta: `${e.position || "—"} · ${e.department || "—"}`,
                  }))}
                />
                <RankingCard
                  title="Needs attention"
                  items={data.overview.needsAttention.map((e) => ({
                    key: e.id,
                    label: e.name,
                    score: e.overallScore,
                    meta: e.alerts?.[0] || e.position || "—",
                  }))}
                />
              </div>

              <motion.div variants={staggerItem}>
                <DesignationPerformancePanel people={designationPeople} />
              </motion.div>

              <ChartCard
                title="Departments"
                subtitle="Select a department to compare team leads"
              >
                <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                  {data.byDepartment.map((d) => (
                    <button
                      key={d.key}
                      type="button"
                      onClick={() =>
                        setDrill({ level: "department", department: d.key })
                      }
                      className="rounded-xl border border-border p-4 text-left hover:bg-muted/50 transition-colors"
                    >
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <p className="font-medium text-foreground truncate">
                            {d.label}
                          </p>
                          <p className="text-xs text-muted-foreground mt-0.5">
                            {d.headcount} people
                          </p>
                        </div>
                        <Badge variant="outline" className="tabular-nums">
                          {d.avgOverall.toFixed(1)}
                        </Badge>
                      </div>
                      <div className="mt-3 h-1.5 rounded-full bg-muted overflow-hidden">
                        <div
                          className="h-full rounded-full bg-primary"
                          style={{
                            width: `${Math.min(100, d.avgOverall)}%`,
                          }}
                        />
                      </div>
                    </button>
                  ))}
                </div>
              </ChartCard>
            </motion.div>
          )}

          {drill.level === "department" && drill.department && (
            <motion.div
              variants={staggerContainer}
              initial="initial"
              animate="animate"
              className="space-y-5"
            >
              {(() => {
                const dept = data.byDepartment.find(
                  (d) => d.key === drill.department,
                );
                if (!dept) {
                  return (
                    <p className="text-sm text-muted-foreground">
                      Department not found in scope.
                    </p>
                  );
                }
                const leadChart = departmentLeads.map((l) => ({
                  name: l.lead.name.split(" ")[0],
                  fullName: l.lead.name,
                  id: l.key,
                  overall: l.avgOverall,
                  attendance: l.avgAttendance,
                  members: l.headcount,
                }));
                return (
                  <>
                    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                      <ScoreCard
                        label="Department overall"
                        value={dept.avgOverall.toFixed(1)}
                        icon={<TrendingUp className="h-4 w-4" />}
                        tone={performanceTone(dept.avgOverall)}
                      />
                      <ScoreCard
                        label="Attendance"
                        value={`${dept.avgAttendance.toFixed(1)}%`}
                        icon={<CalendarCheck className="h-4 w-4" />}
                      />
                      <ScoreCard
                        label="Hours"
                        value={`${dept.totalHours.toFixed(0)}h`}
                        hint={`${dept.hoursUtilization.toFixed(0)}% utilization`}
                        icon={<Clock className="h-4 w-4" />}
                      />
                      <ScoreCard
                        label="Team leads"
                        value={String(departmentLeads.length)}
                        hint={`${dept.headcount} people`}
                        icon={<Users className="h-4 w-4" />}
                      />
                    </div>

                    <ChartCard
                      title="Team lead comparison"
                      subtitle={`Leads with people in ${drill.department}`}
                    >
                      {leadChart.length === 0 ? (
                        <p className="text-sm text-muted-foreground py-10 text-center">
                          No team leads found for this department.
                        </p>
                      ) : (
                        <div className="h-72">
                          <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={leadChart}>
                              <CartesianGrid
                                strokeDasharray="3 3"
                                className="stroke-border"
                              />
                              <XAxis dataKey="name" tick={{ fontSize: 11 }} />
                              <YAxis
                                domain={[0, 100]}
                                tick={{ fontSize: 11 }}
                              />
                              <Tooltip
                                content={
                                  <AnalyticsChartTooltip
                                    labelFormatter={(_, p) =>
                                      String(p?.[0]?.payload?.fullName || "")
                                    }
                                    valueFormatter={(v) =>
                                      typeof v === "number" ? v.toFixed(1) : v
                                    }
                                  />
                                }
                              />
                              <Bar
                                dataKey="overall"
                                fill={CHART_COLORS[0]}
                                radius={[6, 6, 0, 0]}
                                cursor="pointer"
                                onClick={(entry: any) => {
                                  const id = entry?.payload?.id;
                                  const name = entry?.payload?.fullName;
                                  if (id) {
                                    setDrill({
                                      level: "lead",
                                      department: drill.department,
                                      leadId: id,
                                      leadName: name,
                                    });
                                  }
                                }}
                              />
                            </BarChart>
                          </ResponsiveContainer>
                        </div>
                      )}
                    </ChartCard>

                    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                      {departmentLeads.map((l) => (
                        <button
                          key={l.key}
                          type="button"
                          onClick={() =>
                            setDrill({
                              level: "lead",
                              department: drill.department,
                              leadId: l.key,
                              leadName: l.lead.name,
                            })
                          }
                          className="rounded-xl border border-border p-4 text-left hover:bg-muted/50 transition-colors"
                        >
                          <div className="flex items-start justify-between gap-2">
                            <div className="min-w-0">
                              <p className="font-medium truncate">
                                {l.lead.name}
                              </p>
                              <p className="text-xs text-muted-foreground mt-0.5 truncate">
                                {l.lead.position || "Team Lead"} · {l.headcount}{" "}
                                people
                              </p>
                            </div>
                            <Badge variant="outline" className="tabular-nums">
                              {l.avgOverall.toFixed(1)}
                            </Badge>
                          </div>
                          <div className="mt-3 flex gap-3 text-xs text-muted-foreground">
                            <span className="inline-flex items-center gap-1">
                              <CalendarCheck className="h-3.5 w-3.5" />
                              {l.avgAttendance.toFixed(0)}%
                            </span>
                            <span className="inline-flex items-center gap-1">
                              <Clock className="h-3.5 w-3.5" />
                              {l.totalHours.toFixed(0)}h
                            </span>
                          </div>
                        </button>
                      ))}
                    </div>
                  </>
                );
              })()}
            </motion.div>
          )}

          {drill.level === "lead" && drill.leadId && (
            <motion.div
              variants={staggerContainer}
              initial="initial"
              animate="animate"
              className="space-y-5"
            >
              {(() => {
                const lead = data.byLead.find((l) => l.key === drill.leadId);
                if (!lead) {
                  return (
                    <p className="text-sm text-muted-foreground">
                      Team lead not found in scope.
                    </p>
                  );
                }
                const desChart = leadDesignations.map((d) => ({
                  name:
                    d.label.length > 16 ? `${d.label.slice(0, 14)}…` : d.label,
                  fullName: d.label,
                  key: d.key,
                  overall: d.avgOverall,
                  headcount: d.headcount,
                }));
                return (
                  <>
                    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                      <ScoreCard
                        label="Team overall"
                        value={lead.avgOverall.toFixed(1)}
                        icon={<UserRound className="h-4 w-4" />}
                        tone={performanceTone(lead.avgOverall)}
                      />
                      <ScoreCard
                        label="Attendance"
                        value={`${lead.avgAttendance.toFixed(1)}%`}
                        icon={<CalendarCheck className="h-4 w-4" />}
                      />
                      <ScoreCard
                        label="Hours"
                        value={`${lead.totalHours.toFixed(0)}h`}
                        icon={<Clock className="h-4 w-4" />}
                      />
                      <ScoreCard
                        label="Designations"
                        value={String(leadDesignations.length)}
                        hint={`${lead.headcount} on team`}
                        icon={<Briefcase className="h-4 w-4" />}
                      />
                    </div>

                    <ChartCard
                      title="Designation performance"
                      subtitle="Click a designation to see people"
                    >
                      {desChart.length === 0 ? (
                        <p className="text-sm text-muted-foreground py-10 text-center">
                          No designations on this team.
                        </p>
                      ) : (
                        <div className="h-72">
                          <ResponsiveContainer width="100%" height="100%">
                            <BarChart data={desChart} layout="vertical">
                              <CartesianGrid
                                strokeDasharray="3 3"
                                className="stroke-border"
                              />
                              <XAxis
                                type="number"
                                domain={[0, 100]}
                                tick={{ fontSize: 11 }}
                              />
                              <YAxis
                                type="category"
                                dataKey="name"
                                width={110}
                                tick={{ fontSize: 11 }}
                              />
                              <Tooltip
                                content={
                                  <AnalyticsChartTooltip
                                    labelFormatter={(_, p) =>
                                      String(p?.[0]?.payload?.fullName || "")
                                    }
                                    valueFormatter={(v) =>
                                      typeof v === "number" ? v.toFixed(1) : v
                                    }
                                  />
                                }
                              />
                              <Bar
                                dataKey="overall"
                                fill={CHART_COLORS[2]}
                                radius={[0, 6, 6, 0]}
                                cursor="pointer"
                                onClick={(entry: any) => {
                                  const key = entry?.payload?.key;
                                  if (key) {
                                    setDrill({
                                      level: "designation",
                                      department: drill.department,
                                      leadId: drill.leadId,
                                      leadName: drill.leadName,
                                      position: key,
                                    });
                                  }
                                }}
                              />
                            </BarChart>
                          </ResponsiveContainer>
                        </div>
                      )}
                    </ChartCard>

                    <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
                      {leadDesignations.map((d) => (
                        <button
                          key={d.key}
                          type="button"
                          onClick={() =>
                            setDrill({
                              level: "designation",
                              department: drill.department,
                              leadId: drill.leadId,
                              leadName: drill.leadName,
                              position: d.key,
                            })
                          }
                          className="rounded-xl border border-border p-4 text-left hover:bg-muted/50 transition-colors"
                        >
                          <div className="flex items-start justify-between gap-2">
                            <div className="min-w-0">
                              <p className="font-medium truncate">{d.label}</p>
                              <p className="text-xs text-muted-foreground mt-0.5">
                                {d.headcount} people · {d.scoredCount} scored
                              </p>
                            </div>
                            <Badge variant="outline" className="tabular-nums">
                              {d.avgOverall.toFixed(1)}
                            </Badge>
                          </div>
                        </button>
                      ))}
                    </div>

                    {lead.needsAttention?.length > 0 ? (
                      <RankingCard
                        title="Team members needing attention"
                        items={lead.needsAttention.map((e: any) => ({
                          key: e.id,
                          label: e.name,
                          score: e.score,
                          meta: e.alerts?.[0] || "Needs review",
                        }))}
                      />
                    ) : null}
                  </>
                );
              })()}
            </motion.div>
          )}

          {drill.level === "designation" && drill.position && (
            <motion.div
              variants={staggerContainer}
              initial="initial"
              animate="animate"
              className="space-y-5"
            >
              {(() => {
                const scoredPeople = designationEmployees.filter(
                  (e) => e.hasData,
                );
                const groupAvg = scoredPeople.length
                  ? scoredPeople.reduce((s, e) => s + e.overallScore, 0) /
                    scoredPeople.length
                  : 0;
                const lowest = [...scoredPeople].sort(
                  (a, b) => a.overallScore - b.overallScore,
                )[0];
                return (
                  <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
                    <ScoreCard
                      label="Group overall"
                      value={groupAvg.toFixed(1)}
                      icon={<Briefcase className="h-4 w-4" />}
                      tone={performanceTone(groupAvg)}
                    />
                    <ScoreCard
                      label="People"
                      value={String(designationEmployees.length)}
                      icon={<Users className="h-4 w-4" />}
                    />
                    <ScoreCard
                      label="Top score"
                      value={
                        designationEmployees[0]?.hasData
                          ? designationEmployees[0].overallScore.toFixed(1)
                          : "—"
                      }
                      icon={<TrendingUp className="h-4 w-4" />}
                      tone="good"
                    />
                    <ScoreCard
                      label="Lowest scored"
                      value={lowest ? lowest.overallScore.toFixed(1) : "—"}
                      icon={<TrendingDown className="h-4 w-4" />}
                      tone="warn"
                    />
                  </div>
                );
              })()}

              <ChartCard
                title={`${drill.position} · people`}
                subtitle="Open a person for full User Detail / Report Card"
              >
                {designationEmployees.length === 0 ? (
                  <p className="text-sm text-muted-foreground py-10 text-center">
                    No employees in this designation for the selected lead.
                  </p>
                ) : (
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b border-border text-left text-xs text-muted-foreground">
                          <th className="py-2 pr-3 font-medium">Employee</th>
                          <th className="py-2 pr-3 font-medium">Overall</th>
                          <th className="py-2 pr-3 font-medium">Dept KPI</th>
                          <th className="py-2 pr-3 font-medium">Attendance</th>
                          <th className="py-2 pr-3 font-medium">Hours</th>
                          <th className="py-2 font-medium">Status</th>
                        </tr>
                      </thead>
                      <tbody>
                        {designationEmployees.map((e) => (
                          <tr
                            key={e.id}
                            className="border-b border-border/70 last:border-0"
                          >
                            <td className="py-3 pr-3">
                              <Link
                                href={`/dashboard/users/${e.id}`}
                                className="font-medium text-foreground hover:text-primary transition-colors"
                              >
                                {e.name}
                              </Link>
                              <p className="text-xs text-muted-foreground">
                                {e.department || "—"}
                              </p>
                            </td>
                            <td className="py-3 pr-3 tabular-nums">
                              <Badge variant="outline">
                                {e.hasData ? e.overallScore.toFixed(1) : "—"} ·{" "}
                                {e.grade}
                              </Badge>
                            </td>
                            <td className="py-3 pr-3 tabular-nums text-muted-foreground">
                              {e.departmentalScore.toFixed(1)}
                            </td>
                            <td className="py-3 pr-3 tabular-nums text-muted-foreground">
                              {e.attendanceRate.toFixed(0)}%
                            </td>
                            <td className="py-3 pr-3 tabular-nums text-muted-foreground">
                              {e.totalHours.toFixed(0)}h
                            </td>
                            <td className="py-3">
                              {e.alerts?.length ? (
                                <span className="text-xs text-amber-600 dark:text-amber-300">
                                  {e.alerts[0]}
                                </span>
                              ) : e.hasData ? (
                                <span className="text-xs text-emerald-600 dark:text-emerald-300">
                                  On track
                                </span>
                              ) : (
                                <span className="text-xs text-muted-foreground">
                                  No data
                                </span>
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </ChartCard>
            </motion.div>
          )}
        </motion.div>
      </AnimatePresence>
    </div>
  );
}
