"use client"

import { useState, useMemo } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table"
import { CalendarOff, Clock, DollarSign, LayoutDashboard, ScanLine } from "lucide-react"

// ─── types (shaped by the Prisma include in page.tsx) ────────────────────────

type Shift       = { id: string; name: string; startTime: string; endTime: string }
type LeaveType   = { id: string; name: string }
type LeaveAllowance = { id: string; leaveTypeId: string; days: number; leaveType: LeaveType }
type LeaveRequest = {
  id: string; leaveTypeId: string; startDate: string | Date; endDate: string | Date
  duration: number; reason: string | null; status: string
  leaveType: LeaveType
}
type PayrollItem = { id: string; type: string; description: string; amount: number }
type Payroll = {
  id: string; month: number; year: number
  workingDays: number; daysWorked: number
  basicSalary: number; totalAdditions: number; totalDeductions: number; netPayable: number
  status: string; items: PayrollItem[]
}
type Attendance = {
  id: string; date: string | Date; checkIn: string | Date | null; checkOut: string | Date | null
  status: string; note: string | null
}
type SalaryComponent = { id: string; category: string; amount: number }
type Employee = {
  id: string; fullName: string; position: string | null; email: string | null
  phone: string | null; nationality: string | null; avatarUrl: string | null
  joiningDate: string | Date | null; civilId: string | null
  branch: { name: string } | null
  department: { name: string } | null
  subDepartment: { name: string } | null
  reportingManager: { fullName: string; position: string | null; avatarUrl: string | null } | null
  shifts: Array<{ shift: Shift }>
  salaryComponents: SalaryComponent[]
  leaveAllowances: LeaveAllowance[]
  leaveRequests: LeaveRequest[]
  payrolls: Payroll[]
  attendances: Attendance[]
}

// ─── helpers ──────────────────────────────────────────────────────────────────

const MONTH_NAMES = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]

function fmt(date: string | Date | null | undefined, opts?: Intl.DateTimeFormatOptions) {
  if (!date) return "—"
  return new Date(date).toLocaleDateString("en-US", opts ?? { day: "numeric", month: "short", year: "numeric" })
}
function fmtTime(date: string | Date | null | undefined) {
  if (!date) return "—"
  return new Date(date).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit", hour12: true })
}
function fmtCurrency(n: number) {
  return `KWD ${n.toLocaleString("en-US", { minimumFractionDigits: 3, maximumFractionDigits: 3 })}`
}

const STATUS_PILL: Record<string, string> = {
  present:  "bg-green-100 text-green-700",
  absent:   "bg-red-100 text-red-700",
  late:     "bg-yellow-100 text-yellow-700",
  half_day: "bg-blue-100 text-blue-700",
  on_leave: "bg-purple-100 text-purple-700",
  pending:  "bg-yellow-100 text-yellow-700",
  approved: "bg-green-100 text-green-700",
  rejected: "bg-red-100 text-red-700",
  DRAFT:    "bg-gray-100 text-gray-600",
  APPROVED: "bg-green-100 text-green-700",
  PAID:     "bg-emerald-100 text-emerald-700",
}

function Pill({ status }: { status: string }) {
  const cls = STATUS_PILL[status] ?? "bg-muted text-muted-foreground"
  return (
    <span className={`inline-flex items-center rounded-full border border-border/60 px-2 py-0.5 text-xs font-medium capitalize ${cls}`}>
      {status.replace(/_/g, " ").toLowerCase()}
    </span>
  )
}

// ─── tab definitions ──────────────────────────────────────────────────────────

type Tab = "overview" | "payroll" | "leave" | "attendance"
const TABS: { id: Tab; label: string; icon: React.ReactNode }[] = [
  { id: "overview", label: "Overview", icon: <LayoutDashboard className="h-4 w-4" /> },
  { id: "payroll", label: "Payroll", icon: <DollarSign className="h-4 w-4" /> },
  { id: "leave", label: "Leave", icon: <CalendarOff className="h-4 w-4" /> },
  { id: "attendance", label: "Attendance", icon: <ScanLine className="h-4 w-4" /> },
]

// ─── main component ───────────────────────────────────────────────────────────

