"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect, useMemo, Suspense } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { Clock, Search, Play, Square, UserCheck, X, Download, ChevronDown, Wifi, WifiOff, RefreshCw, Fingerprint, Eye, Trash2, Plus, ArrowUpDown, ArrowUp, ArrowDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { downloadAttendancePDF, downloadAttendanceMonthlySummaryPDF } from "@/lib/pdf";

interface PunchRecord {
  id: string;
  checkIn: string | null;
  checkOut: string | null;
  deviceSource: string | null;
}

interface AttendanceRecord {
  id: string;
  employeeId: string;
  date: string;
  checkIn: string | null;
  checkOut: string | null;
  status: string;
  holidayName?: string;
  overtimeHrs: number;
  overtimeAmount: number;
  totalWorkedHrs: number;
  deductionHrs: number;
  deductionAmount: number;
  adjustedMins?: number;
  punches: PunchRecord[];
  employee: {
    firstName: string;
    lastName: string;
    employeeId: string;
    department: string;
  };
}

interface LeaveRecord {
  employeeId: string;
  startDate: string;
  endDate: string;
  status: string;
}

function fmtHrs(h: number): string {
  const hrs = Math.floor(h);
  const mins = Math.round((h - hrs) * 60);
  return `${hrs}h ${mins}m`;
}

function getWorkedHrs(rec: AttendanceRecord): number {
  const ins = (rec.punches || [])
    .filter((p: any) => p.checkIn != null && p.deviceSource !== "DELETED_MANUAL")
    .sort((a: any, b: any) => new Date(a.checkIn!).getTime() - new Date(b.checkIn!).getTime());
  const outs = (rec.punches || [])
    .filter((p: any) => p.checkOut && p.deviceSource !== "DELETED_MANUAL")
    .sort((a: any, b: any) => new Date(a.checkOut!).getTime() - new Date(b.checkOut!).getTime());

  let totalMin = 0;
  const len = Math.max(ins.length, outs.length);
  for (let i = 0; i < len; i++) {
    const inn = ins[i];
    const out = outs[i];
    if (inn?.checkIn && out?.checkOut) {
      totalMin += (new Date(out.checkOut).getTime() - new Date(inn.checkIn).getTime()) / 60000;
    }
  }
  return totalMin > 0 ? totalMin / 60 : (rec.totalWorkedHrs || 0);
}

export default function AttendancePage() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <AttendanceContent />
    </Suspense>
  );
}

