"use client";

import { useMemo, useState, type ReactNode } from "react";
import Link from "next/link";
import { motion } from "motion/react";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  Legend,
} from "recharts";
import {
  BarChart3,
  TrendingUp,
  Users,
  Clock,
  CalendarCheck,
  Filter,
  Search,
  ChevronLeft,
  ChevronRight,
  AlertTriangle,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DatePicker } from "@/components/ui/date-picker";
import { FilterSelect } from "@/components/ui/filter-select";
import { AppSpinner } from "@/components/ui/app-loader";
import { AnalyticsChartTooltip } from "@/components/ui/analytics-chart-tooltip";
import { DesignationPerformancePanel } from "@/components/dashboard/designation-performance";
import { staggerContainer, staggerItem } from "@/lib/motion";
import { useTeamInsights } from "@/hooks/use-team-insights";
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))",
];

const HEALTH_COLORS = {
  strong: "hsl(142 50% 42%)",
  onTrack: "hsl(var(--chart-1))",
  coaching: "hsl(38 80% 48%)",
  atRisk: "hsl(0 62% 50%)",
};

const PAGE_SIZE = 10;

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 healthBucket(score: number): keyof typeof HEALTH_COLORS {
  if (score >= 80) return "strong";
  if (score >= 70) return "onTrack";
  if (score >= 60) return "coaching";
  return "atRisk";
}

