"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  ShieldCheck, Plus, FileSignature, Download, Info, UserPlus,
  XCircle, AlertTriangle, CheckCircle2, RefreshCw, BookOpen,
  Scale, ChevronDown, ChevronUp, Loader2, Coins,
} from "lucide-react";
import { downloadCompliancePolicyPDF, downloadGratuityPDF, downloadGratuityPDFUrdu, getCompanyName } from "@/lib/pdf";
import { cn } from "@/lib/utils";

interface Policy {
  id: string;
  title: string;
  description: string;
  _count: { signatures: number };
}

interface ComplianceCheck {
  label: string;
  law: string;
  status: "COMPLIANT" | "WARNING" | "VIOLATION";
  violations: { employeeId: string; name: string; basicSalary?: number; joiningDate?: string; issue?: string }[];
}

interface GratuityRecord {
  id: string;
  yearsOfService: number;
  amount: number;
  settlementDate: string | null;
  status: string;
  employee: { firstName: string; lastName: string; employeeId: string; designation?: string; department?: string; cnic?: string; joiningDate?: string; basicSalary?: number; bankName?: string; accountNumber?: string };
}

interface ChecksResult {
  minimumWage: ComplianceCheck;
  socialSecurity: ComplianceCheck;
  contracts: ComplianceCheck;
  payroll: ComplianceCheck;
  gratuity: ComplianceCheck;
  summary: {
    totalEmployees: number;
    checksRun: number;
    violations: number;
    warnings: number;
    minimumWage: number;
    checkedMonth: number;
    checkedYear: number;
  };
}

const LAW_CATEGORIES = [
  { label: "Wages & Pay", color: "bg-blue-50 text-blue-700 ring-blue-600/20" },
  { label: "Social Security", color: "bg-green-50 text-green-700 ring-green-600/20" },
  { label: "Safety & Health", color: "bg-amber-50 text-amber-700 ring-amber-600/20" },
  { label: "Leave & Benefits", color: "bg-purple-50 text-purple-700 ring-purple-600/20" },
  { label: "Employment Terms", color: "bg-brand-50 text-brand-700 ring-brand-600/20" },
  { label: "Anti-Harassment", color: "bg-rose-50 text-rose-700 ring-rose-600/20" },
];

function categoryForTitle(title: string): { label: string; color: string } {
  if (/wage|payment|wages|overtime|salary/i.test(title)) return LAW_CATEGORIES[0];
  if (/eobi|pessi|social|gratuity|compensation/i.test(title)) return LAW_CATEGORIES[1];
  if (/factory|factories|safety|health|posh|accident/i.test(title)) return LAW_CATEGORIES[2];
  if (/leave|maternity|annual|casual|sick/i.test(title)) return LAW_CATEGORIES[3];
  if (/standing|terms|employment|child/i.test(title)) return LAW_CATEGORIES[4];
  if (/harassment/i.test(title)) return LAW_CATEGORIES[5];
  return LAW_CATEGORIES[4];
}