function AttendanceContent() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [records, setRecords] = useState<AttendanceRecord[]>([]);
  const [employees, setEmployees] = useState<any[]>([]);
  const [leaves, setLeaves] = useState<LeaveRecord[]>([]);
  const [holidayCalendar, setHolidayCalendar] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");

  const [sortField, setSortField] = useState<string | null>(null);
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortOrder(prev => (prev === "asc" ? "desc" : "asc"));
    } else {
      setSortField(field);
      setSortOrder("asc");
    }
    setCurrentPage(1);
  };
  const [dateFilter, setDateFilter] = useState(() => {
    return searchParams.get("date") || new Date().toISOString().split("T")[0];
  });

  // Update URL when dateFilter changes
  useEffect(() => {
    const currentUrlDate = searchParams.get("date");
    if (currentUrlDate !== dateFilter) {
      const params = new URLSearchParams(searchParams.toString());
      if (dateFilter) {
        params.set("date", dateFilter);
      } else {
        params.delete("date");
      }
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    }
  }, [dateFilter, pathname, router, searchParams]);

  const [selectedEmployeeId, setSelectedEmployeeId] = useState("");
  const [manualDate, setManualDate] = useState(new Date().toISOString().split("T")[0]);
  const [manualTime, setManualTime] = useState(() => {
    const n = new Date();
    return `${String(n.getHours()).padStart(2, "0")}:${String(n.getMinutes()).padStart(2, "0")}`;
  });
  const [useManualTime, setUseManualTime] = useState(false);

  // Punch detail popup
  const [punchModal, setPunchModal] = useState<AttendanceRecord | null>(null);
  const [editInTime, setEditInTime] = useState("");
  const [editOutTime, setEditOutTime] = useState("");
  const [editInDate, setEditInDate] = useState("");
  const [editOutDate, setEditOutDate] = useState("");
  const [savingEdit, setSavingEdit] = useState(false);
  const [deletingRecord, setDeletingRecord] = useState(false);
  const [editingPunchId, setEditingPunchId] = useState<string | null>(null);
  const [punchEditIn, setPunchEditIn] = useState("");
  const [punchEditOut, setPunchEditOut] = useState("");
  const [punchEditInDate, setPunchEditInDate] = useState("");
  const [punchEditOutDate, setPunchEditOutDate] = useState("");
  const [savingPunch, setSavingPunch] = useState(false);

  // ── zkteco device sync ──────────────────────────────────────────────────
  const [deviceOnline, setDeviceOnline] = useState<boolean | null>(null);
  const [deviceError, setDeviceError] = useState<string>("");
  const [syncing, setSyncing] = useState(false);
  const [syncResult, setSyncResult] = useState<{ created?: number; skipped?: number; error?: string; unmappedIds?: string[] } | null>(null);
  const [syncDays, setSyncDays] = useState(1);
  const [syncDate, setSyncDate] = useState("");

  const checkDevice = async () => {
    setDeviceOnline(null);
    setDeviceError("");
    try {
      const res = await authFetch(`${API}/dash/zkteco/status`);
      const data = await res.json();
      setDeviceOnline(data.online === true);
      if (!data.online) setDeviceError(data.error ?? "");
    } catch (e) { setDeviceOnline(false); setDeviceError(String(e)); }
  };

  const handleSync = async () => {
    setSyncing(true);
    setSyncResult(null);
    try {
      const params = syncDate ? `date=${syncDate}` : `days=${syncDays}`;
      const res = await authFetch(`${API}/dash/zkteco/sync?${params}`, { method: "POST" });
      const data = await res.json();
      setSyncResult(data);
      if (data.success) { fetchRecords(); setTimeout(fetchRecords, 800); }
    } catch (e) {
      setSyncResult({ error: String(e) });
    } finally {
      setSyncing(false);
    }
  };

  useEffect(() => { checkDevice(); }, []);

  const [downloadMode, setDownloadMode] = useState<"daily" | "weekly" | "monthly" | "range">("daily");
  const [downloadDate, setDownloadDate] = useState(new Date().toISOString().split("T")[0]);
  const [downloadRangeFrom, setDownloadRangeFrom] = useState("");
  const [downloadRangeTo, setDownloadRangeTo] = useState("");
  const [downloadEmployeeId, setDownloadEmployeeId] = useState("");
  const [showDownloadPanel, setShowDownloadPanel] = useState(false);

  const [showRecalcPanel, setShowRecalcPanel] = useState(false);
  const [recalcFrom, setRecalcFrom] = useState("");
  const [recalcTo, setRecalcTo] = useState("");
  const [recalculating, setRecalculating] = useState(false);

  const PAGE_SIZE = 10;
  const [currentPage, setCurrentPage] = useState(1);

  const fetchRecords = async () => {
    try {
      setIsLoading(true);
      const res = await authFetch(`${API}/dash/attendance`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) setRecords(data);
      else setRecords([]);
    } catch (e) {
      setRecords([]);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchEmployees = async () => {
    try {
      const res = await authFetch(`${API}/dash/employees?limit=1000`);
      const raw = await res.json();
      if (res.ok) setEmployees(Array.isArray(raw) ? raw : (raw.employees ?? []));
    } catch (e) {
      console.error(e);
    }
  };

  const fetchLeaves = async () => {
    try {
      const res = await authFetch(`${API}/dash/leaves`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) {
        setLeaves(data.filter((l) => l.status === "APPROVED"));
      } else {
        setLeaves([]);
      }
    } catch {
      setLeaves([]);
    }
  };

  const fetchSettings = async () => {
    try {
      const res = await authFetch(`${API}/dash/settings`);
      const data = await res.json();
      if (res.ok && data.holidayCalendar) {
        const p = typeof data.holidayCalendar === "string" ? JSON.parse(data.holidayCalendar) : data.holidayCalendar;
        setHolidayCalendar(Array.isArray(p) ? p : []);
      }
    } catch { }
  };

  useEffect(() => {
    fetchRecords();
    fetchEmployees();
    fetchLeaves();
    fetchSettings();
  }, []);

  const buildTimePayload = () => {
    if (!useManualTime) return {};
    const isoTime = new Date(`${manualDate}T${manualTime}:00`).toISOString();
    return { manualTime: isoTime, manualDate };
  };

  const handleClockIn = async () => {
    if (!selectedEmployeeId) return alert("Please select an employee");
    try {
      const res = await authFetch(`${API}/dash/attendance/clock-in`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ employeeId: selectedEmployeeId, ...buildTimePayload() }),
      });
      if (!res.ok) {
        const err = await res.json();
        alert(err.message);
      } else {
        setIsSlideOverOpen(false);
        fetchRecords();
      }
    } catch (e) {
      console.error(e);
    }
  };

  const handleClockOut = async () => {
    if (!selectedEmployeeId) return alert("Please select an employee");
    try {
      const res = await authFetch(`${API}/dash/attendance/clock-out`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ employeeId: selectedEmployeeId, ...buildTimePayload() }),
      });
      if (!res.ok) {
        const err = await res.json();
        alert(err.message);
      } else {
        setIsSlideOverOpen(false);
        fetchRecords();
      }
    } catch (e) {
      console.error(e);
    }
  };

  const handleDownloadPDF = async () => {
    const base = new Date(downloadDate);
    let filtered: typeof records = [];
    let label = "";

    const onApprovedLeave = (employeeId: string, dateMs: number) =>
      leaves.some((l) => {
        if (l.employeeId !== employeeId || l.status !== "APPROVED") return false;
        const s = new Date(l.startDate); s.setHours(0, 0, 0, 0);
        const e = new Date(l.endDate); e.setHours(0, 0, 0, 0);
        return dateMs >= s.getTime() && dateMs <= e.getTime();
      });

    const generateFullList = (start: Date, end: Date) => {
      const full: AttendanceRecord[] = [];
      const curr = new Date(start);
      const toLocalDS = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
      const toLocalDSStr = (s: string) => { const d = new Date(s); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; };
      while (curr <= end) {
        const ds = toLocalDS(curr);
        const dateMs = curr.getTime();
        const forDay = records.filter(r => toLocalDSStr(r.date) === ds);
        const byEmp = new Map(forDay.map(r => [r.employeeId, r]));

        employees.forEach(emp => {
          if (downloadEmployeeId && emp.id !== downloadEmployeeId) return;
          if (byEmp.has(emp.id)) {
            full.push(byEmp.get(emp.id)!);
          } else {
            full.push({
              id: `v-${emp.id}-${ds}`,
              employeeId: emp.id,
              date: curr.toISOString(),
              checkIn: null, checkOut: null,
              status: onApprovedLeave(emp.id, dateMs) ? "ON_LEAVE" : (curr.getDay() === 0 ? "WEEKLY_OFF" : "ABSENT"),
              overtimeHrs: 0, overtimeAmount: 0, totalWorkedHrs: 0, deductionHrs: 0, deductionAmount: 0, punches: [],
              employee: { firstName: emp.firstName, lastName: emp.lastName, employeeId: emp.employeeId, department: emp.department }
            } as any);
          }
        });
        curr.setDate(curr.getDate() + 1);
      }
      return full;
    };

    if (downloadMode === "daily") {
      const start = new Date(downloadDate + "T00:00:00");
      filtered = generateFullList(start, start);
      label = start.toLocaleDateString("en-PK", { day: "2-digit", month: "long", year: "numeric" });
    } else if (downloadMode === "weekly") {
      const end = new Date(downloadDate + "T00:00:00");
      const start = new Date(end); start.setDate(end.getDate() - 6);
      filtered = generateFullList(start, end);
      label = `${start.toLocaleDateString("en-PK", { day: "2-digit", month: "short" })} – ${end.toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" })}`;
    } else if (downloadMode === "range") {
      if (!downloadRangeFrom || !downloadRangeTo) { alert("Please select both From and To dates."); return; }
      const start = new Date(downloadRangeFrom + "T00:00:00");
      const end = new Date(downloadRangeTo + "T00:00:00");
      filtered = generateFullList(start, end);
      const fmtD = (ds: string) => new Date(ds).toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" });
      label = `${fmtD(downloadRangeFrom)} – ${fmtD(downloadRangeTo)}`;
    } else {
      const end = new Date(downloadDate + "T00:00:00");
      const start = new Date(end); start.setDate(end.getDate() - 29);
      const toLocalDSStr = (s: string) => { const d = new Date(s); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`; };
      const startDS = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, "0")}-${String(start.getDate()).padStart(2, "0")}`;
      const endDS = `${end.getFullYear()}-${String(end.getMonth() + 1).padStart(2, "0")}-${String(end.getDate()).padStart(2, "0")}`;
      filtered = records.filter(r => {
        if (downloadEmployeeId && r.employeeId !== downloadEmployeeId) return false;
        const ds = toLocalDSStr(r.date);
        return ds >= startDS && ds <= endDS;
      });
      label = `${start.toLocaleDateString("en-PK", { day: "2-digit", month: "short" })} – ${end.toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" })}`;
    }

    if (downloadMode === "monthly") {
      await downloadAttendanceMonthlySummaryPDF(filtered, label);
    } else {
      await downloadAttendancePDF(filtered, downloadMode as "daily" | "weekly" | "range", label);
    }
    setShowDownloadPanel(false);
  };

  // For the selected date, show all employees:
  // - Existing attendance records as-is
  // - Employees without a record as ABSENT placeholders
  const filteredRecords: AttendanceRecord[] = (() => {
    const q = searchQuery.toLowerCase();

    // When no date filter, keep existing behaviour (only actual records)
    if (!dateFilter) {
      return records.filter((r) => {
        const recordDate = new Date(r.date);
        const localDateString = `${recordDate.getFullYear()}-${String(
          recordDate.getMonth() + 1,
        ).padStart(2, "0")}-${String(recordDate.getDate()).padStart(2, "0")}`;

        return (
          (r.employee?.firstName.toLowerCase().includes(q) ||
            r.employee?.lastName.toLowerCase().includes(q) ||
            (r.employee?.employeeId &&
              r.employee.employeeId.toLowerCase().includes(q)) ||
            r.employee?.department.toLowerCase().includes(q)) &&
          localDateString === dateFilter
        );
      });
    }

    // First, take all real records for that date
    const forDate = records.filter((r) => {
      const recordDate = new Date(r.date);
      const localDateString = `${recordDate.getFullYear()}-${String(
        recordDate.getMonth() + 1,
      ).padStart(2, "0")}-${String(recordDate.getDate()).padStart(2, "0")}`;
      return localDateString === dateFilter;
    });

    const dateObj = new Date(dateFilter + "T00:00:00");
    const dateMs = dateObj.getTime();

    const currentHoliday = holidayCalendar.find(h => {
      const s = new Date(h.startDate); s.setHours(0, 0, 0, 0);
      const e = new Date(h.endDate); e.setHours(23, 59, 59, 999);
      return dateMs >= s.getTime() && dateMs <= e.getTime();
    });

    const onApprovedLeave = (employeeId: string) =>
      leaves.some((l) => {
        if (l.employeeId !== employeeId || l.status !== "APPROVED") return false;
        const s = new Date(l.startDate);
        s.setHours(0, 0, 0, 0);
        const e = new Date(l.endDate);
        e.setHours(0, 0, 0, 0);
        return dateMs >= s.getTime() && dateMs <= e.getTime();
      });

    const byEmployeeId = new Map<string, AttendanceRecord>();
    forDate.forEach((r) => {
      byEmployeeId.set(r.employeeId, r);
      if (currentHoliday) r.holidayName = currentHoliday.title;
    });

    // Build placeholder ABSENT rows for employees without a record
    const placeholderRecords: AttendanceRecord[] = employees
      .filter((emp) => !byEmployeeId.has(emp.id))
      .map((emp) => ({
        id: `absent-${emp.id}-${dateFilter}`,
        employeeId: emp.id,
        date: dateObj.toISOString(),
        checkIn: null,
        checkOut: null,
        status: currentHoliday ? "HOLIDAY" : (onApprovedLeave(emp.id) ? "ON_LEAVE" : (dateObj.getDay() === 0 ? "WEEKLY_OFF" : "ABSENT")),
        holidayName: currentHoliday?.title,
        overtimeHrs: 0,
        overtimeAmount: 0,
        totalWorkedHrs: 0,
        deductionHrs: 0,
        deductionAmount: 0,
        punches: [],
        employee: {
          firstName: emp.firstName,
          lastName: emp.lastName,
          employeeId: emp.employeeId,
          department: emp.department,
        },
      }));

    const combined = [...forDate, ...placeholderRecords];

    // Now apply search filter on combined list
    return combined.filter((r) => {
      return (
        r.employee?.firstName.toLowerCase().includes(q) ||
        r.employee?.lastName.toLowerCase().includes(q) ||
        (r.employee?.employeeId &&
          r.employee.employeeId.toLowerCase().includes(q)) ||
        r.employee?.department.toLowerCase().includes(q)
      );
    });
  })();

  const sortedRecords = useMemo(() => {
    if (!sortField) return filteredRecords;

    return [...filteredRecords].sort((a, b) => {
      let valA: any = null;
      let valB: any = null;

      switch (sortField) {
        case "checkIn":
          valA = a.checkIn ? new Date(a.checkIn).getTime() : null;
          valB = b.checkIn ? new Date(b.checkIn).getTime() : null;
          break;
        case "checkOut":
          valA = a.checkOut ? new Date(a.checkOut).getTime() : null;
          valB = b.checkOut ? new Date(b.checkOut).getTime() : null;
          break;
        case "worked":
          valA = getWorkedHrs(a);
          valB = getWorkedHrs(b);
          break;
        case "deduction":
          valA = a.deductionAmount || 0;
          valB = b.deductionAmount || 0;
          break;
        case "adjusted":
          valA = a.adjustedMins || 0;
          valB = b.adjustedMins || 0;
          break;
        case "otHrs":
          valA = a.overtimeHrs || 0;
          valB = b.overtimeHrs || 0;
          break;
        case "otAmount":
          valA = a.overtimeAmount || 0;
          valB = b.overtimeAmount || 0;
          break;
        case "status":
          valA = a.status || "";
          valB = b.status || "";
          break;
        default:
          return 0;
      }

      if (valA === null || valA === undefined || valA === "") return 1;
      if (valB === null || valB === undefined || valB === "") return -1;

      if (typeof valA === "string" && typeof valB === "string") {
        return sortOrder === "asc"
          ? valA.localeCompare(valB)
          : valB.localeCompare(valA);
      }

      return sortOrder === "asc"
        ? (valA < valB ? -1 : valA > valB ? 1 : 0)
        : (valA > valB ? -1 : valA < valB ? 1 : 0);
    });
  }, [filteredRecords, sortField, sortOrder]);

  // Reset to page 1 whenever filter/search changes
  const totalPages = Math.max(1, Math.ceil(sortedRecords.length / PAGE_SIZE));
  const pagedRecords = sortedRecords.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE);

  return (
    <div className="space-y-6 relative">

      {/* ── zkteco Device Bar ───────────────────────────────────────────── */}
      <div className="rounded-xl border border-gray-200 bg-white shadow-sm px-4 py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div className="flex items-center gap-3">
          {deviceOnline === null ? (
            <span className="inline-flex items-center gap-1.5 text-xs text-gray-400"><RefreshCw className="h-3.5 w-3.5 animate-spin" /> Checking device…</span>
          ) : deviceOnline ? (
            <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-emerald-600"><Wifi className="h-3.5 w-3.5" /> zkteco online — 192.168.10.252</span>
          ) : (
            <span className="inline-flex flex-col gap-0.5">
              <span className="inline-flex items-center gap-1.5 text-xs font-semibold text-red-500"><WifiOff className="h-3.5 w-3.5" /> Device offline or unreachable</span>
              {deviceError && <span className="text-xs text-red-400 pl-5">{deviceError}</span>}
            </span>
          )}
          <button onClick={checkDevice} className="text-xs text-gray-400 hover:text-gray-600 underline">Refresh</button>
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-xs text-gray-500">Manual:</span>
          <input
            type="date"
            value={syncDate}
            onChange={e => setSyncDate(e.target.value)}
            className="rounded-lg border-0 py-1 px-2 text-xs text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-brand-500 bg-white"
            title="Sync specific date"
          />
          {!syncDate && (
            <select
              value={syncDays}
              onChange={e => setSyncDays(Number(e.target.value))}
              className="rounded-lg border-0 py-1 pl-2 pr-6 text-xs text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-brand-500 bg-white"
            >
              <option value={1}>1 day</option>
              <option value={3}>3 days</option>
              <option value={7}>7 days</option>
              <option value={30}>30 days</option>
            </select>
          )}
          {syncDate && (
            <button onClick={() => setSyncDate("")} className="text-xs text-gray-400 hover:text-gray-600 underline">Clear</button>
          )}
          <button
            onClick={handleSync}
            disabled={syncing}
            className="inline-flex items-center gap-1.5 rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-semibold text-white shadow-sm hover:bg-brand-700 disabled:opacity-60 transition-colors"
          >
            <RefreshCw className={cn("h-3.5 w-3.5", syncing && "animate-spin")} />
            {syncing ? "Syncing…" : "Sync Now"}
          </button>
          {syncResult && (
            syncResult.error
              ? <span className="text-xs text-red-500">Error: {syncResult.error}</span>
              : (
                <span className="text-xs text-emerald-600 font-medium">Done — {syncResult.created} records synced</span>
              )
          )}
        </div>
      </div>

      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
            Attendance Log
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            Real-time daily attendance and machine logs.
          </p>
        </div>

        <div className="flex items-center gap-3 flex-wrap">
          <div className="relative">
            <button
              onClick={() => setShowDownloadPanel((v) => !v)}
              className="inline-flex items-center justify-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 transition-colors gap-2"
            >
              <Download className="h-4 w-4" />
              Download Report
              <ChevronDown className={cn("h-3 w-3 transition-transform", showDownloadPanel && "rotate-180")} />
            </button>

            <AnimatePresence>
              {showDownloadPanel && (
                <motion.div
                  initial={{ opacity: 0, y: -6, scale: 0.97 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: -6, scale: 0.97 }}
                  transition={{ duration: 0.15 }}
                  className="absolute right-0 top-11 z-50 w-72 rounded-xl border border-gray-200 bg-white p-4 shadow-xl"
                >
                  <p className="text-xs font-semibold uppercase tracking-wider text-gray-400 mb-3">Export Options</p>

                  <div className="flex gap-1 rounded-lg bg-gray-100 p-0.5 mb-3">
                    {(["daily", "weekly", "monthly", "range"] as const).map((m) => (
                      <button
                        key={m}
                        onClick={() => setDownloadMode(m)}
                        className={cn(
                          "flex-1 rounded-md py-1 text-xs font-semibold capitalize transition-colors",
                          downloadMode === m ? "bg-white text-brand-600 shadow-sm" : "text-gray-500 hover:text-gray-700"
                        )}
                      >
                        {m === "range" ? "Range" : m}
                      </button>
                    ))}
                  </div>

                  {downloadMode === "range" ? (
                    <div className="space-y-2 mb-3">
                      <div>
                        <label className="block text-xs font-medium text-gray-500 mb-1">From</label>
                        <input
                          type="date"
                          value={downloadRangeFrom}
                          onChange={(e) => setDownloadRangeFrom(e.target.value)}
                          className="block w-full rounded-lg border-0 py-2 px-3 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600"
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-gray-500 mb-1">To</label>
                        <input
                          type="date"
                          value={downloadRangeTo}
                          onChange={(e) => setDownloadRangeTo(e.target.value)}
                          className="block w-full rounded-lg border-0 py-2 px-3 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600"
                        />
                      </div>
                    </div>
                  ) : (
                    <>
                      <label className="block text-xs font-medium text-gray-500 mb-1">
                        {downloadMode === "monthly" ? "Pick any day in that month" : downloadMode === "weekly" ? "Pick any day in that week" : "Select date"}
                      </label>
                      <input
                        type="date"
                        value={downloadDate}
                        onChange={(e) => setDownloadDate(e.target.value)}
                        className="block w-full rounded-lg border-0 py-2 px-3 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600 mb-3"
                      />
                    </>
                  )}

                  <label className="block text-xs font-medium text-gray-500 mb-1">
                    Employee (optional)
                  </label>
                  <select
                    value={downloadEmployeeId}
                    onChange={(e) => setDownloadEmployeeId(e.target.value)}
                    className="block w-full rounded-lg border-0 py-2 px-3 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600 mb-3 bg-white"
                  >
                    <option value="">All Employees</option>
                    {employees.map((emp) => (
                      <option key={emp.id} value={emp.id}>
                        {emp.employeeId} - {emp.firstName} {emp.lastName}
                      </option>
                    ))}
                  </select>

                  <button
                    onClick={handleDownloadPDF}
                    className="w-full rounded-lg bg-brand-600 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors flex items-center justify-center gap-2"
                  >
                    <Download className="h-4 w-4" />
                    Download PDF
                  </button>
                </motion.div>
              )}
            </AnimatePresence>
          </div>

          <button
            onClick={() => setIsSlideOverOpen(true)}
            className="inline-flex items-center justify-center rounded-lg border border-transparent bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors"
          >
            <Clock className="mr-2 h-4 w-4" />
            Terminal Punch
          </button>
        </div>
      </div>

      <div className="rounded-2xl bg-white shadow-sm border border-[#E2E8F0] overflow-hidden">
        <div className="p-6 border-b border-gray-200 bg-gray-50/50 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="relative max-w-md w-full">
            <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
              <Search className="h-4 w-4 text-gray-400" />
            </div>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="block w-full rounded-lg border-0 py-2.5 pl-10 pr-3 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-brand-600 sm:text-sm sm:leading-6"
              placeholder="Search by Employee ID, Name..."
            />
          </div>

          <div className="flex items-center gap-2">
            <label className="text-xs font-bold text-gray-400 uppercase">Filter Date:</label>
            <input
              type="date"
              value={dateFilter}
              onChange={(e) => setDateFilter(e.target.value)}
              className="rounded-lg border-0 py-2 px-3 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600 sm:text-sm"
            />
            {dateFilter && (
              <button
                onClick={() => { setDateFilter(""); setCurrentPage(1); }}
                className="text-xs text-brand-600 font-bold hover:underline"
              >
                Clear
              </button>
            )}
          </div>
        </div>

        {isLoading ? (
          <div className="p-12 text-center text-sm text-gray-500">Loading attendance logs...</div>
        ) : filteredRecords.length === 0 ? (
          <div className="flex flex-col items-center justify-center p-16 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-brand-50 mb-4">
              <UserCheck className="h-8 w-8 text-brand-600" />
            </div>
            <h3 className="text-lg font-medium text-gray-900">No logs today</h3>
            <p className="mt-1 text-sm text-gray-500 max-w-sm">
              Use Terminal Punch to simulate a biometric scan or check-in.
            </p>
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="min-w-full table-fixed divide-y divide-gray-300">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="py-3.5 pl-6 pr-3 text-left text-sm font-semibold text-gray-900 w-[220px] min-w-[220px] max-w-[220px]">Employee</th>
                    <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 w-[100px] min-w-[100px] max-w-[100px]">Date</th>
                    <th
                      onClick={() => handleSort("checkIn")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[110px] min-w-[110px] max-w-[110px]"
                    >
                      <div className="flex items-center gap-1">
                        Check In
                        {sortField === "checkIn" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                    <th
                      onClick={() => handleSort("checkOut")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[110px] min-w-[110px] max-w-[110px]"
                    >
                      <div className="flex items-center gap-1">
                        Check Out
                        {sortField === "checkOut" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                    <th
                      onClick={() => handleSort("worked")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[95px] min-w-[95px] max-w-[95px]"
                    >
                      <div className="flex items-center gap-1">
                        Worked
                        {sortField === "worked" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                    <th
                      onClick={() => handleSort("deduction")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[185px] min-w-[185px] max-w-[185px]"
                    >
                      <div className="flex items-center gap-1">
                        Deduction
                        {sortField === "deduction" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                    <th
                      onClick={() => handleSort("adjusted")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[95px] min-w-[95px] max-w-[95px]"
                    >
                      <div className="flex items-center gap-1">
                        Adjusted
                        {sortField === "adjusted" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                    <th
                      onClick={() => handleSort("otHrs")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[95px] min-w-[95px] max-w-[95px]"
                    >
                      <div className="flex items-center gap-1">
                        OT Hrs
                        {sortField === "otHrs" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                    <th
                      onClick={() => handleSort("otAmount")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[120px] min-w-[120px] max-w-[120px]"
                    >
                      <div className="flex items-center gap-1">
                        OT Amount
                        {sortField === "otAmount" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                    <th
                      onClick={() => handleSort("status")}
                      className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900 cursor-pointer select-none group hover:bg-gray-100/50 transition-colors w-[110px] min-w-[110px] max-w-[110px]"
                    >
                      <div className="flex items-center gap-1">
                        Status
                        {sortField === "status" ? (
                          sortOrder === "asc" ? <ArrowUp className="h-3.5 w-3.5 text-brand-600" /> : <ArrowDown className="h-3.5 w-3.5 text-brand-600" />
                        ) : (
                          <ArrowUpDown className="h-3.5 w-3.5 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity" />
                        )}
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200 bg-white">
                  {pagedRecords.map((rec) => (
                    <motion.tr
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      key={rec.id}
                      className="hover:bg-gray-50 transition-colors"
                    >
                      <td className="whitespace-nowrap py-4 pl-6 pr-3 text-sm w-[220px] min-w-[220px] max-w-[220px]">
                        <div className="flex items-center w-[184px]">
                          <div className="h-10 w-10 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 font-bold uppercase ring-2 ring-white">
                            {rec.employee?.firstName?.charAt(0)}{rec.employee?.lastName?.charAt(0)}
                          </div>
                          <div className="ml-4 min-w-0 flex-1">
                            <div
                              className="font-medium text-gray-900 truncate w-full"
                              title={`${rec.employee?.firstName} ${rec.employee?.lastName}`}
                            >
                              {rec.employee?.firstName} {rec.employee?.lastName}
                            </div>
                            <div className="mt-1 text-gray-500 text-xs font-mono">#{rec.employee?.employeeId}</div>
                          </div>
                        </div>
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                        {new Date(rec.date).toLocaleDateString()}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm font-medium text-green-600">
                        {rec.checkIn ? new Date(rec.checkIn).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true }) : "--:--"}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm font-medium text-red-600">
                        {rec.checkOut ? new Date(rec.checkOut).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true }) : "--:--"}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-600 font-mono">
                        {(() => {
                          const ins = (rec.punches || [])
                            .filter((p: any) => p.checkIn != null && p.deviceSource !== "DELETED_MANUAL")
                            .sort((a: any, b: any) => new Date(a.checkIn!).getTime() - new Date(b.checkIn!).getTime());
                          const outs = (rec.punches || [])
                            .filter((p: any) => p.checkOut && p.deviceSource !== "DELETED_MANUAL")
                            .sort((a: any, b: any) => new Date(a.checkOut!).getTime() - new Date(b.checkOut!).getTime());

                          let totalMin = 0;
                          const len = Math.max(ins.length, outs.length);
                          for (let i = 0; i < len; i++) {
                            const inn = ins[i];
                            const out = outs[i];
                            if (inn?.checkIn && out?.checkOut) {
                              totalMin += (new Date(out.checkOut).getTime() - new Date(inn.checkIn).getTime()) / 60000;
                            }
                          }
                          return totalMin > 0 ? fmtHrs(totalMin / 60) : (rec.totalWorkedHrs > 0 ? fmtHrs(rec.totalWorkedHrs) : "—");
                        })()}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm font-medium font-mono">
                        {rec.deductionAmount > 0 ? (
                          <div>
                            <span className="text-red-600 font-medium">{fmtHrs(rec.deductionHrs)} / Rs {rec.deductionAmount.toFixed(0)}</span>
                          </div>
                        ) : (
                          <span className="text-gray-400">—</span>
                        )}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm font-medium font-mono">
                        {rec.adjustedMins && rec.adjustedMins > 0 ? (
                          <span className="text-orange-600 font-medium">{Math.round(rec.adjustedMins)}m</span>
                        ) : (
                          <span className="text-gray-400">—</span>
                        )}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm font-medium text-gray-500 font-mono">
                        {rec.overtimeHrs > 0 ? fmtHrs(rec.overtimeHrs) : "—"}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm font-medium text-brand-600 font-mono">
                        {rec.overtimeAmount > 0 ? `Rs ${rec.overtimeAmount.toFixed(2)}` : "—"}
                      </td>
                      <td className="whitespace-nowrap px-3 py-4 text-sm">
                        <span className={cn(
                          "inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset",
                          rec.status === "PRESENT" ? "bg-green-50 text-green-700 ring-green-600/20" :
                            rec.status === "LATE" ? "bg-yellow-50 text-yellow-800 ring-yellow-600/20" :
                              rec.status === "EARLY_OUT" ? "bg-orange-50 text-orange-700 ring-orange-600/20" :
                                rec.status === "ON_LEAVE" ? "bg-blue-50 text-blue-700 ring-blue-600/20" :
                                  rec.status === "WEEKLY_OFF" ? "bg-purple-50 text-purple-700 ring-purple-600/20" :
                                    rec.status === "HOLIDAY" ? "bg-pink-50 text-pink-700 ring-pink-600/20" :
                                      "bg-red-50 text-red-700 ring-red-700/10"
                        )}>
                          {rec.status === "WEEKLY_OFF" ? "WEEKLY OFF" : (rec.status === "HOLIDAY" ? (rec.holidayName || "HOLIDAY") : rec.status)}
                        </span>
                      </td>
                    </motion.tr>
                  ))}
                </tbody>
              </table>
            </div>
            {/* Pagination */}
            {filteredRecords.length > PAGE_SIZE && (
              <div className="px-6 py-4 border-t border-gray-200 bg-gray-50/50">
                <div className="flex items-center justify-between">
                  <div className="text-sm text-gray-700">
                    Showing {(currentPage - 1) * PAGE_SIZE + 1} to {Math.min(currentPage * PAGE_SIZE, filteredRecords.length)} of {filteredRecords.length} results
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                      disabled={currentPage === 1}
                      className="px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Previous
                    </button>
                    <div className="flex items-center gap-1">
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum;
                        if (totalPages <= 5) {
                          pageNum = i + 1;
                        } else if (currentPage <= 3) {
                          pageNum = i + 1;
                        } else if (currentPage >= totalPages - 2) {
                          pageNum = totalPages - 4 + i;
                        } else {
                          pageNum = currentPage - 2 + i;
                        }
                        return (
                          <button
                            key={pageNum}
                            onClick={() => setCurrentPage(pageNum)}
                            className={`px-3 py-2 text-sm font-medium rounded-md ${
                              currentPage === pageNum
                                ? "bg-brand-600 text-white"
                                : "text-gray-700 bg-white border border-gray-300 hover:bg-gray-50"
                            }`}
                          >
                            {pageNum}
                          </button>
                        );
                      })}
                    </div>
                    <button
                      onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                      disabled={currentPage === totalPages}
                      className="px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Next
                    </button>
                  </div>
                </div>
              </div>
            )}
          </>
        )}
      </div>

      {/* Punch Detail Popup */}
      <AnimatePresence>
        {punchModal && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setPunchModal(null)}
              className="fixed inset-0 bg-gray-900/50 backdrop-blur-sm z-40"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 16 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 16 }}
              transition={{ type: "spring", bounce: 0, duration: 0.3 }}
              className="fixed inset-0 z-50 flex items-center justify-center p-6"
              onClick={() => setPunchModal(null)}
            >
              <div
                className="bg-white rounded-3xl shadow-2xl border border-gray-200 w-full max-w-2xl max-h-[88vh] overflow-y-auto flex flex-col"
                onClick={(e) => e.stopPropagation()}
              >
                {/* Header */}
                <div className="px-8 py-6 border-b border-gray-100 flex items-center justify-between bg-gradient-to-r from-brand-50 to-white rounded-t-3xl">
                  <div className="flex items-center gap-4">
                    <div className="h-14 w-14 rounded-2xl bg-brand-600 flex items-center justify-center text-white text-xl font-bold shadow-md">
                      {punchModal.employee?.firstName?.charAt(0)}{punchModal.employee?.lastName?.charAt(0)}
                    </div>
                    <div>
                      <h3 className="text-xl font-bold text-gray-900">
                        {punchModal.employee?.firstName} {punchModal.employee?.lastName}
                      </h3>
                      <p className="text-sm text-gray-500 mt-0.5">
                        {new Date(punchModal.date).toLocaleDateString("en-PK", { weekday: "long", day: "2-digit", month: "long", year: "numeric" })}
                      </p>
                      <span className={cn(
                        "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold mt-1.5",
                        punchModal.status === "PRESENT" ? "bg-green-100 text-green-700" :
                          punchModal.status === "LATE" ? "bg-yellow-100 text-yellow-700" :
                            punchModal.status === "ON_LEAVE" ? "bg-blue-100 text-blue-700" :
                              punchModal.status === "WEEKLY_OFF" ? "bg-purple-100 text-purple-700" :
                                "bg-red-100 text-red-700"
                      )}>{punchModal.status === "WEEKLY_OFF" ? "WEEKLY OFF" : punchModal.status}</span>
                    </div>
                  </div>
                  <button onClick={() => setPunchModal(null)} className="rounded-full p-2.5 text-gray-400 hover:bg-white hover:text-gray-600 transition-colors shadow-sm border border-gray-100">
                    <X className="h-5 w-5" />
                  </button>
                </div>

                {/* Summary Cards */}
                <div className="px-8 py-4 grid grid-cols-3 gap-3 border-b border-gray-100 bg-gray-50/60">
                  <div className="rounded-xl bg-white border border-gray-200 px-4 py-3 shadow-sm">
                    <p className="text-xs text-gray-400 font-medium">Check In</p>
                    <p className="text-sm font-bold text-green-600 mt-0.5 font-mono">{punchModal.checkIn ? new Date(punchModal.checkIn).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true }) : "—"}</p>
                  </div>
                  <div className="rounded-xl bg-white border border-gray-200 px-4 py-3 shadow-sm">
                    <p className="text-xs text-gray-400 font-medium">Check Out</p>
                    <p className="text-sm font-bold text-red-500 mt-0.5 font-mono">{punchModal.checkOut ? new Date(punchModal.checkOut).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true }) : "—"}</p>
                  </div>
                  <div className="rounded-xl bg-white border border-gray-200 px-4 py-3 shadow-sm">
                    <p className="text-xs text-gray-400 font-medium">Total Worked</p>
                    <p className="text-sm font-bold text-gray-800 mt-0.5 font-mono">{
                      (() => {
                        const ins = [...punchModal.punches]
                          .filter((p) => p.checkIn != null && p.deviceSource !== "DELETED_MANUAL")
                          .sort((a, b) => new Date(a.checkIn!).getTime() - new Date(b.checkIn!).getTime());
                        const outs = [...punchModal.punches]
                          .filter((p) => p.checkOut && p.deviceSource !== "DELETED_MANUAL")
                          .sort((a, b) => new Date(a.checkOut!).getTime() - new Date(b.checkOut!).getTime());

                        let totalMin = 0;
                        const len = Math.max(ins.length, outs.length);
                        for (let i = 0; i < len; i++) {
                          const inn = ins[i];
                          const out = outs[i];
                          if (inn?.checkIn && out?.checkOut) {
                            totalMin += (new Date(out.checkOut).getTime() - new Date(inn.checkIn).getTime()) / 60000;
                          }
                        }
                        return totalMin > 0 ? fmtHrs(totalMin / 60) : "—";
                      })()
                    }</p>
                  </div>
                </div>

                {/* Override Edit */}
                <div className="px-8 py-4 border-b border-gray-100">
                  <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Override Day Check In/Out</p>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-3">
                      <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-gray-400 uppercase">In Date</label>
                        <input type="date" value={editInDate} onChange={e => setEditInDate(e.target.value)}
                          className="border border-gray-200 rounded-xl px-3 py-2 text-sm text-gray-700 bg-white focus:ring-2 focus:ring-brand-500 focus:outline-none shadow-sm" />
                      </div>
                      <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-gray-400 uppercase">In Time</label>
                        <input type="time" value={editInTime} onChange={e => setEditInTime(e.target.value)}
                          onKeyDown={e => {
                            if (e.key === 'Enter') {
                              e.preventDefault();
                              document.getElementById("out-time-input")?.focus();
                            }
                          }}
                          className="border border-gray-200 rounded-xl px-3 py-2 text-sm text-gray-700 bg-white focus:ring-2 focus:ring-brand-500 focus:outline-none shadow-sm" />
                      </div>
                    </div>
                    <div className="space-y-3">
                      <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-gray-400 uppercase">Out Date</label>
                        <input type="date" value={editOutDate} onChange={e => setEditOutDate(e.target.value)}
                          className="border border-gray-200 rounded-xl px-3 py-2 text-sm text-gray-700 bg-white focus:ring-2 focus:ring-brand-500 focus:outline-none shadow-sm" />
                      </div>
                      <div className="flex flex-col gap-1">
                        <label className="text-[10px] font-bold text-gray-400 uppercase">Out Time</label>
                        <input id="out-time-input" type="time" value={editOutTime} onChange={e => setEditOutTime(e.target.value)}
                          className="border border-gray-200 rounded-xl px-3 py-2 text-sm text-gray-700 bg-white focus:ring-2 focus:ring-brand-500 focus:outline-none shadow-sm" />
                      </div>
                    </div>
                  </div>
                  <div className="mt-4 flex justify-end">
                    <button
                      disabled={savingEdit || !editInTime || !editOutTime || !editInDate || !editOutDate}
                      onClick={async () => {
                        if (!punchModal || !editInTime || !editOutTime || !editInDate || !editOutDate) return;
                        try {
                          setSavingEdit(true);
                          const overrideRes = await authFetch(`${API}/dash/attendance/${punchModal.id}`, {
                            method: "PATCH",
                            headers: { "Content-Type": "application/json" },
                            body: JSON.stringify({
                              checkIn: new Date(`${editInDate}T${editInTime}:00`).toISOString(),
                              checkOut: new Date(`${editOutDate}T${editOutTime}:00`).toISOString(),
                            }),
                          });
                          if (!overrideRes.ok) { const e = await overrideRes.json().catch(() => null); alert(e?.message || "Failed to save"); return; }
                          const fresh = await overrideRes.json();
                          if (fresh) {
                            setPunchModal(fresh);
                            setRecords(prev => prev.map(r => r.id === fresh.id ? { ...r, ...fresh } : r));
                          }
                        } catch { alert("Failed to save. Check console."); }
                        finally { setSavingEdit(false); }
                      }}
                      className={cn(
                        "inline-flex items-center rounded-xl px-8 py-2.5 text-sm font-bold shadow-md transition-all active:scale-95",
                        savingEdit || !editInTime || !editOutTime || !editInDate || !editOutDate
                          ? "bg-gray-100 text-gray-400 cursor-not-allowed"
                          : "bg-brand-600 text-white hover:bg-brand-700"
                      )}
                    >
                      {savingEdit ? "Saving…" : "Save Override"}
                    </button>
                  </div>
                </div>

                <div className="px-8 py-5">
                  <div className="flex items-center justify-between mb-4">
                    <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">Punch Timeline</p>
                    <button
                      onClick={() => {
                        setEditingPunchId("new");
                        const d = new Date(punchModal.date);
                        const dStr = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
                        setPunchEditIn("");
                        setPunchEditInDate(dStr);
                        setPunchEditOut("");
                        setPunchEditOutDate(dStr);
                      }}
                      className="text-xs font-bold text-brand-600 hover:text-brand-700 flex items-center gap-1 bg-brand-50 px-2.5 py-1.5 rounded-xl transition-all active:scale-95 border border-brand-100 shadow-sm"
                    >
                      <Plus className="h-3.5 w-3.5" /> Add New Punch
                    </button>
                  </div>
                  {punchModal.punches && punchModal.punches.length > 0 || editingPunchId === "new" ? (
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="text-xs text-gray-400 uppercase tracking-wider bg-gray-50 rounded-lg">
                          <th className="text-left px-3 py-2.5 font-semibold rounded-l-lg">#</th>
                          <th className="text-left px-3 py-2.5 font-semibold">Check In</th>
                          <th className="text-left px-3 py-2.5 font-semibold">Check Out</th>
                          <th className="text-right px-3 py-2.5 font-semibold rounded-r-lg">Duration</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-gray-50">
                        {editingPunchId === "new" && (
                          <tr className="bg-brand-50/40 animate-in fade-in slide-in-from-top-1 duration-200">
                            <td className="py-2.5 font-mono text-xs text-brand-600 font-bold px-3">NEW</td>
                            <td className="py-2 space-y-1 px-3">
                              <div className="flex flex-col gap-1">
                                <input type="date" value={punchEditInDate} onChange={e => setPunchEditInDate(e.target.value)}
                                  className="border border-brand-200 rounded-lg px-2 py-1 text-[10px] w-full focus:ring-2 focus:ring-brand-500 focus:outline-none bg-white shadow-sm text-gray-900" />
                                <input type="time" value={punchEditIn} onChange={e => setPunchEditIn(e.target.value)}
                                  onKeyDown={e => {
                                    if (e.key === 'Enter') {
                                      e.preventDefault();
                                      document.getElementById("new-punch-out-time")?.focus();
                                    }
                                  }}
                                  className="border border-brand-200 rounded-lg px-2 py-1 text-xs w-full focus:ring-2 focus:ring-brand-500 focus:outline-none bg-white shadow-sm text-gray-900" />
                              </div>
                            </td>
                            <td className="py-2 space-y-1 px-3">
                              <div className="flex flex-col gap-1">
                                <input type="date" value={punchEditOutDate} onChange={e => setPunchEditOutDate(e.target.value)}
                                  className="border border-brand-200 rounded-lg px-2 py-1 text-[10px] w-full focus:ring-2 focus:ring-brand-500 focus:outline-none bg-white shadow-sm text-gray-900" />
                                <input id="new-punch-out-time" type="time" value={punchEditOut} onChange={e => setPunchEditOut(e.target.value)}
                                  className="border border-brand-200 rounded-lg px-2 py-1 text-xs w-full focus:ring-2 focus:ring-brand-500 focus:outline-none bg-white shadow-sm text-gray-900" />
                              </div>
                            </td>
                            <td className="py-2 text-right px-3">
                              <div className="flex items-center justify-end gap-2">
                                <button
                                  disabled={savingPunch || (!punchEditIn && !punchEditOut)}
                                  onClick={async () => {
                                    if (!punchEditIn && !punchEditOut) return;
                                    setSavingPunch(true);
                                    try {
                                      const res = await authFetch(`${API}/dash/attendance/${punchModal.id}/punches`, {
                                        method: "POST",
                                        headers: { "Content-Type": "application/json" },
                                        body: JSON.stringify({
                                          checkIn: punchEditIn ? new Date(`${punchEditInDate}T${punchEditIn}:00`).toISOString() : null,
                                          checkOut: punchEditOut ? new Date(`${punchEditOutDate}T${punchEditOut}:00`).toISOString() : null,
                                          deviceSource: "MANUAL_EDIT"
                                        }),
                                      });
                                      if (!res.ok) { alert("Failed to create punch"); return; }
                                      setEditingPunchId(null);
                                      const refreshRes = await authFetch(`${API}/dash/attendance`);
                                      if (refreshRes.ok) {
                                        const data = await refreshRes.json();
                                        const fetchedRecords = Array.isArray(data) ? data : (data.records || []);
                                        setRecords(fetchedRecords);
                                        const fresh = fetchedRecords.find((r: AttendanceRecord) => r.id === punchModal.id);
                                        if (fresh) setPunchModal(fresh);
                                      }
                                    } catch (e) {
                                      alert("Error creating punch");
                                    } finally {
                                      setSavingPunch(false);
                                    }
                                  }}
                                  className="rounded-lg px-3 py-1.5 text-xs font-bold bg-brand-600 text-white hover:bg-brand-700 shadow-sm transition-all active:scale-95 disabled:opacity-50"
                                >{savingPunch ? "..." : "Create"}</button>
                                <button onClick={() => setEditingPunchId(null)}
                                  className="rounded-lg px-3 py-1.5 text-xs font-semibold text-gray-500 hover:bg-white hover:text-gray-700 border border-gray-200 shadow-sm transition-all active:scale-95">Cancel</button>
                              </div>
                            </td>
                          </tr>
                        )}
                        {(() => {
                          const ins = [...punchModal.punches]
                            .filter((p) => p.checkIn != null && p.deviceSource !== "DELETED_MANUAL")
                            .sort((a, b) => new Date(a.checkIn!).getTime() - new Date(b.checkIn!).getTime());
                          const outs = [...punchModal.punches]
                            .filter((p) => p.checkOut && p.deviceSource !== "DELETED_MANUAL")
                            .sort((a, b) => new Date(a.checkOut!).getTime() - new Date(b.checkOut!).getTime());
                          const rows = Array.from({ length: Math.max(ins.length, outs.length) }, (_, i) => ({
                            inn: ins[i] || null,
                            out: outs[i] || null,
                            rowKey: `${ins[i]?.id || ""}-${outs[i]?.id || ""}`,
                          }));
                          return rows.map((row, i) => {
                            const dur = row.inn?.checkIn && row.out?.checkOut
                              ? (new Date(row.out.checkOut).getTime() - new Date(row.inn.checkIn).getTime()) / 3_600_000
                              : 0;
                            const isEditing = editingPunchId === row.rowKey;
                            const toTime = (iso: string | null) => {
                              if (!iso) return "";
                              const d = new Date(iso);
                              return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
                            };
                            return (
                              <tr key={row.rowKey} className="text-gray-700 group">
                                <td className="py-2.5 font-mono text-xs text-gray-400">{i + 1}</td>
                                {isEditing ? (
                                  <>
                                    <td className="py-1.5 space-y-1">
                                      <input type="date" value={punchEditInDate} onChange={e => setPunchEditInDate(e.target.value)}
                                        className="border border-gray-200 rounded px-1.5 py-1 text-[10px] w-28 focus:ring-1 focus:ring-brand-500 focus:outline-none text-gray-900" />
                                      <input type="time" value={punchEditIn} onChange={e => setPunchEditIn(e.target.value)}
                                        onKeyDown={e => {
                                          if (e.key === 'Enter') {
                                            e.preventDefault();
                                            document.getElementById(`punch-out-time-${row.rowKey}`)?.focus();
                                          }
                                        }}
                                        className="border border-gray-200 rounded px-1.5 py-1 text-xs w-28 focus:ring-1 focus:ring-brand-500 focus:outline-none text-gray-900" />
                                    </td>
                                    <td className="py-1.5 space-y-1">
                                      <input type="date" value={punchEditOutDate} onChange={e => setPunchEditOutDate(e.target.value)}
                                        className="border border-gray-200 rounded px-1.5 py-1 text-[10px] w-28 focus:ring-1 focus:ring-brand-500 focus:outline-none text-gray-900" />
                                      <input id={`punch-out-time-${row.rowKey}`} type="time" value={punchEditOut} onChange={e => setPunchEditOut(e.target.value)}
                                        className="border border-gray-200 rounded px-1.5 py-1 text-xs w-28 focus:ring-1 focus:ring-brand-500 focus:outline-none text-gray-900" />
                                    </td>
                                    <td className="py-1.5 text-right">
                                      <div className="flex items-center justify-end gap-1">
                                        <button
                                          disabled={savingPunch}
                                          onClick={async () => {
                                            setSavingPunch(true);
                                            try {
                                              let finalAttendance = null;
                                              const sameRecord = row.inn?.id && row.out?.id && row.inn.id === row.out.id;
                                              if (sameRecord && row.inn?.id) {
                                                // Single punch record holds both checkIn and checkOut — one PATCH
                                                const body: Record<string, string> = {};
                                                if (punchEditIn && punchEditInDate) body.checkIn = new Date(`${punchEditInDate}T${punchEditIn}:00`).toISOString();
                                                if (punchEditOut && punchEditOutDate) body.checkOut = new Date(`${punchEditOutDate}T${punchEditOut}:00`).toISOString();
                                                const res = await authFetch(`${API}/dash/attendance/punches/${row.inn.id}`, {
                                                  method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
                                                });
                                                if (!res.ok) { alert("Failed to save punch"); return; }
                                                finalAttendance = (await res.json()).attendance;
                                              } else {
                                                // Separate punch records for check-in and check-out
                                                if (row.inn?.id && punchEditIn && punchEditInDate) {
                                                  const res = await authFetch(`${API}/dash/attendance/punches/${row.inn.id}`, {
                                                    method: "PATCH", headers: { "Content-Type": "application/json" },
                                                    body: JSON.stringify({ checkIn: new Date(`${punchEditInDate}T${punchEditIn}:00`).toISOString() }),
                                                  });
                                                  if (!res.ok) { alert("Failed to save check-in"); return; }
                                                  finalAttendance = (await res.json()).attendance;
                                                } else if (!row.inn && punchEditIn && punchEditInDate) {
                                                  // No checkIn punch — create a new separate checkIn punch record
                                                  const res = await authFetch(`${API}/dash/attendance/${punchModal.id}/punches`, {
                                                    method: "POST", headers: { "Content-Type": "application/json" },
                                                    body: JSON.stringify({ checkIn: new Date(`${punchEditInDate}T${punchEditIn}:00`).toISOString(), deviceSource: "MANUAL_EDIT" }),
                                                  });
                                                  if (!res.ok) { alert("Failed to create check-in punch"); return; }
                                                }
                                                if (row.out?.id && punchEditOut && punchEditOutDate) {
                                                  const res = await authFetch(`${API}/dash/attendance/punches/${row.out.id}`, {
                                                    method: "PATCH", headers: { "Content-Type": "application/json" },
                                                    body: JSON.stringify({ checkOut: new Date(`${punchEditOutDate}T${punchEditOut}:00`).toISOString() }),
                                                  });
                                                  if (!res.ok) { alert("Failed to save check-out"); return; }
                                                  finalAttendance = (await res.json()).attendance;
                                                }
                                              }
                                              setEditingPunchId(null);
                                              const refreshRes = await authFetch(`${API}/dash/attendance`);
                                              if (refreshRes.ok) {
                                                const data = await refreshRes.json();
                                                const fetchedRecords = Array.isArray(data) ? data : (data.records || []);
                                                setRecords(fetchedRecords);
                                                const fresh = fetchedRecords.find((r: AttendanceRecord) => r.id === punchModal.id);
                                                if (fresh) setPunchModal(fresh);
                                              }
                                            } finally { setSavingPunch(false); }
                                          }}
                                          className="rounded px-2 py-1 text-xs font-semibold bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50"
                                        >{savingPunch ? "…" : "Save"}</button>
                                        <button onClick={() => setEditingPunchId(null)}
                                          className="rounded px-2 py-1 text-xs text-gray-500 hover:bg-gray-100">Cancel</button>
                                      </div>
                                    </td>
                                  </>
                                ) : (
                                  <>
                                    <td className="py-2.5 font-medium text-green-600">
                                      {row.inn?.checkIn ? new Date(row.inn.checkIn).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true }) : "—"}
                                    </td>
                                    <td className="py-2.5 font-medium text-red-500">
                                      {row.out?.checkOut ? new Date(row.out.checkOut).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit", hour12: true }) : "—"}
                                    </td>
                                    <td className="py-2.5 text-right font-mono text-xs">
                                      <div className="flex items-center justify-end gap-2">
                                        <span>{row.inn && row.out ? `${Math.floor(dur)}h ${Math.round((dur % 1) * 60)}m` : "…"}</span>
                                        <button
                                          onClick={() => {
                                            setEditingPunchId(row.rowKey);
                                            const toDateStr = (iso: string | null) => {
                                              if (!iso) return "";
                                              const d = new Date(iso);
                                              return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
                                            };
                                            setPunchEditIn(toTime(row.inn?.checkIn || null));
                                            setPunchEditInDate(toDateStr(row.inn?.checkIn || null));
                                            setPunchEditOut(toTime(row.out?.checkOut || null));
                                            setPunchEditOutDate(toDateStr(row.out?.checkOut || null));
                                          }}
                                          className="opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-brand-600"
                                          title="Edit this row"
                                        >
                                          <svg xmlns="http://www.w3.org/2000/svg" className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" /><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" /></svg>
                                        </button>
                                        {(row.inn?.id || row.out?.id) && (
                                          <button
                                            onClick={async () => {
                                              const targetPunch = row.inn || row.out;
                                              const isInn = !!row.inn;
                                              if (!confirm(`Remove this ${isInn ? "check-in" : "check-out"} punch? It will also be deleted from the device.`)) return;
                                              const punchSource = targetPunch!.deviceSource as string | null;
                                              console.log("[Punch Delete] deviceSource:", punchSource);
                                              if (punchSource?.startsWith("ZKTECO:")) {
                                                const txId = punchSource.replace("ZKTECO:", "");
                                                const delRes = await authFetch(`${API}/dash/zkteco/delete-transaction`, {
                                                  method: "DELETE", headers: { "Content-Type": "application/json" },
                                                  body: JSON.stringify({ transactionId: txId }),
                                                });
                                                const delData = await delRes.json().catch(() => null);
                                                console.log("[Punch Delete] Device delete response:", delData);
                                                if (!delRes.ok) console.warn("[Punch Delete] Device delete failed:", delData?.message);
                                              } else {
                                                console.warn("[Punch Delete] No ZKTECO: ID found in deviceSource — device delete skipped. Source:", punchSource);
                                              }
                                              const body = isInn ? { clearCheckIn: true } : { clearCheckOut: true };
                                              const res = await authFetch(`${API}/dash/attendance/punches/${targetPunch!.id}`, {
                                                method: "PATCH", headers: { "Content-Type": "application/json" },
                                                body: JSON.stringify(body),
                                              });
                                              if (!res.ok) { alert("Failed to remove punch"); return; }
                                              const refreshRes = await authFetch(`${API}/dash/attendance`);
                                              if (refreshRes.ok) {
                                                const data = await refreshRes.json();
                                                const fetchedRecords = Array.isArray(data) ? data : (data.records || []);
                                                setRecords(fetchedRecords);
                                                const fresh = fetchedRecords.find((r: AttendanceRecord) => r.id === punchModal.id);
                                                if (fresh) setPunchModal(fresh);
                                              }
                                            }}
                                            className="opacity-0 group-hover:opacity-100 transition-opacity text-gray-400 hover:text-red-500"
                                            title="Remove this punch"
                                          >
                                            <svg xmlns="http://www.w3.org/2000/svg" className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10" /><path d="M15 9l-6 6M9 9l6 6" /></svg>
                                          </button>
                                        )}
                                      </div>
                                    </td>
                                  </>
                                )}
                              </tr>
                            );
                          });
                        })()}
                      </tbody>
                    </table>
                  ) : (
                    <p className="text-sm text-gray-400 italic py-2">No punch records found.</p>
                  )}
                </div>

                <div className="px-8 py-6 border-t border-gray-100 bg-gray-50/40 rounded-b-3xl mt-auto">
                  <div className="flex items-center justify-between">
                    <div>
                      <h4 className="text-sm font-semibold text-gray-900">Manage Record</h4>
                      <p className="text-xs text-gray-500 mt-0.5">Completely remove this day's attendance for this employee.</p>
                    </div>
                    <button
                      disabled={deletingRecord || punchModal.id.startsWith("absent-")}
                      onClick={async () => {
                        if (!punchModal || punchModal.id.startsWith("absent-")) return;
                        if (!confirm(`Are you sure you want to delete the attendance record for ${punchModal.employee?.firstName} on ${new Date(punchModal.date).toLocaleDateString()}? This cannot be undone.`)) return;

                        try {
                          setDeletingRecord(true);
                          const res = await authFetch(`${API}/dash/attendance/${punchModal.id}`, { method: "DELETE" });
                          if (!res.ok) {
                            const e = await res.json().catch(() => null);
                            alert(e?.message || "Failed to delete");
                            return;
                          }
                          setPunchModal(null);
                          setRecords(prev => prev.filter(r => r.id !== punchModal.id));
                        } catch (err) {
                          alert("An error occurred while deleting.");
                        } finally {
                          setDeletingRecord(false);
                        }
                      }}
                      className="inline-flex items-center gap-2 px-4 py-2 text-sm font-semibold text-red-600 hover:bg-red-50 rounded-xl transition-colors disabled:opacity-40"
                    >
                      <Trash2 className="h-4 w-4" />
                      {deletingRecord ? "Deleting..." : "Delete Record"}
                    </button>
                  </div>
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* Slide-over for Terminal Punch */}
      <AnimatePresence>
        {isSlideOverOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsSlideOverOpen(false)}
              className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm z-40 transition-opacity"
            />
            <motion.div
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", bounce: 0, duration: 0.4 }}
              className="fixed inset-y-0 right-0 z-50 w-full max-w-md bg-white text-gray-900 shadow-2xl flex flex-col border-l border-gray-200"
            >
              <div className="flex items-center justify-between px-6 py-5 border-b border-gray-100 bg-white/50 backdrop-blur-md">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-brand-50 border border-brand-100">
                    <Clock className="h-5 w-5 text-brand-600" />
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-gray-900">Terminal Punch</h2>
                    <p className="text-xs text-gray-500 font-medium mt-0.5">Simulate Biometric Scan</p>
                  </div>
                </div>
                <button
                  onClick={() => setIsSlideOverOpen(false)}
                  className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto px-6 py-6 custom-scrollbar bg-gray-50/30">
                <div className="space-y-6">

                  <div className="space-y-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-900/5">
                    <div>
                      <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Select Employee</label>
                      <select required value={selectedEmployeeId} onChange={e => setSelectedEmployeeId(e.target.value)} className="block w-full rounded-lg border-0 py-2.5 pl-3 pr-8 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm sm:leading-6 transition-colors shadow-sm appearance-none">
                        <option value="" disabled>Search or Select...</option>
                        {employees.map(emp => (
                          <option key={emp.id} value={emp.id}>{emp.firstName} {emp.lastName} (#{emp.employeeId})</option>
                        ))}
                      </select>
                    </div>

                    <div className="flex items-center justify-between rounded-lg bg-gray-50 px-3 py-2.5 ring-1 ring-gray-200">
                      <div>
                        <p className="text-xs font-semibold text-gray-700">Manual Entry</p>
                        <p className="text-xs text-gray-400">Override with custom date & time</p>
                      </div>
                      <button
                        onClick={() => setUseManualTime(v => !v)}
                        className={cn(
                          "relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none",
                          useManualTime ? "bg-brand-600" : "bg-gray-300"
                        )}
                      >
                        <span className={cn(
                          "inline-block h-4 w-4 transform rounded-full bg-white shadow ring-0 transition duration-200 ease-in-out",
                          useManualTime ? "translate-x-4" : "translate-x-0"
                        )} />
                      </button>
                    </div>

                    {useManualTime && (
                      <div className="grid grid-cols-2 gap-3">
                        <div>
                          <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1">Date</label>
                          <input
                            type="date"
                            value={manualDate}
                            onChange={e => setManualDate(e.target.value)}
                            className="block w-full rounded-lg border-0 py-2 px-3 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600"
                          />
                        </div>
                        <div>
                          <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1">Time</label>
                          <input
                            type="time"
                            value={manualTime}
                            onChange={e => setManualTime(e.target.value)}
                            className="block w-full rounded-lg border-0 py-2 px-3 text-sm text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600"
                          />
                        </div>
                      </div>
                    )}

                    <div className="grid grid-cols-2 gap-4">
                      <button
                        onClick={handleClockIn}
                        className="flex flex-col items-center justify-center p-4 rounded-xl border-2 border-dashed border-green-200 bg-green-50 text-green-700 hover:bg-green-100 transition-colors group"
                      >
                        <Play className="h-6 w-6 mb-2 group-hover:scale-110 transition-transform" />
                        <span className="text-sm font-bold uppercase tracking-tight">Clock In</span>
                      </button>
                      <button
                        onClick={handleClockOut}
                        className="flex flex-col items-center justify-center p-4 rounded-xl border-2 border-dashed border-red-200 bg-red-50 text-red-700 hover:bg-red-100 transition-colors group"
                      >
                        <Square className="h-6 w-6 mb-2 group-hover:scale-110 transition-transform" />
                        <span className="text-sm font-bold uppercase tracking-tight">Clock Out</span>
                      </button>
                    </div>
                  </div>

                  <div className="rounded-xl bg-brand-600 p-5 text-white shadow-lg">
                    <div className="flex items-center gap-3">
                      <Clock className="h-6 w-6 opacity-80" />
                      <div>
                        <p className="text-xs font-medium uppercase tracking-widest opacity-80">Local Server Time</p>
                        <p className="text-2xl font-bold font-mono">{new Date().toLocaleTimeString()}</p>
                      </div>
                    </div>
                  </div>

                </div>
              </div>

              <div className="border-t border-gray-100 px-6 py-4 bg-white">
                <p className="text-xs text-center text-gray-400">
                  This simulated terminal will record the actual timestamp for attendance calculations.
                </p>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}

function SummaryCard({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <div className="rounded-lg bg-white border border-gray-200 px-3 py-2.5 shadow-sm">
      <p className="text-xs text-gray-400 font-medium">{label}</p>
      <p className={cn("text-sm font-bold mt-0.5", color)}>{value}</p>
    </div>
  );
}