export default function EmployeeDashboard({ employee }: { employee: Employee }) {
  const [tab, setTab] = useState<Tab>("overview")

  const currentShift = employee.shifts[0]?.shift ?? null

  // today's attendance
  const todayStr = new Date().toISOString().slice(0, 10)
  const todayAtt = employee.attendances.find(
    a => new Date(a.date).toISOString().slice(0, 10) === todayStr
  )

  // latest payroll
  const latestPayroll = employee.payrolls[0] ?? null

  // leave summary
  const pendingLeaves  = employee.leaveRequests.filter(l => l.status === "pending").length
  const approvedLeaves = employee.leaveRequests.filter(l => l.status === "approved").length

  // this month attendance summary
  const now = new Date()
  const thisMonthAtt = employee.attendances.filter(a => {
    const d = new Date(a.date)
    return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear()
  })
  const attSummary = {
    present:  thisMonthAtt.filter(a => a.status === "present").length,
    absent:   thisMonthAtt.filter(a => a.status === "absent").length,
    late:     thisMonthAtt.filter(a => a.status === "late").length,
    on_leave: thisMonthAtt.filter(a => a.status === "on_leave").length,
  }

  return (
    <div className="space-y-6">

      {/* ── hero profile card ── */}
      <div className="relative overflow-hidden rounded-2xl border bg-card shadow-sm">
        {/* decorative gradient band */}
        <div className="absolute inset-x-0 top-0 h-24 bg-gradient-to-r from-primary/20 via-primary/10 to-transparent" />

        <div className="relative px-6 pt-6 pb-5">
          <div className="flex flex-wrap items-end gap-4">
            {/* avatar */}
            <div className="relative shrink-0">
              {employee.avatarUrl ? (
                <img src={employee.avatarUrl} alt={employee.fullName}
                  className="h-20 w-20 rounded-2xl object-cover border-4 border-card shadow-md" />
              ) : (
                <div className="h-20 w-20 rounded-2xl bg-primary/10 border-4 border-card shadow-md flex items-center justify-center text-3xl font-bold text-primary">
                  {employee.fullName.charAt(0).toUpperCase()}
                </div>
              )}
            </div>

            {/* name + meta */}
            <div className="flex-1 min-w-0 pb-1">
              <h1 className="text-2xl font-bold tracking-tight truncate">{employee.fullName}</h1>
              <p className="text-sm text-muted-foreground mt-0.5">
                {employee.position ?? "—"}
                {employee.department && <> &middot; {employee.department.name}</>}
                {employee.branch && <> &middot; {employee.branch.name}</>}
              </p>
              <div className="flex flex-wrap gap-2 mt-2">
                {todayAtt && <Pill status={todayAtt.status} />}
                {currentShift && (
                  <span className="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">
                    <Clock className="h-3.5 w-3.5" />
                    {currentShift.name} · {currentShift.startTime}–{currentShift.endTime}
                  </span>
                )}
              </div>
            </div>

            {/* quick stats */}
            <div className="flex gap-6 pb-1">
              {[
                { label: "Check In",  value: todayAtt ? fmtTime(todayAtt.checkIn)  : "—" },
                { label: "Check Out", value: todayAtt ? fmtTime(todayAtt.checkOut) : "—" },
                { label: "Net Pay",   value: latestPayroll ? fmtCurrency(latestPayroll.netPayable) : "—" },
              ].map(s => (
                <div key={s.label} className="text-center">
                  <div className="text-lg font-bold tabular-nums">{s.value}</div>
                  <div className="text-[11px] text-muted-foreground">{s.label}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ── tab bar ── */}
      <div className="inline-flex items-center rounded-lg border border-border bg-muted p-1 gap-1">
        {TABS.map(t => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-all duration-150 ${
              tab === t.id
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            <span className={tab === t.id ? "text-foreground" : "text-muted-foreground/80"}>
              {t.icon}
            </span>
            {t.label}
          </button>
        ))}
      </div>

      {/* ── tab panels ── */}
      {tab === "overview"   && <OverviewTab   employee={employee} attSummary={attSummary} pendingLeaves={pendingLeaves} approvedLeaves={approvedLeaves} latestPayroll={latestPayroll} />}
      {tab === "payroll"    && <PayrollTab    payrolls={employee.payrolls} />}
      {tab === "leave"      && <LeaveTab      leaveRequests={employee.leaveRequests} leaveAllowances={employee.leaveAllowances} />}
      {tab === "attendance" && <AttendanceTab attendances={employee.attendances} />}
    </div>
  )
}

// ─── Overview tab ─────────────────────────────────────────────────────────────

function OverviewTab({ employee, attSummary, pendingLeaves, approvedLeaves, latestPayroll }: {
  employee: Employee
  attSummary: { present: number; absent: number; late: number; on_leave: number }
  pendingLeaves: number
  approvedLeaves: number
  latestPayroll: Payroll | null
}) {
  const now = new Date()

  return (
    <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">

      {/* left col: personal info */}
      <div className="space-y-4 lg:col-span-2">

        {/* stat cards row */}
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
          {[
            { label: "Present",  value: attSummary.present,  color: "text-green-600",  bg: "bg-green-50"  },
            { label: "Absent",   value: attSummary.absent,   color: "text-red-600",    bg: "bg-red-50"    },
            { label: "Late",     value: attSummary.late,     color: "text-yellow-600", bg: "bg-yellow-50" },
            { label: "On Leave", value: attSummary.on_leave, color: "text-purple-600", bg: "bg-purple-50" },
          ].map(s => (
            <div key={s.label} className={`rounded-xl border p-3 ${s.bg}`}>
              <div className={`text-2xl font-bold tabular-nums ${s.color}`}>{s.value}</div>
              <div className="text-xs text-muted-foreground mt-0.5">{s.label} this month</div>
            </div>
          ))}
        </div>

        {/* personal details */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Personal Information</CardTitle>
          </CardHeader>
          <CardContent>
            <dl className="grid grid-cols-1 sm:grid-cols-2 gap-x-6 gap-y-3 text-sm">
              {[
                { label: "Full Name",    value: employee.fullName },
                { label: "Email",        value: employee.email },
                { label: "Phone",        value: employee.phone },
                { label: "Nationality",  value: employee.nationality },
                { label: "Civil ID",     value: employee.civilId },
                { label: "Joining Date", value: fmt(employee.joiningDate) },
                { label: "Branch",       value: employee.branch?.name },
                { label: "Department",   value: employee.department?.name },
                { label: "Sub-Dept",     value: employee.subDepartment?.name },
                { label: "Position",     value: employee.position },
              ].map(({ label, value }) => (
                <div key={label} className="flex flex-col gap-0.5">
                  <dt className="text-[11px] font-medium text-muted-foreground uppercase tracking-wide">{label}</dt>
                  <dd className="font-medium text-foreground">{value ?? "—"}</dd>
                </div>
              ))}
            </dl>
          </CardContent>
        </Card>

        {/* salary breakdown */}
        {employee.salaryComponents.length > 0 && (
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Salary Components</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Category</TableHead>
                    <TableHead className="text-right">Amount</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {employee.salaryComponents.map(c => (
                    <TableRow key={c.id}>
                      <TableCell className="capitalize">{c.category.replace(/_/g, " ")}</TableCell>
                      <TableCell className="text-right font-medium tabular-nums">{fmtCurrency(c.amount)}</TableCell>
                    </TableRow>
                  ))}
                  <TableRow className="bg-muted/40 font-semibold">
                    <TableCell>Total</TableCell>
                    <TableCell className="text-right tabular-nums">
                      {fmtCurrency(employee.salaryComponents.reduce((s, c) => s + c.amount, 0))}
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )}
      </div>

      {/* right col */}
      <div className="space-y-4">

        {/* reporting manager */}
        {employee.reportingManager && (
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Reporting To</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-3">
                {employee.reportingManager.avatarUrl ? (
                  <img src={employee.reportingManager.avatarUrl} alt=""
                    className="h-10 w-10 rounded-xl object-cover" />
                ) : (
                  <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center text-sm font-bold text-primary">
                    {employee.reportingManager.fullName.charAt(0)}
                  </div>
                )}
                <div>
                  <div className="font-medium text-sm">{employee.reportingManager.fullName}</div>
                  <div className="text-xs text-muted-foreground">{employee.reportingManager.position ?? "—"}</div>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* latest payslip preview */}
        {latestPayroll && (
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
                Latest Payslip — {MONTH_NAMES[latestPayroll.month - 1]} {latestPayroll.year}
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2 text-sm">
              {[
                { label: "Basic Salary",  value: fmtCurrency(latestPayroll.basicSalary) },
                { label: "Additions",     value: fmtCurrency(latestPayroll.totalAdditions) },
                { label: "Deductions",    value: fmtCurrency(latestPayroll.totalDeductions) },
              ].map(r => (
                <div key={r.label} className="flex justify-between">
                  <span className="text-muted-foreground">{r.label}</span>
                  <span className="font-medium tabular-nums">{r.value}</span>
                </div>
              ))}
              <div className="border-t pt-2 flex justify-between font-semibold">
                <span>Net Payable</span>
                <span className="tabular-nums text-primary">{fmtCurrency(latestPayroll.netPayable)}</span>
              </div>
              <div className="flex justify-between items-center pt-1">
                <span className="text-xs text-muted-foreground">{latestPayroll.daysWorked}/{latestPayroll.workingDays} days</span>
                <Pill status={latestPayroll.status} />
              </div>
            </CardContent>
          </Card>
        )}

        {/* leave allowance */}
        {employee.leaveAllowances.length > 0 && (
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Leave Balance</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {employee.leaveAllowances.map(la => (
                <div key={la.id} className="flex justify-between items-center text-sm">
                  <span className="text-muted-foreground">{la.leaveType.name}</span>
                  <span className="font-semibold tabular-nums">{la.days} days</span>
                </div>
              ))}
            </CardContent>
          </Card>
        )}

        {/* leave request mini-summary */}
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Leave Requests</CardTitle>
          </CardHeader>
          <CardContent className="flex gap-4">
            <div className="text-center flex-1">
              <div className="text-2xl font-bold text-yellow-600">{pendingLeaves}</div>
              <div className="text-xs text-muted-foreground">Pending</div>
            </div>
            <div className="w-px bg-border" />
            <div className="text-center flex-1">
              <div className="text-2xl font-bold text-green-600">{approvedLeaves}</div>
              <div className="text-xs text-muted-foreground">Approved</div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

// ─── Payroll tab ──────────────────────────────────────────────────────────────

function PayrollTab({ payrolls }: { payrolls: Payroll[] }) {
  const [selected, setSelected] = useState<Payroll | null>(payrolls[0] ?? null)

  if (payrolls.length === 0) {
    return <EmptyState icon="💰" title="No payroll records yet" />
  }

  return (
    <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">

      {/* payroll list */}
      <Card className="lg:col-span-1">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Payslips</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {payrolls.map(p => (
            <button
              key={p.id}
              onClick={() => setSelected(p)}
              className={`w-full flex items-center justify-between px-4 py-3 text-sm transition-colors border-b last:border-0 ${
                selected?.id === p.id
                  ? "bg-primary/5 text-primary font-medium"
                  : "hover:bg-muted/50"
              }`}
            >
              <span>{MONTH_NAMES[p.month - 1]} {p.year}</span>
              <div className="flex items-center gap-2">
                <span className="tabular-nums font-medium">{fmtCurrency(p.netPayable)}</span>
                <Pill status={p.status} />
              </div>
            </button>
          ))}
        </CardContent>
      </Card>

      {/* payslip detail */}
      {selected && (
        <Card className="lg:col-span-2">
          <CardHeader className="border-b pb-4">
            <div className="flex items-start justify-between">
              <div>
                <CardTitle className="text-lg">
                  Payslip — {MONTH_NAMES[selected.month - 1]} {selected.year}
                </CardTitle>
                <p className="text-sm text-muted-foreground mt-0.5">
                  {selected.daysWorked} of {selected.workingDays} working days
                </p>
              </div>
              <Pill status={selected.status} />
            </div>
          </CardHeader>
          <CardContent className="pt-4 space-y-4">
            {/* summary row */}
            <div className="grid grid-cols-3 gap-3">
              {[
                { label: "Basic Salary", value: fmtCurrency(selected.basicSalary), color: "text-foreground" },
                { label: "Additions",    value: fmtCurrency(selected.totalAdditions), color: "text-green-600" },
                { label: "Deductions",   value: fmtCurrency(selected.totalDeductions), color: "text-red-600" },
              ].map(s => (
                <div key={s.label} className="rounded-lg border p-3 text-center">
                  <div className={`text-lg font-bold tabular-nums ${s.color}`}>{s.value}</div>
                  <div className="text-xs text-muted-foreground mt-0.5">{s.label}</div>
                </div>
              ))}
            </div>

            {/* net payable */}
            <div className="rounded-xl bg-primary/5 border border-primary/20 p-4 flex items-center justify-between">
              <span className="font-semibold">Net Payable</span>
              <span className="text-2xl font-bold tabular-nums text-primary">{fmtCurrency(selected.netPayable)}</span>
            </div>

            {/* line items */}
            {selected.items.length > 0 && (
              <div>
                <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">Breakdown</p>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Type</TableHead>
                      <TableHead>Description</TableHead>
                      <TableHead className="text-right">Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selected.items.map(item => (
                      <TableRow key={item.id}>
                        <TableCell>
                          <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium capitalize ${
                            item.type === "addition"  ? "bg-green-100 text-green-700" :
                            item.type === "deduction" ? "bg-red-100 text-red-700"    :
                            "bg-muted text-muted-foreground"
                          }`}>
                            {item.type}
                          </span>
                        </TableCell>
                        <TableCell>{item.description}</TableCell>
                        <TableCell className={`text-right font-medium tabular-nums ${
                          item.type === "addition"  ? "text-green-600" :
                          item.type === "deduction" ? "text-red-600"   : ""
                        }`}>
                          {item.type === "deduction" ? "−" : "+"}{fmtCurrency(item.amount)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  )
}

// ─── Leave tab ────────────────────────────────────────────────────────────────

function LeaveTab({ leaveRequests, leaveAllowances }: {
  leaveRequests: LeaveRequest[]
  leaveAllowances: LeaveAllowance[]
}) {
  return (
    <div className="space-y-4">

      {/* balance cards */}
      {leaveAllowances.length > 0 && (
        <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
          {leaveAllowances.map(la => (
            <div key={la.id} className="rounded-xl border bg-card p-4 shadow-sm">
              <div className="text-2xl font-bold tabular-nums">{la.days}</div>
              <div className="text-xs text-muted-foreground mt-0.5">{la.leaveType.name}</div>
              <div className="text-[10px] text-muted-foreground/60 mt-0.5">days remaining</div>
            </div>
          ))}
        </div>
      )}

      {/* leave history */}
      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">Leave History</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {leaveRequests.length === 0 ? (
            <div className="py-10 text-center text-muted-foreground text-sm">No leave requests found.</div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Type</TableHead>
                  <TableHead>From</TableHead>
                  <TableHead>To</TableHead>
                  <TableHead>Days</TableHead>
                  <TableHead>Reason</TableHead>
                  <TableHead>Status</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {leaveRequests.map(lr => (
                  <TableRow key={lr.id}>
                    <TableCell className="font-medium">{lr.leaveType.name}</TableCell>
                    <TableCell>{fmt(lr.startDate)}</TableCell>
                    <TableCell>{fmt(lr.endDate)}</TableCell>
                    <TableCell>{lr.duration}</TableCell>
                    <TableCell className="text-muted-foreground max-w-[200px] truncate">{lr.reason ?? "—"}</TableCell>
                    <TableCell><Pill status={lr.status} /></TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

// ─── Attendance tab ───────────────────────────────────────────────────────────

function AttendanceTab({ attendances }: { attendances: Attendance[] }) {
  const summary = useMemo(() => ({
    present:  attendances.filter(a => a.status === "present").length,
    absent:   attendances.filter(a => a.status === "absent").length,
    late:     attendances.filter(a => a.status === "late").length,
    on_leave: attendances.filter(a => a.status === "on_leave").length,
  }), [attendances])

  return (
    <div className="space-y-4">

      {/* summary pills */}
      <div className="flex flex-wrap gap-2">
        {[
          { label: "Present",  value: summary.present,  cls: "bg-green-100 text-green-700"   },
          { label: "Absent",   value: summary.absent,   cls: "bg-red-100 text-red-700"       },
          { label: "Late",     value: summary.late,     cls: "bg-yellow-100 text-yellow-700" },
          { label: "On Leave", value: summary.on_leave, cls: "bg-purple-100 text-purple-700" },
        ].map(s => (
          <span key={s.label} className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium ${s.cls}`}>
            {s.label}: <strong>{s.value}</strong>
          </span>
        ))}
      </div>

      {/* attendance log */}
      <Card>
        <CardHeader className="pb-2">
          <CardTitle className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
            Recent Attendance (last {attendances.length} records)
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {attendances.length === 0 ? (
            <div className="py-10 text-center text-muted-foreground text-sm">No attendance records found.</div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Date</TableHead>
                  <TableHead>Day</TableHead>
                  <TableHead>Check In</TableHead>
                  <TableHead>Check Out</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Note</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {attendances.map(a => {
                  const d = new Date(a.date)
                  const isWeekend = d.getDay() === 0 || d.getDay() === 6
                  return (
                    <TableRow key={a.id} className={isWeekend ? "bg-muted/30" : ""}>
                      <TableCell className="font-medium tabular-nums">{fmt(a.date)}</TableCell>
                      <TableCell className="text-muted-foreground">
                        {d.toLocaleDateString("en-US", { weekday: "short" })}
                      </TableCell>
                      <TableCell className="tabular-nums">{fmtTime(a.checkIn)}</TableCell>
                      <TableCell className="tabular-nums">{fmtTime(a.checkOut)}</TableCell>
                      <TableCell><Pill status={a.status} /></TableCell>
                      <TableCell className="text-muted-foreground text-xs">{a.note ?? "—"}</TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

// ─── EmptyState ───────────────────────────────────────────────────────────────

function EmptyState({ icon, title }: { icon: string; title: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-20 text-center gap-2">
      <div className="text-4xl">{icon}</div>
      <p className="text-muted-foreground text-sm">{title}</p>
    </div>
  )
}