export default function CompliancePage() {
  const [policies, setPolicies] = useState<Policy[]>([]);
  const [checks, setChecks] = useState<ChecksResult | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isChecksLoading, setIsChecksLoading] = useState(true);
  const [isSeeding, setIsSeeding] = useState(false);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [isSignModalOpen, setIsSignModalOpen] = useState(false);
  const [employees, setEmployees] = useState<any[]>([]);
  const [selectedPolicy, setSelectedPolicy] = useState<Policy | null>(null);
  const [expandedCheck, setExpandedCheck] = useState<string | null>(null);
  const [expandedPolicy, setExpandedPolicy] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<"checks" | "policies" | "gratuity">("checks");
  const [gratuityRecords, setGratuityRecords] = useState<GratuityRecord[]>([]);
  const [gratuityLoading, setGratuityLoading] = useState(false);
  const [markingPaid, setMarkingPaid] = useState<string | null>(null);
  const [newPolicy, setNewPolicy] = useState({ title: "", description: "" });
  const [signData, setSignData] = useState({ employeeId: "" });

  const fetchPolicies = async () => {
    try {
      setIsLoading(true);
      const res = await authFetch(`${API}/dash/compliance/policies`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) setPolicies(data);
    } catch { /* ignore */ } finally { setIsLoading(false); }
  };

  const fetchChecks = async (force = false) => {
    try {
      setIsChecksLoading(true);
      const url = force ? `${API}/dash/compliance/checks?generate=true` : `${API}/dash/compliance/checks`;
      const res = await authFetch(url);
      const data = await res.json();
      if (res.ok) setChecks(data);
    } catch { /* ignore */ } finally { setIsChecksLoading(false); }
  };

  const fetchGratuities = async () => {
    try {
      setGratuityLoading(true);
      const res = await authFetch(`${API}/dash/gratuity`);
      if (res.ok) setGratuityRecords(await res.json());
    } catch { /* ignore */ } finally { setGratuityLoading(false); }
  };

  const handleMarkGratuityPaid = async (v: ComplianceCheck["violations"][number]) => {
    setMarkingPaid(v.employeeId);
    try {
      const joining = v.joiningDate ? new Date(v.joiningDate) : null;
      const years = joining ? Math.floor((Date.now() - joining.getTime()) / (365.25*24*3600*1000)) : 0;
      const amount = (v.basicSalary ?? 0) * years;
      const res = await authFetch(`${API}/dash/gratuity`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ employeeId: v.employeeId, yearsOfService: years, amount, settlementDate: new Date().toISOString().slice(0,10) }),
      });
      if (res.ok) { await fetchChecks(); await fetchGratuities(); }
      else alert("Failed to mark as paid.");
    } catch { alert("Error."); } finally { setMarkingPaid(null); }
  };

  const fetchEmployees = async () => {
    try {
      const res = await authFetch(`${API}/dash/employees?limit=1000`);
      const data = await res.json();
      if (res.ok) {
        const list = Array.isArray(data) ? data : data.employees;
        if (Array.isArray(list)) setEmployees(list);
      }
    } catch { /* ignore */ }
  };

  useEffect(() => {
    fetchPolicies();
    fetchChecks();
    fetchEmployees();
    fetchGratuities();
  }, []);

  const handleSeedPunjab = async () => {
    setIsSeeding(true);
    try {
      await authFetch(`${API}/dash/compliance/seed-punjab`, { method: "POST" });
      await fetchPolicies();
      setActiveTab("policies");
    } catch { /* ignore */ } finally { setIsSeeding(false); }
  };

  const handleCreatePolicy = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await authFetch(`${API}/dash/compliance/policies`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newPolicy),
      });
      setIsSlideOverOpen(false);
      setNewPolicy({ title: "", description: "" });
      fetchPolicies();
    } catch { /* ignore */ }
  };

  const handleSign = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedPolicy) return;
    try {
      await authFetch(`${API}/dash/compliance/sign`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ policyId: selectedPolicy.id, employeeId: signData.employeeId }),
      });
      setIsSignModalOpen(false);
      fetchPolicies();
    } catch { /* ignore */ }
  };

  const checkEntries = checks
    ? ([
        checks.minimumWage,
        checks.socialSecurity,
        checks.contracts,
        checks.payroll,
        checks.gratuity,
      ] as ComplianceCheck[])
    : [];

  const months = ["","January","February","March","April","May","June","July","August","September","October","November","December"];

  return (
    <div className="space-y-6 relative">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 sm:text-3xl">Compliance & Labor Law</h1>
          <p className="mt-1 text-sm text-gray-500">
            Punjab Government labor law compliance — live checks, policies & acknowledgments.
          </p>
        </div>
      </div>

      {/* Live Compliance Summary Cards */}
      {checks && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
          <div className="rounded-2xl bg-white border border-gray-100 shadow-sm p-5">
            <p className="text-xs font-bold text-gray-400 uppercase tracking-widest">Total Employees</p>
            <p className="text-2xl font-extrabold text-gray-900 mt-1">{checks.summary.totalEmployees}</p>
            <p className="text-xs text-gray-400 mt-1">Enrolled workforce</p>
          </div>
          <div className="rounded-2xl bg-white border border-gray-100 shadow-sm p-5">
            <p className="text-xs font-bold text-gray-400 uppercase tracking-widest">Checks Run</p>
            <p className="text-2xl font-extrabold text-brand-600 mt-1">{checks.summary.checksRun}</p>
            <p className="text-xs text-gray-400 mt-1">{months[checks.summary.checkedMonth]} {checks.summary.checkedYear}</p>
          </div>
          <div className={cn("rounded-2xl border shadow-sm p-5", checks.summary.violations > 0 ? "bg-red-50 border-red-100" : "bg-green-50 border-green-100")}>
            <p className="text-xs font-bold uppercase tracking-widest text-gray-400">Violations</p>
            <p className={cn("text-2xl font-extrabold mt-1", checks.summary.violations > 0 ? "text-red-600" : "text-green-600")}>
              {checks.summary.violations}
            </p>
            <p className="text-xs text-gray-500 mt-1">Legal breaches</p>
          </div>
          <div className={cn("rounded-2xl border shadow-sm p-5", checks.summary.warnings > 0 ? "bg-amber-50 border-amber-100" : "bg-green-50 border-green-100")}>
            <p className="text-xs font-bold uppercase tracking-widest text-gray-400">Warnings</p>
            <p className={cn("text-2xl font-extrabold mt-1", checks.summary.warnings > 0 ? "text-amber-600" : "text-green-600")}>
              {checks.summary.warnings}
            </p>
            <p className="text-xs text-gray-500 mt-1">Needs attention</p>
          </div>
        </div>
      )}

      {/* Min Wage Banner */}
      {checks && (
        <div className="rounded-xl bg-brand-50 border border-brand-100 px-5 py-3 flex items-center gap-3">
          <Scale className="h-5 w-5 text-brand-600 flex-shrink-0" />
          <p className="text-sm text-brand-800">
            <span className="font-bold">Punjab Minimum Wage 2025-26:</span> Rs. {checks.summary.minimumWage?.toLocaleString() ?? "40,000"}/month — enforced under Punjab Minimum Wages Act, 2019.
          </p>
        </div>
      )}

      {/* Tabs */}
      <div className="flex gap-1 rounded-xl bg-gray-100 p-1 w-fit">
        {(["checks", "policies", "gratuity"] as const).map((tab) => (
          <button
            key={tab}
            onClick={() => { setActiveTab(tab); if (tab === "gratuity") fetchGratuities(); }}
            className={cn(
              "px-5 py-2 rounded-lg text-sm font-semibold transition-all",
              activeTab === tab ? "bg-white text-gray-900 shadow-sm" : "text-gray-500 hover:text-gray-700"
            )}
          >
            {tab === "checks" ? "Live Compliance Checks" : tab === "policies" ? `Policies (${policies.length})` : "Gratuity"}
          </button>
        ))}
      </div>

      {/* ── Tab: Live Checks ── */}
      {activeTab === "checks" && (
        <div className="rounded-2xl bg-white border border-gray-100 shadow-sm overflow-hidden">
          <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between">
            <div>
              <h2 className="text-base font-bold text-gray-900">Automated Compliance Audit</h2>
              <p className="text-xs text-gray-400 mt-0.5">Based on live employee, payroll, and contract data</p>
            </div>
            <div className="flex items-center gap-2">
              <button 
                onClick={() => fetchChecks(true)} 
                disabled={isChecksLoading}
                className="inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-bold text-white bg-brand-600 hover:bg-brand-700 disabled:opacity-50 transition-colors"
                title="Regenerate all attendance and payroll for compliance"
              >
                {isChecksLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
                Recalculate Compliance
              </button>
              <button onClick={() => fetchChecks(false)} className="p-1.5 text-gray-400 hover:text-brand-600 transition-colors" title="Quick Refresh">
                <RefreshCw className={cn("h-4 w-4", isChecksLoading && "animate-spin")} />
              </button>
            </div>
          </div>

          {isChecksLoading ? (
            <div className="p-12 text-center text-sm text-gray-400">Running compliance checks...</div>
          ) : (
            <div className="divide-y divide-gray-100">
              {checkEntries.map((check) => (
                <div key={check.label}>
                  <button
                    onClick={() => setExpandedCheck(expandedCheck === check.label ? null : check.label)}
                    className="w-full flex items-center justify-between px-6 py-4 hover:bg-gray-50 transition-colors text-left"
                  >
                    <div className="flex items-center gap-4">
                      {check.status === "COMPLIANT" ? (
                        <CheckCircle2 className="h-5 w-5 text-green-500 flex-shrink-0" />
                      ) : check.status === "VIOLATION" ? (
                        <XCircle className="h-5 w-5 text-red-500 flex-shrink-0" />
                      ) : (
                        <AlertTriangle className="h-5 w-5 text-amber-500 flex-shrink-0" />
                      )}
                      <div>
                        <p className="text-sm font-semibold text-gray-900">{check.label}</p>
                        <p className="text-xs text-gray-400">{check.law}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3">
                      <span className={cn(
                        "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-bold ring-1 ring-inset",
                        check.status === "COMPLIANT"
                          ? "bg-green-50 text-green-700 ring-green-600/20"
                          : check.status === "VIOLATION"
                          ? "bg-red-50 text-red-700 ring-red-600/20"
                          : "bg-amber-50 text-amber-700 ring-amber-600/20"
                      )}>
                        {check.status === "COMPLIANT" ? "✓ Compliant" : check.status === "VIOLATION" ? `${check.violations.length} Violation${check.violations.length > 1 ? "s" : ""}` : `${check.violations.length} Warning${check.violations.length > 1 ? "s" : ""}`}
                      </span>
                      {check.violations.length > 0 && (
                        expandedCheck === check.label ? <ChevronUp className="h-4 w-4 text-gray-400" /> : <ChevronDown className="h-4 w-4 text-gray-400" />
                      )}
                    </div>
                  </button>

                  {expandedCheck === check.label && check.violations.length > 0 && (
                    <motion.div
                      initial={{ height: 0, opacity: 0 }}
                      animate={{ height: "auto", opacity: 1 }}
                      exit={{ height: 0, opacity: 0 }}
                      className="bg-gray-50 border-t border-gray-100 px-6 py-3"
                    >
                      <table className="min-w-full text-sm">
                        <thead>
                          <tr>
                            <th className="text-left text-xs font-bold text-gray-400 uppercase py-2 pr-4">Employee</th>
                            <th className="text-left text-xs font-bold text-gray-400 uppercase py-2 pr-4">ID</th>
                            <th className="text-left text-xs font-bold text-gray-400 uppercase py-2">Issue</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100">
                          {check.violations.map((v) => (
                            <tr key={v.employeeId}>
                              <td className="py-2 pr-4 font-medium text-gray-900">{v.name}</td>
                              <td className="py-2 pr-4 text-gray-400 font-mono text-xs">#{v.employeeId}</td>
                              <td className="py-2 text-red-600 text-xs font-medium">
                                {v.issue}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </motion.div>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* ── Tab: Policies ── */}
      {activeTab === "policies" && (
        <>
          {isLoading ? (
            <div className="p-12 text-center text-sm text-gray-400">Loading policies...</div>
          ) : policies.length === 0 ? (
            <div className="rounded-2xl border-2 border-dashed border-gray-200 py-16 text-center">
              <BookOpen className="h-10 w-10 text-gray-300 mx-auto mb-4" />
              <h3 className="text-base font-semibold text-gray-600">No policies yet</h3>
              <p className="text-sm text-gray-400 mt-1 mb-6">Click <b>Load Punjab Labor Laws</b> to import 14 real policies.</p>
              <button onClick={handleSeedPunjab} disabled={isSeeding} className="inline-flex items-center rounded-lg bg-brand-600 px-5 py-2 text-sm font-medium text-white hover:bg-brand-700 disabled:opacity-60">
                {isSeeding ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <BookOpen className="mr-2 h-4 w-4" />}
                Load Punjab Labor Laws
              </button>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
              {policies.map((policy, idx) => {
                const cat = categoryForTitle(policy.title);
                const isExpanded = expandedPolicy === policy.id;
                const pct = employees.length > 0 ? Math.round((policy._count.signatures / employees.length) * 100) : 0;
                return (
                  <motion.div
                    key={policy.id}
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: idx * 0.03 }}
                    className="relative flex flex-col rounded-2xl bg-white shadow-sm border border-gray-100 hover:shadow-md transition-shadow"
                  >
                    <div className="p-5">
                      <div className="flex items-start justify-between gap-2 mb-3">
                        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-50 text-brand-600 flex-shrink-0">
                          <ShieldCheck className="h-5 w-5" />
                        </div>
                        <span className={cn("inline-flex items-center rounded-full px-2 py-0.5 text-xs font-semibold ring-1 ring-inset", cat.color)}>
                          {cat.label}
                        </span>
                      </div>

                      <h3 className="text-sm font-bold text-gray-900 leading-snug">{policy.title}</h3>

                      <div className="mt-3">
                        <p className={cn("text-xs text-gray-500 leading-relaxed", !isExpanded && "line-clamp-2")}>
                          {policy.description}
                        </p>
                        {policy.description && policy.description.length > 120 && (
                          <button
                            onClick={() => setExpandedPolicy(isExpanded ? null : policy.id)}
                            className="text-xs text-brand-600 font-semibold mt-1 hover:underline"
                          >
                            {isExpanded ? "Show less" : "Read full policy"}
                          </button>
                        )}
                      </div>

                      <div className="mt-4">
                        <div className="flex justify-between text-xs text-gray-400 mb-1">
                          <span>Acknowledgments</span>
                          <span className="font-bold text-gray-600">{policy._count.signatures} / {employees.length} workers ({pct}%)</span>
                        </div>
                        <div className="w-full bg-gray-100 rounded-full h-1.5">
                          <div
                            className={cn("h-1.5 rounded-full transition-all", pct === 100 ? "bg-green-500" : pct >= 50 ? "bg-amber-400" : "bg-red-400")}
                            style={{ width: `${pct}%` }}
                          />
                        </div>
                      </div>
                    </div>

                    <div className="px-5 pb-5 flex gap-2">
                      <button
                        onClick={() => { setSelectedPolicy(policy); setIsSignModalOpen(true); }}
                        className="flex-1 inline-flex items-center justify-center rounded-lg bg-white px-3 py-2 text-xs font-bold text-gray-700 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50"
                      >
                        <FileSignature className="mr-1.5 h-3.5 w-3.5" />
                        Log Signature
                      </button>
                      <button
                        onClick={async () => await downloadCompliancePolicyPDF(policy)}
                        className="inline-flex items-center justify-center rounded-lg bg-brand-50 p-2 text-brand-600 hover:bg-brand-100"
                        title="Download PDF"
                      >
                        <Download className="h-4 w-4" />
                      </button>
                    </div>
                  </motion.div>
                );
              })}
            </div>
          )}
        </>
      )}

      {/* ── Tab: Gratuity ── */}
      {activeTab === "gratuity" && (
        <div className="space-y-6">
          <div className="rounded-2xl bg-white border border-gray-100 shadow-sm overflow-hidden">
            <div className="px-6 py-4 border-b border-gray-100 bg-amber-50/40">
              <div className="flex items-center gap-2">
                <Coins className="h-5 w-5 text-amber-600" />
                <h2 className="text-base font-bold text-gray-900">Gratuity Management</h2>
              </div>
              <p className="text-xs text-gray-500 mt-0.5">Eligible employees (15+ years) and payment history</p>
            </div>

            <div className="p-6 space-y-8">
                {/* Eligible — unpaid */}
                {checks?.gratuity?.violations && checks.gratuity.violations.length > 0 && (
                  <div className="px-6 pt-5 pb-3">
                    <p className="text-xs font-bold text-gray-500 uppercase tracking-widest mb-3">Eligible — Not Yet Paid ({checks.gratuity.violations.length})</p>
                    <div className="space-y-3">
                      {checks.gratuity.violations.map(v => {
                        const joining = v.joiningDate ? new Date(v.joiningDate) : null;
                        const years = joining ? Math.floor((Date.now() - joining.getTime()) / (365.25*24*3600*1000)) : 0;
                        const amount = (v.basicSalary ?? 0) * years;
                        return (
                          <div key={v.employeeId} className="rounded-xl border border-amber-100 bg-amber-50/60 p-4">
                            <div className="flex items-start justify-between gap-2">
                              <div>
                                <p className="text-sm font-bold text-gray-900">{v.name}</p>
                                <p className="text-xs text-gray-500 font-mono">#{v.employeeId}</p>
                                <p className="text-xs text-amber-700 mt-1">{v.issue}</p>
                                <p className="text-xs text-gray-500 mt-0.5">Estimated: <span className="font-bold text-gray-800">PKR {amount.toLocaleString("en-PK", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span></p>
                              </div>
                              <button
                                onClick={() => handleMarkGratuityPaid(v)}
                                disabled={markingPaid === v.employeeId}
                                className="inline-flex items-center gap-1 rounded-lg px-3 py-1.5 text-xs font-bold text-white bg-amber-500 hover:bg-amber-600 disabled:opacity-50 transition-colors flex-shrink-0"
                              >
                                {markingPaid === v.employeeId ? <Loader2 className="h-3 w-3 animate-spin" /> : <CheckCircle2 className="h-3 w-3" />}
                                Mark Paid
                              </button>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                )}

                {checks?.gratuity?.violations?.length === 0 && (
                  <div className="px-6 pt-5 pb-3">
                    <div className="rounded-xl border border-green-100 bg-green-50 p-4 flex items-center gap-3">
                      <CheckCircle2 className="h-5 w-5 text-green-500 flex-shrink-0" />
                      <p className="text-sm text-green-700 font-medium">All eligible employees have been paid.</p>
                    </div>
                  </div>
                )}

                {/* Payment History */}
                <div className="px-6 pt-4 pb-6">
                  <p className="text-xs font-bold text-gray-500 uppercase tracking-widest mb-3">Payment History ({gratuityRecords.length})</p>
                  {gratuityLoading ? (
                    <div className="flex items-center justify-center h-20"><Loader2 className="h-5 w-5 animate-spin text-gray-300" /></div>
                  ) : gratuityRecords.length === 0 ? (
                    <p className="text-sm text-gray-400 text-center py-6">No gratuity payments recorded yet.</p>
                  ) : (
                    <div className="space-y-3">
                      {gratuityRecords.map(g => (
                        <div key={g.id} className="rounded-xl border border-gray-100 bg-white p-4 shadow-sm">
                          <div className="flex items-start justify-between gap-2">
                            <div className="flex-1 min-w-0">
                              <p className="text-sm font-bold text-gray-900">{g.employee.firstName} {g.employee.lastName}</p>
                              <p className="text-xs text-gray-400 font-mono">#{g.employee.employeeId} · {g.employee.designation ?? ""}</p>
                              <div className="flex items-center gap-3 mt-1.5 flex-wrap">
                                <span className="text-xs text-gray-500">{g.yearsOfService} yrs service</span>
                                <span className="text-xs font-bold text-green-700 bg-green-50 px-2 py-0.5 rounded-full">PKR {g.amount.toLocaleString("en-PK", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
                                {g.settlementDate && <span className="text-xs text-gray-400">{new Date(g.settlementDate).toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" })}</span>}
                              </div>
                            </div>
                            <div className="flex gap-1 flex-shrink-0">
                              <button
                                onClick={async () => {
                                  const companyName = await getCompanyName();
                                  downloadGratuityPDF({ employee: g.employee, yearsOfService: g.yearsOfService, amount: g.amount, settlementDate: g.settlementDate ?? new Date().toISOString().slice(0,10), companyName });
                                }}
                                className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-white bg-brand-600 hover:bg-brand-700 transition-colors"
                                title="Download English Certificate"
                              >
                                <Download className="h-3 w-3" /> EN
                              </button>
                              <button
                                onClick={async () => {
                                  const companyName = await getCompanyName();
                                  downloadGratuityPDFUrdu({ employee: g.employee, yearsOfService: g.yearsOfService, amount: g.amount, settlementDate: g.settlementDate ?? new Date().toISOString().slice(0,10), companyName });
                                }}
                                className="inline-flex items-center gap-1 rounded-lg px-2.5 py-1.5 text-xs font-semibold text-brand-700 bg-brand-50 hover:bg-brand-100 border border-brand-100 transition-colors"
                                title="Download Urdu Certificate"
                              >
                                <Download className="h-3 w-3" /> UR
                              </button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
            </div>
          </div>
        </div>
      )}

      {/* Modal: Create Policy */}
      <AnimatePresence>
        {isSlideOverOpen && (
          <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => { setIsSlideOverOpen(false); setNewPolicy({ title: "", description: "" }); }} className="fixed inset-0 bg-gray-900/50 backdrop-blur-sm" />
            <motion.div initial={{ scale: 0.95, opacity: 0, y: 10 }} animate={{ scale: 1, opacity: 1, y: 0 }} exit={{ scale: 0.95, opacity: 0, y: 10 }} transition={{ type: "spring", bounce: 0.15, duration: 0.3 }} className="relative w-full max-w-xl bg-white rounded-2xl shadow-2xl flex flex-col max-h-[90vh]">

              {/* Header */}
              <div className="flex items-center justify-between px-6 py-5 bg-gradient-to-r from-brand-600 to-brand-700 rounded-t-2xl flex-shrink-0">
                <div className="flex items-center gap-3">
                  <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-white/20">
                    <ShieldCheck className="h-5 w-5 text-white" />
                  </div>
                  <div>
                    <h2 className="text-base font-bold text-white">New Compliance Policy</h2>
                    <p className="text-xs text-brand-200">Publish a policy for employee acknowledgment</p>
                  </div>
                </div>
                <button onClick={() => { setIsSlideOverOpen(false); setNewPolicy({ title: "", description: "" }); }} className="rounded-lg p-2 hover:bg-white/20 transition-colors">
                  <XCircle className="h-5 w-5 text-white/70" />
                </button>
              </div>

              {/* Form */}
              <div className="flex-1 overflow-y-auto">
                <form id="policy-form" onSubmit={handleCreatePolicy}>
                  <div className="p-6 space-y-5">

                    {/* Category quick-select */}
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-gray-400 mb-2">Category</label>
                      <div className="grid grid-cols-3 gap-2">
                        {LAW_CATEGORIES.map((cat) => (
                          <button
                            key={cat.label}
                            type="button"
                            onClick={() => setNewPolicy({ ...newPolicy, title: newPolicy.title || cat.label })}
                            className={cn("flex items-center gap-1.5 rounded-xl px-3 py-2 text-xs font-semibold ring-1 ring-inset transition-all text-left", cat.color)}
                          >
                            <Scale className="h-3 w-3 flex-shrink-0" />
                            {cat.label}
                          </button>
                        ))}
                      </div>
                    </div>

                    <div className="border-t border-gray-100 pt-5 space-y-4">
                      {/* Title */}
                      <div>
                        <label className="block text-xs font-bold uppercase tracking-wider text-gray-400 mb-1.5">Policy Title <span className="text-red-500">*</span></label>
                        <input
                          required
                          type="text"
                          placeholder="e.g. Anti-Harassment Policy 2025"
                          value={newPolicy.title}
                          onChange={e => setNewPolicy({ ...newPolicy, title: e.target.value })}
                          className="block w-full rounded-xl border-0 py-3 px-4 text-gray-900 text-sm ring-1 ring-inset ring-gray-200 focus:ring-2 focus:ring-brand-500 placeholder:text-gray-300 bg-gray-50 focus:bg-white transition-colors"
                        />
                      </div>

                      {/* Description */}
                      <div>
                        <div className="flex items-center justify-between mb-1.5">
                          <label className="block text-xs font-bold uppercase tracking-wider text-gray-400">Description</label>
                          <span className="text-xs text-gray-300">{newPolicy.description.length} chars</span>
                        </div>
                        <textarea
                          rows={6}
                          placeholder="Full policy text, applicable law references, employee obligations…"
                          value={newPolicy.description}
                          onChange={e => setNewPolicy({ ...newPolicy, description: e.target.value })}
                          className="block w-full rounded-xl border-0 py-3 px-4 text-gray-900 text-sm ring-1 ring-inset ring-gray-200 focus:ring-2 focus:ring-brand-500 placeholder:text-gray-300 bg-gray-50 focus:bg-white transition-colors resize-none leading-relaxed"
                        />
                        <p className="mt-1 text-xs text-gray-400">Include law name, section, and effective date.</p>
                      </div>
                    </div>

                    {/* Live preview */}
                    {newPolicy.title && (
                      <motion.div initial={{ opacity: 0, y: 4 }} animate={{ opacity: 1, y: 0 }} className="rounded-xl bg-brand-50 border border-brand-100 p-4 flex items-start gap-3">
                        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-100 text-brand-600 flex-shrink-0">
                          <ShieldCheck className="h-4 w-4" />
                        </div>
                        <div>
                          <p className="text-xs font-bold text-brand-800">{newPolicy.title}</p>
                          <p className="text-xs text-brand-400 mt-0.5 line-clamp-1">{newPolicy.description || "No description yet"}</p>
                        </div>
                      </motion.div>
                    )}
                  </div>
                </form>
              </div>

              {/* Footer */}
              <div className="px-6 py-4 border-t border-gray-100 bg-gray-50 rounded-b-2xl flex items-center justify-end gap-3 flex-shrink-0">
                <button type="button" onClick={() => { setIsSlideOverOpen(false); setNewPolicy({ title: "", description: "" }); }} className="px-4 py-2.5 text-sm font-semibold text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded-xl transition-colors">
                  Cancel
                </button>
                <button type="submit" form="policy-form" className="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-6 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-brand-700 transition-colors">
                  <ShieldCheck className="h-4 w-4" />
                  Publish Policy
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* Signature Modal */}
      <AnimatePresence>
        {isSignModalOpen && (
          <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => setIsSignModalOpen(false)} className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm" />
            <motion.div initial={{ scale: 0.95, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.95, opacity: 0 }} className="relative w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl">
              <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-green-50 text-green-600 mb-4">
                <UserPlus className="h-6 w-6" />
              </div>
              <h2 className="text-xl font-bold text-gray-900">Log Acknowledgment</h2>
              <p className="mt-1 text-sm text-gray-500">Record employee signature for <b>{selectedPolicy?.title}</b>.</p>
              <form onSubmit={handleSign} className="mt-5 space-y-4">
                <div>
                  <label className="block text-xs font-bold uppercase text-gray-500 mb-1.5">Select Employee</label>
                  <select required value={signData.employeeId} onChange={e => setSignData({ employeeId: e.target.value })} className="block w-full rounded-lg border-gray-200 py-2.5 text-sm focus:border-brand-600 focus:ring-brand-600">
                    <option value="">Select...</option>
                    {employees.map(emp => (
                      <option key={emp.id} value={emp.id}>{emp.firstName} {emp.lastName}</option>
                    ))}
                  </select>
                </div>
                <div className="flex gap-3 pt-1">
                  <button type="button" onClick={() => setIsSignModalOpen(false)} className="flex-1 py-2 text-sm font-bold text-gray-500 hover:text-gray-700">Cancel</button>
                  <button type="submit" className="flex-1 rounded-lg bg-brand-600 py-2 text-sm font-bold text-white hover:bg-brand-700">Confirm</button>
                </div>
              </form>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
}