export function WorkforceAnalytics() {
  const [dateFrom, setDateFrom] = useState(DASHBOARD_DEFAULT_DATE_FROM);
  const [dateTo, setDateTo] = useState(DASHBOARD_DEFAULT_DATE_TO);
  const [leadFilter, setLeadFilter] = useState("all");
  const [employeeQuery, setEmployeeQuery] = useState("");
  const [employeeView, setEmployeeView] = useState<"top" | "bottom" | "all">(
    "top",
  );
  const [employeePage, setEmployeePage] = useState(0);
  const { data, loading, error, progress, reload } = useTeamInsights(
    dateFrom,
    dateTo,
  );

  const filteredEmployees = useMemo(() => {
    if (!data) return [];
    if (leadFilter === "all") return data.employees.filter((e) => e.hasData);
    if (leadFilter === "unassigned") {
      return data.unassigned.filter((e) => e.hasData);
    }
    return data.employees.filter(
      (e) =>
        e.hasData &&
        (e.user.managerId === leadFilter || e.user.id === leadFilter),
    );
  }, [data, leadFilter]);

  const leadChartData = useMemo(() => {
    if (!data) return [];
    return data.leads.map((t) => ({
      name: t.lead.name.split(" ")[0],
      fullName: t.lead.name,
      overall: t.avgOverall,
      attendance: t.avgAttendance,
      hours: Math.round(t.totalHours),
      members: t.memberCount,
    }));
  }, [data]);

  /** Actionable performance health — clearer than letter-grade pie alone */
  const performanceHealth = useMemo(() => {
    const buckets = {
      strong: { key: "strong", label: "Strong (80+)", count: 0 },
      onTrack: { key: "onTrack", label: "On track (70–79)", count: 0 },
      coaching: { key: "coaching", label: "Needs coaching (60–69)", count: 0 },
      atRisk: { key: "atRisk", label: "At risk (<60)", count: 0 },
    };
    for (const e of filteredEmployees) {
      buckets[healthBucket(e.overallScore)].count += 1;
    }
    const total = filteredEmployees.length || 1;
    return Object.values(buckets).map((b) => ({
      ...b,
      pct: Math.round((b.count / total) * 1000) / 10,
      fill: HEALTH_COLORS[b.key as keyof typeof HEALTH_COLORS],
    }));
  }, [filteredEmployees]);

  const componentAverages = useMemo(() => {
    if (!filteredEmployees.length) return [];
    const n = filteredEmployees.length;
    return [
      {
        name: "Dept KPIs",
        score:
          filteredEmployees.reduce((s, e) => s + e.departmentalScore, 0) / n,
      },
      {
        name: "Personnel",
        score: filteredEmployees.reduce((s, e) => s + e.personnelScore, 0) / n,
      },
      {
        name: "Attendance",
        score: filteredEmployees.reduce((s, e) => s + e.attendanceScore, 0) / n,
      },
      {
        name: "Work Summary",
        score: filteredEmployees.reduce((s, e) => s + e.hoursScore, 0) / n,
      },
    ].map((r) => ({ ...r, score: Math.round(r.score * 10) / 10 }));
  }, [filteredEmployees]);

  /** Replace empty KPI trend: attention load by team lead */
  const attentionByLead = useMemo(() => {
    if (!data) return [];
    return data.leads
      .map((t) => {
        const attention = t.needsAttention?.length || 0;
        return {
          name: t.lead.name.split(" ")[0],
          fullName: t.lead.name,
          attention,
          headcount: t.memberCount,
          avgOverall: t.avgOverall,
          attentionRate:
            t.memberCount > 0
              ? Math.round((attention / t.memberCount) * 1000) / 10
              : 0,
        };
      })
      .sort((a, b) => b.attention - a.attention);
  }, [data]);

  const employeeExplorer = useMemo(() => {
    const q = employeeQuery.trim().toLowerCase();
    let list = [...filteredEmployees];
    if (q) {
      list = list.filter(
        (e) =>
          e.user.name.toLowerCase().includes(q) ||
          (e.user.position || "").toLowerCase().includes(q) ||
          (e.user.email || "").toLowerCase().includes(q),
      );
    }
    list.sort((a, b) =>
      employeeView === "bottom"
        ? a.overallScore - b.overallScore
        : b.overallScore - a.overallScore,
    );
    return list;
  }, [filteredEmployees, employeeQuery, employeeView]);

  const employeePageCount = Math.max(
    1,
    Math.ceil(employeeExplorer.length / PAGE_SIZE),
  );
  const safePage = Math.min(employeePage, employeePageCount - 1);
  const employeePageRows = employeeExplorer.slice(
    safePage * PAGE_SIZE,
    safePage * PAGE_SIZE + PAGE_SIZE,
  );

  const employeePageChart = useMemo(
    () =>
      employeePageRows.map((e) => ({
        name:
          e.user.name.split(" ")[0] +
          (e.user.name.split(" ").length > 1
            ? ` ${e.user.name.split(" ")[1]?.[0] || ""}.`
            : ""),
        fullName: e.user.name,
        overall: e.overallScore,
        attendance: e.attendanceRate,
        hoursScore: e.hoursScore,
        hours: e.totalHours,
      })),
    [employeePageRows],
  );

  const roleBreakdown = useMemo(() => {
    if (!data) return [];
    // Peer Manager counts aren't actionable for lead/manager analytics views
    const roles = data.overview.roleBreakdown.filter(
      (r) => r.role !== "MANAGER",
    );
    const total = roles.reduce((s, r) => s + r.count, 0) || 1;
    return roles.map((r, i) => ({
      name: r.role.replace("_", " "),
      value: r.count,
      pct: Math.round((r.count / total) * 1000) / 10,
      fill: CHART_COLORS[i % CHART_COLORS.length],
    }));
  }, [data]);

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

  if (loading && !data) {
    return (
      <div className="flex min-h-[50vh] flex-col items-center justify-center gap-3">
        <AppSpinner className="h-8 w-8" />
        <p className="text-sm text-muted-foreground">
          Building analytics…
          {progress.total > 0 ? ` ${progress.done}/${progress.total}` : ""}
        </p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-xl border border-border bg-card p-8 text-center space-y-3">
        <p className="text-sm text-destructive">{error}</p>
        <Button variant="outline" size="sm" onClick={reload}>
          Retry
        </Button>
      </div>
    );
  }

  if (!data) return null;

  const leadOptions = [
    { value: "all", label: "All teams" },
    ...data.leads.map((t) => ({ value: t.lead.id, label: t.lead.name })),
    { value: "unassigned", label: "Unassigned members" },
  ];

  const healthTotal = performanceHealth.reduce((s, b) => s + b.count, 0);

  return (
    <motion.div
      className="space-y-6"
      variants={staggerContainer}
      initial="initial"
      animate="animate"
    >
      <motion.div
        variants={staggerItem}
        className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between"
      >
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <div className="p-2 rounded-lg bg-primary/10">
              <BarChart3 className="h-5 w-5 text-primary" />
            </div>
            <div>
              <h1 className="text-2xl font-semibold tracking-tight text-foreground">
                Analytics
              </h1>
              <p className="text-sm text-muted-foreground">
                Detailed workforce insights for {data.department}
              </p>
            </div>
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <Filter className="h-3.5 w-3.5 text-muted-foreground" />
          <FilterSelect
            value={leadFilter}
            onValueChange={(v) => {
              setLeadFilter(v);
              setEmployeePage(0);
            }}
            placeholder="Team"
            options={leadOptions}
            className="min-w-[160px]"
          />
          <DatePicker
            value={dateFrom}
            onChange={setDateFrom}
            max={dateTo}
            buttonClassName="h-9 w-[140px]"
          />
          <span className="text-xs text-muted-foreground">to</span>
          <DatePicker
            value={dateTo}
            onChange={setDateTo}
            min={dateFrom}
            buttonClassName="h-9 w-[140px]"
          />
        </div>
      </motion.div>

      <motion.div
        variants={staggerItem}
        className="grid grid-cols-2 lg:grid-cols-4 gap-3"
      >
        {[
          {
            label: "Avg overall",
            value: `${data.overview.avgOverall.toFixed(1)}%`,
            icon: TrendingUp,
          },
          {
            label: "Avg attendance",
            value: `${data.overview.avgAttendance.toFixed(1)}%`,
            icon: CalendarCheck,
          },
          {
            label: "Hours logged",
            value: `${data.overview.totalHours.toFixed(0)}h`,
            icon: Clock,
          },
          {
            label: "In view",
            value: filteredEmployees.length,
            icon: Users,
          },
        ].map((card) => (
          <div
            key={card.label}
            className="rounded-xl border border-border bg-card px-4 py-3.5"
          >
            <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground">
              <card.icon className="h-3 w-3 text-primary" />
              {card.label}
            </div>
            <p className="mt-1 text-xl font-semibold tabular-nums tracking-tight">
              {card.value}
            </p>
          </div>
        ))}
      </motion.div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-5">
        <ChartCard
          title="Team lead comparison"
          subtitle="Average overall score and attendance by lead"
        >
          <div className="h-72">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={leadChartData}
                margin={{ top: 8, right: 8, left: 0, bottom: 0 }}
              >
                <CartesianGrid
                  strokeDasharray="3 3"
                  stroke="hsl(var(--border))"
                />
                <XAxis
                  dataKey="name"
                  tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                />
                <YAxis
                  tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                  domain={[0, 100]}
                />
                <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="hsl(var(--chart-1))"
                  radius={[6, 6, 0, 0]}
                />
                <Bar
                  dataKey="attendance"
                  name="Attendance %"
                  fill="hsl(var(--chart-2))"
                  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 — based on overall score"
        >
          <div className="space-y-4">
            {healthTotal === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-16">
                No scored employees in this filter
              </p>
            ) : (
              <>
                <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 transition-all"
                        style={{
                          width: `${b.pct}%`,
                          backgroundColor: b.fill,
                        }}
                        title={`${b.label}: ${b.count}`}
                      />
                    ))}
                </div>
                <ul className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {performanceHealth.map((b) => (
                    <li
                      key={b.key}
                      className="flex items-center justify-between rounded-lg border border-border px-3 py-2"
                    >
                      <span className="inline-flex items-center gap-2 text-sm text-foreground">
                        <span
                          className="h-2.5 w-2.5 rounded-sm"
                          style={{ backgroundColor: b.fill }}
                        />
                        {b.label}
                      </span>
                      <span className="text-sm font-semibold tabular-nums">
                        {b.count}{" "}
                        <span className="text-muted-foreground font-normal">
                          ({b.pct}%)
                        </span>
                      </span>
                    </li>
                  ))}
                </ul>
                <p className="text-xs text-muted-foreground">
                  Use this to prioritize coaching: focus on At risk and Needs
                  coaching first.
                </p>
              </>
            )}
          </div>
        </ChartCard>

        <ChartCard
          title="KPI component averages"
          subtitle="Departmental, personnel, attendance, and hours scores"
        >
          <div className="h-72">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={componentAverages}
                layout="vertical"
                margin={{ left: 16 }}
              >
                <CartesianGrid
                  strokeDasharray="3 3"
                  stroke="hsl(var(--border))"
                />
                <XAxis
                  type="number"
                  domain={[0, 100]}
                  tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                />
                <YAxis
                  type="category"
                  dataKey="name"
                  width={80}
                  tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                />
                <Tooltip
                  content={
                    <AnalyticsChartTooltip
                      valueFormatter={(v) =>
                        typeof v === "number" ? `${v.toFixed(1)}%` : v
                      }
                    />
                  }
                />
                <Bar
                  dataKey="score"
                  name="Avg score"
                  fill="hsl(var(--chart-1))"
                  radius={[0, 6, 6, 0]}
                />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </ChartCard>

        <ChartCard
          title="Team attention load"
          subtitle="People needing attention per team lead — who needs manager support"
        >
          <div className="h-72">
            {attentionByLead.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center pt-20">
                No team lead data
              </p>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={attentionByLead}
                  layout="vertical"
                  margin={{ left: 8 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 3"
                    stroke="hsl(var(--border))"
                  />
                  <XAxis
                    type="number"
                    allowDecimals={false}
                    tick={{
                      fontSize: 11,
                      fill: "hsl(var(--muted-foreground))",
                    }}
                  />
                  <YAxis
                    type="category"
                    dataKey="name"
                    width={72}
                    tick={{
                      fontSize: 11,
                      fill: "hsl(var(--muted-foreground))",
                    }}
                  />
                  <Tooltip
                    content={
                      <AnalyticsChartTooltip
                        labelFormatter={(_, payload) =>
                          String(payload?.[0]?.payload?.fullName || "")
                        }
                        valueFormatter={(v, name, item) => {
                          if (name === "Needs attention") {
                            const hc = Number(item.payload?.headcount || 0);
                            return `${v} of ${hc} (${item.payload?.attentionRate ?? 0}%)`;
                          }
                          return v;
                        }}
                      />
                    }
                  />
                  <Bar
                    dataKey="attention"
                    name="Needs attention"
                    fill="hsl(var(--chart-5))"
                    radius={[0, 6, 6, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            )}
          </div>
        </ChartCard>

        <ChartCard
          title="Employee performance explorer"
          subtitle="Search, sort top/bottom, and page through everyone in view — not just a top-12 chart"
          className="xl:col-span-2"
        >
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
            <div className="relative flex-1 max-w-sm">
              <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
              <Input
                value={employeeQuery}
                onChange={(e) => {
                  setEmployeeQuery(e.target.value);
                  setEmployeePage(0);
                }}
                placeholder="Search name, email, or position…"
                className="pl-8 h-9"
              />
            </div>
            <div className="flex flex-wrap gap-1.5">
              {(
                [
                  ["top", "Top scores"],
                  ["bottom", "Needs attention"],
                  ["all", "A–Z / ranked"],
                ] as const
              ).map(([key, label]) => (
                <Button
                  key={key}
                  type="button"
                  size="sm"
                  variant={employeeView === key ? "default" : "outline"}
                  className="h-8"
                  onClick={() => {
                    setEmployeeView(key);
                    setEmployeePage(0);
                  }}
                >
                  {key === "bottom" ? (
                    <AlertTriangle className="h-3.5 w-3.5 mr-1.5" />
                  ) : null}
                  {label}
                </Button>
              ))}
            </div>
          </div>

          <div className="h-64 mb-4">
            {employeePageChart.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center pt-20">
                No employees match this search/filter
              </p>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={employeePageChart}>
                  <CartesianGrid
                    strokeDasharray="3 3"
                    stroke="hsl(var(--border))"
                  />
                  <XAxis
                    dataKey="name"
                    tick={{
                      fontSize: 10,
                      fill: "hsl(var(--muted-foreground))",
                    }}
                    interval={0}
                    angle={-20}
                    textAnchor="end"
                    height={48}
                  />
                  <YAxis
                    domain={[0, 100]}
                    tick={{
                      fontSize: 11,
                      fill: "hsl(var(--muted-foreground))",
                    }}
                  />
                  <Tooltip
                    content={
                      <AnalyticsChartTooltip
                        labelFormatter={(_, payload) =>
                          String(payload?.[0]?.payload?.fullName || "")
                        }
                        valueFormatter={(v, name) => {
                          if (typeof v !== "number") return v;
                          if (name === "Hours logged")
                            return `${v.toFixed(0)}h`;
                          return `${v.toFixed(1)}%`;
                        }}
                      />
                    }
                  />
                  <Legend />
                  <Bar
                    dataKey="overall"
                    name="Overall %"
                    fill="hsl(var(--chart-1))"
                    radius={[4, 4, 0, 0]}
                  />
                  <Bar
                    dataKey="attendance"
                    name="Attendance %"
                    fill="hsl(var(--chart-3))"
                    radius={[4, 4, 0, 0]}
                  />
                  <Bar
                    dataKey="hoursScore"
                    name="Work Summary %"
                    fill="hsl(var(--chart-2))"
                    radius={[4, 4, 0, 0]}
                  />
                </BarChart>
              </ResponsiveContainer>
            )}
          </div>

          <div className="overflow-x-auto rounded-lg border border-border">
            <table className="w-full text-sm">
              <thead className="bg-muted/40">
                <tr className="text-xs uppercase tracking-wide text-muted-foreground border-b border-border">
                  <th className="text-left py-2 px-3 font-semibold">
                    Employee
                  </th>
                  <th className="text-right py-2 px-3 font-semibold">
                    Overall
                  </th>
                  <th className="text-right py-2 px-3 font-semibold">Att.</th>
                  <th className="text-right py-2 px-3 font-semibold">Hours</th>
                  <th className="text-left py-2 px-3 font-semibold">Health</th>
                </tr>
              </thead>
              <tbody>
                {employeePageRows.map((e) => {
                  const bucket = healthBucket(e.overallScore);
                  const labels = {
                    strong: "Strong",
                    onTrack: "On track",
                    coaching: "Coaching",
                    atRisk: "At risk",
                  };
                  return (
                    <tr
                      key={e.user.id}
                      className="border-b border-border/60 hover:bg-muted/40"
                    >
                      <td className="py-2 px-3">
                        <Link
                          href={`/dashboard/users/${e.user.id}`}
                          className="font-medium text-foreground hover:text-primary"
                        >
                          {e.user.name}
                        </Link>
                        <div className="text-[11px] text-muted-foreground truncate max-w-[200px]">
                          {e.user.position || e.user.role}
                        </div>
                      </td>
                      <td className="py-2 px-3 text-right tabular-nums">
                        <Badge variant="outline" className="text-[10px]">
                          {e.grade} · {e.overallScore.toFixed(1)}%
                        </Badge>
                      </td>
                      <td className="py-2 px-3 text-right tabular-nums text-muted-foreground">
                        {e.attendanceRate.toFixed(0)}%
                      </td>
                      <td className="py-2 px-3 text-right tabular-nums text-muted-foreground">
                        {e.totalHours.toFixed(0)}h
                      </td>
                      <td className="py-2 px-3">
                        <span
                          className="inline-flex items-center gap-1.5 text-xs font-medium"
                          style={{ color: HEALTH_COLORS[bucket] }}
                        >
                          <span
                            className="h-2 w-2 rounded-full"
                            style={{ backgroundColor: HEALTH_COLORS[bucket] }}
                          />
                          {labels[bucket]}
                        </span>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div className="mt-3 flex items-center justify-between gap-2">
            <p className="text-xs text-muted-foreground">
              Showing{" "}
              {employeeExplorer.length === 0 ? 0 : safePage * PAGE_SIZE + 1}–
              {Math.min((safePage + 1) * PAGE_SIZE, employeeExplorer.length)} of{" "}
              {employeeExplorer.length}
            </p>
            <div className="flex items-center gap-1">
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8"
                disabled={safePage <= 0}
                onClick={() => setEmployeePage((p) => Math.max(0, p - 1))}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <span className="text-xs tabular-nums text-muted-foreground px-2">
                {safePage + 1} / {employeePageCount}
              </span>
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="h-8"
                disabled={safePage >= employeePageCount - 1}
                onClick={() =>
                  setEmployeePage((p) => Math.min(employeePageCount - 1, p + 1))
                }
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </ChartCard>

        <motion.div variants={staggerItem} className="min-w-0">
          <DesignationPerformancePanel people={designationPeople} />
        </motion.div>

        <ChartCard
          title="Role mix"
          subtitle="Team composition (excluding Managers)"
          className="self-start"
        >
          <div className="flex flex-col sm:flex-row sm:items-center gap-4">
            <div className="relative mx-auto h-40 w-40 shrink-0">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={roleBreakdown}
                    dataKey="value"
                    nameKey="name"
                    innerRadius={42}
                    outerRadius={68}
                    paddingAngle={2}
                    stroke="hsl(var(--card))"
                    strokeWidth={2}
                  >
                    {roleBreakdown.map((entry, i) => (
                      <Cell
                        key={entry.name}
                        fill={
                          entry.fill || CHART_COLORS[i % CHART_COLORS.length]
                        }
                      />
                    ))}
                  </Pie>
                  <Tooltip
                    content={
                      <AnalyticsChartTooltip
                        valueFormatter={(v, name, item) => {
                          const pct = item.payload?.pct;
                          return `${v} people${pct != null ? ` (${pct}%)` : ""}`;
                        }}
                      />
                    }
                  />
                </PieChart>
              </ResponsiveContainer>
              <div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
                <span className="text-lg font-semibold tabular-nums text-foreground leading-none">
                  {roleBreakdown.reduce((s, r) => s + r.value, 0)}
                </span>
                <span className="text-[10px] uppercase tracking-wide text-muted-foreground mt-0.5">
                  people
                </span>
              </div>
            </div>

            <ul className="flex-1 min-w-0 space-y-3 w-full">
              {roleBreakdown.map((entry) => (
                <li key={entry.name} className="space-y-1.5">
                  <div className="flex items-center justify-between gap-2 text-sm">
                    <span className="inline-flex items-center gap-2 min-w-0">
                      <span
                        className="h-2.5 w-2.5 rounded-sm shrink-0"
                        style={{
                          backgroundColor: entry.fill || CHART_COLORS[0],
                        }}
                      />
                      <span className="font-medium text-foreground truncate capitalize">
                        {entry.name.toLowerCase()}
                      </span>
                    </span>
                    <span className="tabular-nums text-muted-foreground shrink-0">
                      <span className="font-semibold text-foreground">
                        {entry.value}
                      </span>
                      <span className="mx-1 opacity-40">·</span>
                      {entry.pct}%
                    </span>
                  </div>
                  <div className="h-1.5 rounded-full bg-muted overflow-hidden">
                    <div
                      className="h-full rounded-full transition-[width]"
                      style={{
                        width: `${Math.max(entry.pct, 2)}%`,
                        backgroundColor: entry.fill || CHART_COLORS[0],
                      }}
                    />
                  </div>
                </li>
              ))}
              {roleBreakdown.length === 0 ? (
                <li className="text-sm text-muted-foreground py-4 text-center">
                  No role data in view.
                </li>
              ) : null}
            </ul>
          </div>
        </ChartCard>
      </div>
    </motion.div>
  );
}
