"use client";
import { useState, useEffect, useCallback } from "react";
import {
  X,
  Phone,
  MessageSquare,
  Mail,
  Radio,
  Building2,
  Shield,
  Calendar,
  Loader2,
  Lock,
  Eye,
  EyeOff,
  Pencil,
  Save,
  AlertTriangle,
  HeartPulse,
  BadgeCheck,
  Clock,
  ChevronRight,
  UserCog,
  History,
  Camera,
} from "lucide-react";
import { format } from "date-fns";
import { cn, getInitials, AVATAR_COLORS, formatTime } from "@/lib/utils";
import Badge from "./ui/Badge";

interface Props {
  employeeId: number | null;
  actorId: number | null;
  onClose: () => void;
  onSaved?: () => void;
}

interface ProfileData {
  employee: Record<string, string | number | boolean | null>;
  unit: { id: number; name: string; type: string; color: string | null } | null;
  chain: Array<{ id: number; name: string; type: string; color: string | null }>;
  supervisors: Array<{
    id: number;
    firstName: string;
    lastName: string;
    rank: string | null;
    avatarColor: string | null;
    photoUrl: string | null;
  }>;
  upcomingShifts: Array<{ id: number; date: string; startTime: string; endTime: string; shiftType: string | null }>;
  leave: Array<{ id: number; startDate: string; endDate: string; type: string | null; status: string }>;
  confidential: Record<string, string | number | boolean | null> | null;
  accessLog: Array<{ id: number; action: string; actorRole: string | null; createdAt: string }>;
  viewer: { actorId: number | null; role: string; canSeeConfidential: boolean; canEdit: boolean };
}

const SHIFT_COLOR: Record<string, string> = {
  day: "#3B82F6",
  evening: "#F59E0B",
  night: "#8B5CF6",
  custom: "#10B981",
};

const ROLE_COLOR: Record<string, string> = {
  admin: "#EF4444",
  supervisor: "#F59E0B",
  officer: "#3B82F6",
};

/** Strips formatting so tel:/sms: links dial correctly. */
const dial = (n: string) => n.replace(/[^\d+]/g, "");

function ContactRow({
  icon: Icon,
  label,
  value,
  primary,
}: {
  icon: React.ElementType;
  label: string;
  value: string;
  primary?: boolean;
}) {
  const num = dial(value);
  return (
    <div
      className={cn(
        "flex items-center gap-3 rounded-xl border p-2.5",
        primary ? "border-blue-200 bg-blue-50/60" : "border-slate-200 bg-white"
      )}
    >
      <div
        className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0"
        style={{ backgroundColor: primary ? "#3B82F620" : "#F1F5F9", color: primary ? "#2563EB" : "#64748B" }}
      >
        <Icon size={15} />
      </div>
      <div className="min-w-0 flex-1">
        <p className="text-[10px] uppercase tracking-wide text-slate-400">{label}</p>
        <p className="text-sm font-medium text-slate-800 truncate">{value}</p>
      </div>
      <div className="flex gap-1.5">
        <a
          href={`tel:${num}`}
          className="p-2 rounded-lg bg-green-50 text-green-600 hover:bg-green-100 transition-colors"
          title={`Call ${value}`}
        >
          <Phone size={14} />
        </a>
        <a
          href={`sms:${num}`}
          className="p-2 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 transition-colors"
          title={`Text ${value}`}
        >
          <MessageSquare size={14} />
        </a>
      </div>
    </div>
  );
}

function Field({
  label,
  value,
  onChange,
  type = "text",
  editing,
  placeholder,
  textarea,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  type?: string;
  editing: boolean;
  placeholder?: string;
  textarea?: boolean;
}) {
  return (
    <div>
      <label className="block text-[11px] font-medium text-slate-500 mb-1">{label}</label>
      {editing ? (
        textarea ? (
          <textarea
            rows={2}
            value={value}
            placeholder={placeholder}
            onChange={(e) => onChange(e.target.value)}
            className="w-full border border-slate-300 rounded-lg px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        ) : (
          <input
            type={type}
            value={value}
            placeholder={placeholder}
            onChange={(e) => onChange(e.target.value)}
            className="w-full border border-slate-300 rounded-lg px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        )
      ) : (
        <p className="text-sm text-slate-800 min-h-[1.5rem] break-words">
          {value || <span className="text-slate-300">—</span>}
        </p>
      )}
    </div>
  );
}

export default function EmployeeProfileModal({ employeeId, actorId, onClose, onSaved }: Props) {
  const [data, setData] = useState<ProfileData | null>(null);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState<"contact" | "assignment" | "confidential">("contact");
  const [editing, setEditing] = useState(false);
  const [revealed, setRevealed] = useState(false);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [profileForm, setProfileForm] = useState<Record<string, string | boolean>>({});
  const [confForm, setConfForm] = useState<Record<string, string | boolean>>({});

  const load = useCallback(async () => {
    if (!employeeId) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/employees/profile?id=${employeeId}&actorId=${actorId ?? ""}`);
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Failed to load");
      setData(json);
      const e = json.employee;
      setProfileForm({
        firstName: e.firstName ?? "",
        lastName: e.lastName ?? "",
        rank: e.rank ?? "",
        role: e.role ?? "officer",
        badgeNumber: e.badgeNumber ?? "",
        jobTitle: e.jobTitle ?? "",
        email: e.email ?? "",
        phone: e.phone ?? "",
        mobilePhone: e.mobilePhone ?? "",
        workPhone: e.workPhone ?? "",
        extension: e.extension ?? "",
        radioCallSign: e.radioCallSign ?? "",
        preferredContact: e.preferredContact ?? "mobile",
        photoUrl: e.photoUrl ?? "",
        bio: e.bio ?? "",
        hireDate: e.hireDate ?? "",
        avatarColor: e.avatarColor ?? "#3B82F6",
        isActive: e.isActive ?? true,
      });
      const c = json.confidential ?? {};
      setConfForm({
        dateOfBirth: c.dateOfBirth ?? "",
        ssnLast4: c.ssnLast4 ?? "",
        driversLicense: c.driversLicense ?? "",
        personalEmail: c.personalEmail ?? "",
        homePhone: c.homePhone ?? "",
        homeAddress: c.homeAddress ?? "",
        emergencyContactName: c.emergencyContactName ?? "",
        emergencyContactPhone: c.emergencyContactPhone ?? "",
        emergencyContactRelation: c.emergencyContactRelation ?? "",
        bloodType: c.bloodType ?? "",
        medicalNotes: c.medicalNotes ?? "",
        allergies: c.allergies ?? "",
        payGrade: c.payGrade ?? "",
        salary: c.salary ?? "",
        unionMember: c.unionMember ?? false,
        clearanceLevel: c.clearanceLevel ?? "",
        disciplinaryNotes: c.disciplinaryNotes ?? "",
        internalAffairsFlag: c.internalAffairsFlag ?? false,
        adminNotes: c.adminNotes ?? "",
      });
    } catch (e) {
      setError(String(e));
    } finally {
      setLoading(false);
    }
  }, [employeeId, actorId]);

  useEffect(() => {
    if (employeeId) {
      setTab("contact");
      setEditing(false);
      setRevealed(false);
      load();
    }
  }, [employeeId, load]);

  useEffect(() => {
    document.body.style.overflow = employeeId ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [employeeId]);

  const save = async () => {
    if (!employeeId) return;
    setSaving(true);
    setError(null);
    try {
      const res = await fetch("/api/employees/profile", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: employeeId,
          actorId,
          profile: profileForm,
          confidential: data?.viewer.canSeeConfidential ? confForm : undefined,
        }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error ?? "Save failed");
      setEditing(false);
      await load();
      onSaved?.();
    } catch (e) {
      setError(String(e));
    } finally {
      setSaving(false);
    }
  };

  if (!employeeId) return null;

  const emp = data?.employee;
  const isAdmin = data?.viewer.canSeeConfidential ?? false;
  const name = emp ? `${emp.firstName} ${emp.lastName}` : "";
  const color = (emp?.avatarColor as string) ?? "#3B82F6";
  const photo = (editing ? (profileForm.photoUrl as string) : (emp?.photoUrl as string)) || "";

  const contacts: Array<{ icon: React.ElementType; label: string; value: string; primary?: boolean }> = [];
  if (emp?.mobilePhone)
    contacts.push({
      icon: Phone,
      label: "Mobile",
      value: String(emp.mobilePhone),
      primary: emp.preferredContact === "mobile",
    });
  if (emp?.phone && emp.phone !== emp.mobilePhone)
    contacts.push({ icon: Phone, label: "Primary", value: String(emp.phone) });
  if (emp?.workPhone)
    contacts.push({
      icon: Building2,
      label: `Desk${emp.extension ? ` · ext ${emp.extension}` : ""}`,
      value: String(emp.workPhone),
      primary: emp.preferredContact === "work",
    });

  return (
    <div className="fixed inset-0 z-[60] flex items-start sm:items-center justify-center p-0 sm:p-4 overflow-y-auto">
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />

      <div className="relative bg-white w-full sm:max-w-3xl sm:rounded-2xl shadow-2xl my-0 sm:my-8 min-h-screen sm:min-h-0">
        {/* Header */}
        <div className="relative rounded-t-none sm:rounded-t-2xl overflow-hidden">
          <div className="h-24" style={{ background: `linear-gradient(135deg, ${color}, ${color}99)` }} />
          <button
            onClick={onClose}
            className="absolute top-3 right-3 p-2 rounded-xl bg-black/20 text-white hover:bg-black/40 transition-colors"
          >
            <X size={18} />
          </button>

          <div className="px-5 pb-4 -mt-12 flex flex-wrap items-end gap-4">
            <div className="relative">
              {photo ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={photo}
                  alt={name}
                  className="w-24 h-24 rounded-2xl object-cover border-4 border-white shadow-lg bg-slate-100"
                  onError={(ev) => {
                    (ev.target as HTMLImageElement).style.display = "none";
                  }}
                />
              ) : (
                <div
                  className="w-24 h-24 rounded-2xl border-4 border-white shadow-lg flex items-center justify-center text-2xl font-bold text-white"
                  style={{ backgroundColor: color }}
                >
                  {emp ? getInitials(String(emp.firstName), String(emp.lastName)) : "…"}
                </div>
              )}
              {editing && (
                <div className="absolute -bottom-1 -right-1 bg-blue-600 text-white rounded-lg p-1.5 shadow">
                  <Camera size={13} />
                </div>
              )}
            </div>

            <div className="flex-1 min-w-[180px] pb-1">
              <div className="flex items-center gap-2 flex-wrap">
                <h2 className="text-xl font-bold text-slate-900">{name || "Loading…"}</h2>
                {emp?.isActive === false && <Badge color="#94A3B8">Inactive</Badge>}
              </div>
              <p className="text-sm text-slate-500">
                {(emp?.rank as string) || (emp?.jobTitle as string) || ""}
                {emp?.badgeNumber ? ` · Badge #${emp.badgeNumber}` : ""}
              </p>
              <div className="flex items-center gap-2 mt-1.5 flex-wrap">
                {emp?.role && <Badge color={ROLE_COLOR[String(emp.role)] ?? "#3B82F6"}>{String(emp.role)}</Badge>}
                {data?.unit && <Badge color={data.unit.color ?? "#3B82F6"}>{data.unit.name}</Badge>}
                {emp?.radioCallSign && (
                  <span className="inline-flex items-center gap-1 text-xs text-slate-500">
                    <Radio size={11} /> {String(emp.radioCallSign)}
                  </span>
                )}
              </div>
            </div>

            {data?.viewer.canEdit && (
              <div className="flex gap-2 pb-1">
                {editing ? (
                  <>
                    <button
                      onClick={save}
                      disabled={saving}
                      className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-blue-600 text-white text-sm font-medium hover:bg-blue-700 disabled:opacity-50"
                    >
                      {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
                      Save
                    </button>
                    <button
                      onClick={() => {
                        setEditing(false);
                        load();
                      }}
                      className="px-3 py-2 rounded-xl border border-slate-200 text-sm text-slate-600 hover:bg-slate-50"
                    >
                      Cancel
                    </button>
                  </>
                ) : (
                  <button
                    onClick={() => setEditing(true)}
                    className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-slate-900 text-white text-sm font-medium hover:bg-slate-800"
                  >
                    <Pencil size={14} /> Edit
                  </button>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Quick actions */}
        {!editing && emp && (
          <div className="px-5 pb-3 flex flex-wrap gap-2">
            {emp.mobilePhone && (
              <>
                <a
                  href={`tel:${dial(String(emp.mobilePhone))}`}
                  className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-green-600 text-white text-sm font-medium hover:bg-green-700"
                >
                  <Phone size={14} /> Call
                </a>
                <a
                  href={`sms:${dial(String(emp.mobilePhone))}`}
                  className="flex items-center gap-1.5 px-3 py-2 rounded-xl bg-blue-600 text-white text-sm font-medium hover:bg-blue-700"
                >
                  <MessageSquare size={14} /> Text
                </a>
              </>
            )}
            {emp.email && (
              <a
                href={`mailto:${emp.email}`}
                className="flex items-center gap-1.5 px-3 py-2 rounded-xl border border-slate-200 text-slate-700 text-sm font-medium hover:bg-slate-50"
              >
                <Mail size={14} /> Email
              </a>
            )}
          </div>
        )}

        {/* Tabs */}
        <div className="px-5 border-b border-slate-200 flex gap-1 overflow-x-auto">
          {(
            [
              ["contact", "Contact", Phone],
              ["assignment", "Assignment", Shield],
              ...(isAdmin ? ([["confidential", "Confidential", Lock]] as const) : []),
            ] as Array<[string, string, React.ElementType]>
          ).map(([key, label, Icon]) => (
            <button
              key={key}
              onClick={() => setTab(key as typeof tab)}
              className={cn(
                "flex items-center gap-1.5 px-3 py-2.5 text-sm font-medium border-b-2 -mb-px whitespace-nowrap transition-colors",
                tab === key
                  ? key === "confidential"
                    ? "border-red-500 text-red-600"
                    : "border-blue-600 text-blue-600"
                  : "border-transparent text-slate-500 hover:text-slate-700"
              )}
            >
              <Icon size={14} />
              {label}
              {key === "confidential" && <Lock size={10} className="text-red-400" />}
            </button>
          ))}
        </div>

        <div className="p-5">
          {loading && (
            <div className="flex justify-center py-10">
              <Loader2 className="animate-spin text-blue-500" size={26} />
            </div>
          )}

          {error && (
            <div className="mb-4 flex items-start gap-2 rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700">
              <AlertTriangle size={15} className="mt-0.5" />
              {error}
            </div>
          )}

          {/* ------------------------------------------------ CONTACT */}
          {!loading && tab === "contact" && emp && (
            <div className="space-y-4">
              {!editing && contacts.length > 0 && (
                <div className="space-y-2">
                  {contacts.map((c, i) => (
                    <ContactRow key={i} {...c} />
                  ))}
                </div>
              )}

              {!editing && emp.email && (
                <a
                  href={`mailto:${emp.email}`}
                  className="flex items-center gap-3 rounded-xl border border-slate-200 p-2.5 hover:bg-slate-50 transition-colors"
                >
                  <div className="w-8 h-8 rounded-lg bg-slate-100 text-slate-500 flex items-center justify-center">
                    <Mail size={15} />
                  </div>
                  <div className="min-w-0">
                    <p className="text-[10px] uppercase tracking-wide text-slate-400">Work email</p>
                    <p className="text-sm font-medium text-blue-600 truncate">{String(emp.email)}</p>
                  </div>
                </a>
              )}

              {!editing && contacts.length === 0 && !emp.email && (
                <p className="text-sm text-slate-400 text-center py-6">No contact details on file.</p>
              )}

              {!editing && emp.bio && (
                <div className="rounded-xl bg-slate-50 p-3">
                  <p className="text-[10px] uppercase tracking-wide text-slate-400 mb-1">About</p>
                  <p className="text-sm text-slate-700">{String(emp.bio)}</p>
                </div>
              )}

              {editing && (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <Field label="First name" editing value={String(profileForm.firstName)} onChange={(v) => setProfileForm({ ...profileForm, firstName: v })} />
                  <Field label="Last name" editing value={String(profileForm.lastName)} onChange={(v) => setProfileForm({ ...profileForm, lastName: v })} />
                  <div className="sm:col-span-2">
                    <Field label="Photo URL" editing value={String(profileForm.photoUrl)} placeholder="https://…/headshot.jpg" onChange={(v) => setProfileForm({ ...profileForm, photoUrl: v })} />
                  </div>
                  <Field label="Mobile phone" editing value={String(profileForm.mobilePhone)} placeholder="555-0142" onChange={(v) => setProfileForm({ ...profileForm, mobilePhone: v })} />
                  <Field label="Work phone" editing value={String(profileForm.workPhone)} onChange={(v) => setProfileForm({ ...profileForm, workPhone: v })} />
                  <Field label="Extension" editing value={String(profileForm.extension)} onChange={(v) => setProfileForm({ ...profileForm, extension: v })} />
                  <Field label="Work email" type="email" editing value={String(profileForm.email)} onChange={(v) => setProfileForm({ ...profileForm, email: v })} />
                  <Field label="Radio call sign" editing value={String(profileForm.radioCallSign)} placeholder="Adam-12" onChange={(v) => setProfileForm({ ...profileForm, radioCallSign: v })} />
                  <div>
                    <label className="block text-[11px] font-medium text-slate-500 mb-1">Preferred contact</label>
                    <select
                      value={String(profileForm.preferredContact)}
                      onChange={(e) => setProfileForm({ ...profileForm, preferredContact: e.target.value })}
                      className="w-full border border-slate-300 rounded-lg px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="mobile">Mobile</option>
                      <option value="work">Work</option>
                      <option value="email">Email</option>
                    </select>
                  </div>
                  <div className="sm:col-span-2">
                    <Field label="About" textarea editing value={String(profileForm.bio)} onChange={(v) => setProfileForm({ ...profileForm, bio: v })} />
                  </div>
                  <div className="sm:col-span-2">
                    <label className="block text-[11px] font-medium text-slate-500 mb-1">Avatar colour</label>
                    <div className="flex flex-wrap gap-1.5">
                      {AVATAR_COLORS.map((c) => (
                        <button
                          key={c}
                          onClick={() => setProfileForm({ ...profileForm, avatarColor: c })}
                          className={cn(
                            "w-7 h-7 rounded-full transition-transform",
                            profileForm.avatarColor === c && "ring-2 ring-offset-2 ring-blue-500 scale-110"
                          )}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* ------------------------------------------------ ASSIGNMENT */}
          {!loading && tab === "assignment" && (
            <div className="space-y-4">
              {editing ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <Field label="Rank" editing value={String(profileForm.rank)} onChange={(v) => setProfileForm({ ...profileForm, rank: v })} />
                  <div>
                    <label className="block text-[11px] font-medium text-slate-500 mb-1">System role</label>
                    <select
                      value={String(profileForm.role)}
                      onChange={(e) => setProfileForm({ ...profileForm, role: e.target.value })}
                      className="w-full border border-slate-300 rounded-lg px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="officer">Officer</option>
                      <option value="supervisor">Supervisor</option>
                      <option value="admin">Administrator</option>
                    </select>
                  </div>
                  <Field label="Badge number" editing value={String(profileForm.badgeNumber)} onChange={(v) => setProfileForm({ ...profileForm, badgeNumber: v })} />
                  <Field label="Job title" editing value={String(profileForm.jobTitle)} onChange={(v) => setProfileForm({ ...profileForm, jobTitle: v })} />
                  <Field label="Hire date" type="date" editing value={String(profileForm.hireDate)} onChange={(v) => setProfileForm({ ...profileForm, hireDate: v })} />
                  <label className="flex items-center gap-2 mt-5">
                    <input
                      type="checkbox"
                      checked={!!profileForm.isActive}
                      onChange={(e) => setProfileForm({ ...profileForm, isActive: e.target.checked })}
                      className="w-4 h-4 rounded border-slate-300 text-blue-600"
                    />
                    <span className="text-sm text-slate-700">Active employee</span>
                  </label>
                </div>
              ) : (
                <>
                  {data?.chain && data.chain.length > 0 && (
                    <div>
                      <p className="text-[10px] uppercase tracking-wide text-slate-400 mb-1.5">Chain of command</p>
                      <div className="flex items-center gap-1 flex-wrap text-sm">
                        {[...data.chain].reverse().map((c) => (
                          <span key={c.id} className="flex items-center gap-1">
                            <span className="px-2 py-1 rounded-lg bg-slate-100 text-slate-700 text-xs font-medium">{c.name}</span>
                            <ChevronRight size={12} className="text-slate-300" />
                          </span>
                        ))}
                        {data.unit && (
                          <span
                            className="px-2 py-1 rounded-lg text-xs font-semibold text-white"
                            style={{ backgroundColor: data.unit.color ?? "#3B82F6" }}
                          >
                            {data.unit.name}
                          </span>
                        )}
                      </div>
                    </div>
                  )}

                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    {[
                      { label: "Rank", value: (emp?.rank as string) || "—" },
                      { label: "Badge", value: emp?.badgeNumber ? `#${emp.badgeNumber}` : "—" },
                      { label: "Hired", value: (emp?.hireDate as string) || "—" },
                      { label: "Employee #", value: (emp?.employeeNumber as string) || "—" },
                    ].map((f) => (
                      <div key={f.label} className="rounded-xl bg-slate-50 p-2.5">
                        <p className="text-[10px] uppercase tracking-wide text-slate-400">{f.label}</p>
                        <p className="text-sm font-semibold text-slate-800 truncate">{f.value}</p>
                      </div>
                    ))}
                  </div>

                  {data?.supervisors && data.supervisors.length > 0 && (
                    <div>
                      <p className="text-[10px] uppercase tracking-wide text-slate-400 mb-1.5">Reports to</p>
                      <div className="flex flex-wrap gap-2">
                        {data.supervisors.map((s) => (
                          <div key={s.id} className="flex items-center gap-2 rounded-lg border border-slate-200 px-2 py-1.5">
                            <div
                              className="w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold text-white"
                              style={{ backgroundColor: s.avatarColor ?? "#3B82F6" }}
                            >
                              {getInitials(s.firstName, s.lastName)}
                            </div>
                            <div className="leading-tight">
                              <p className="text-xs font-medium text-slate-700">
                                {s.firstName} {s.lastName}
                              </p>
                              <p className="text-[10px] text-slate-400">{s.rank}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {data?.upcomingShifts && data.upcomingShifts.length > 0 && (
                    <div>
                      <p className="text-[10px] uppercase tracking-wide text-slate-400 mb-1.5">Next shifts</p>
                      <div className="flex flex-wrap gap-1.5">
                        {data.upcomingShifts.map((s) => (
                          <div
                            key={s.id}
                            className="rounded-lg px-2 py-1 text-[11px] font-medium text-white"
                            style={{ backgroundColor: SHIFT_COLOR[s.shiftType ?? "day"] ?? "#3B82F6" }}
                          >
                            {format(new Date(s.date + "T00:00:00"), "EEE MMM d")} · {formatTime(s.startTime)}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}

                  {data?.leave && data.leave.length > 0 && (
                    <div>
                      <p className="text-[10px] uppercase tracking-wide text-slate-400 mb-1.5">Upcoming leave</p>
                      {data.leave.map((l) => (
                        <div key={l.id} className="flex items-center gap-2 text-xs text-slate-600 mb-1">
                          <Calendar size={12} className="text-slate-400" />
                          {l.startDate} – {l.endDate}
                          <Badge color={l.status === "approved" ? "#10B981" : l.status === "denied" ? "#EF4444" : "#F59E0B"}>
                            {l.status}
                          </Badge>
                          <span className="text-slate-400">{l.type}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </>
              )}
            </div>
          )}

          {/* ------------------------------------------------ CONFIDENTIAL */}
          {!loading && tab === "confidential" && isAdmin && (
            <div className="space-y-4">
              <div className="flex flex-wrap items-center gap-2 rounded-xl border border-red-200 bg-red-50 p-3">
                <Lock size={15} className="text-red-500" />
                <p className="text-xs text-red-800 flex-1 min-w-[180px]">
                  <strong>Restricted personnel record.</strong> Visible to administrators only. Every view and edit is
                  written to the access log.
                </p>
                <button
                  onClick={() => setRevealed((r) => !r)}
                  className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-white border border-red-200 text-xs font-medium text-red-700 hover:bg-red-100"
                >
                  {revealed ? <EyeOff size={13} /> : <Eye size={13} />}
                  {revealed ? "Hide" : "Reveal"}
                </button>
              </div>

              {!revealed && !editing ? (
                <div className="text-center py-10 rounded-xl border-2 border-dashed border-slate-200">
                  <Lock size={30} className="mx-auto mb-2 text-slate-300" />
                  <p className="text-sm text-slate-400">Sensitive fields are hidden. Choose “Reveal” to display them.</p>
                </div>
              ) : (
                <>
                  <section>
                    <h4 className="text-xs font-bold uppercase tracking-wide text-slate-500 mb-2 flex items-center gap-1.5">
                      <UserCog size={13} /> Personal
                    </h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <Field label="Date of birth" type="date" editing={editing} value={String(confForm.dateOfBirth)} onChange={(v) => setConfForm({ ...confForm, dateOfBirth: v })} />
                      <Field label="SSN (last 4)" editing={editing} value={String(confForm.ssnLast4)} placeholder="1234" onChange={(v) => setConfForm({ ...confForm, ssnLast4: v })} />
                      <Field label="Driver's licence" editing={editing} value={String(confForm.driversLicense)} onChange={(v) => setConfForm({ ...confForm, driversLicense: v })} />
                      <Field label="Personal email" editing={editing} value={String(confForm.personalEmail)} onChange={(v) => setConfForm({ ...confForm, personalEmail: v })} />
                      <Field label="Home phone" editing={editing} value={String(confForm.homePhone)} onChange={(v) => setConfForm({ ...confForm, homePhone: v })} />
                      <div className="sm:col-span-2">
                        <Field label="Home address" textarea editing={editing} value={String(confForm.homeAddress)} onChange={(v) => setConfForm({ ...confForm, homeAddress: v })} />
                      </div>
                    </div>
                    {!editing && confForm.homePhone && (
                      <div className="mt-2">
                        <ContactRow icon={Phone} label="Home phone" value={String(confForm.homePhone)} />
                      </div>
                    )}
                  </section>

                  <section>
                    <h4 className="text-xs font-bold uppercase tracking-wide text-slate-500 mb-2 flex items-center gap-1.5">
                      <HeartPulse size={13} /> Emergency & medical
                    </h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <Field label="Emergency contact" editing={editing} value={String(confForm.emergencyContactName)} onChange={(v) => setConfForm({ ...confForm, emergencyContactName: v })} />
                      <Field label="Relationship" editing={editing} value={String(confForm.emergencyContactRelation)} onChange={(v) => setConfForm({ ...confForm, emergencyContactRelation: v })} />
                      <Field label="Emergency phone" editing={editing} value={String(confForm.emergencyContactPhone)} onChange={(v) => setConfForm({ ...confForm, emergencyContactPhone: v })} />
                      <Field label="Blood type" editing={editing} value={String(confForm.bloodType)} onChange={(v) => setConfForm({ ...confForm, bloodType: v })} />
                      <Field label="Allergies" editing={editing} value={String(confForm.allergies)} onChange={(v) => setConfForm({ ...confForm, allergies: v })} />
                      <Field label="Medical notes" editing={editing} value={String(confForm.medicalNotes)} onChange={(v) => setConfForm({ ...confForm, medicalNotes: v })} />
                    </div>
                    {!editing && confForm.emergencyContactPhone && (
                      <div className="mt-2">
                        <ContactRow
                          icon={HeartPulse}
                          label={`Emergency · ${confForm.emergencyContactName || "contact"}`}
                          value={String(confForm.emergencyContactPhone)}
                          primary
                        />
                      </div>
                    )}
                  </section>

                  <section>
                    <h4 className="text-xs font-bold uppercase tracking-wide text-slate-500 mb-2 flex items-center gap-1.5">
                      <BadgeCheck size={13} /> Employment & compliance
                    </h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <Field label="Pay grade" editing={editing} value={String(confForm.payGrade)} onChange={(v) => setConfForm({ ...confForm, payGrade: v })} />
                      <Field label="Salary" editing={editing} value={String(confForm.salary)} onChange={(v) => setConfForm({ ...confForm, salary: v })} />
                      <Field label="Clearance level" editing={editing} value={String(confForm.clearanceLevel)} onChange={(v) => setConfForm({ ...confForm, clearanceLevel: v })} />
                      <div className="flex items-center gap-4 mt-5">
                        <label className="flex items-center gap-2">
                          <input
                            type="checkbox"
                            disabled={!editing}
                            checked={!!confForm.unionMember}
                            onChange={(e) => setConfForm({ ...confForm, unionMember: e.target.checked })}
                            className="w-4 h-4 rounded border-slate-300 text-blue-600"
                          />
                          <span className="text-sm text-slate-700">Union member</span>
                        </label>
                        <label className="flex items-center gap-2">
                          <input
                            type="checkbox"
                            disabled={!editing}
                            checked={!!confForm.internalAffairsFlag}
                            onChange={(e) => setConfForm({ ...confForm, internalAffairsFlag: e.target.checked })}
                            className="w-4 h-4 rounded border-slate-300 text-red-600"
                          />
                          <span className="text-sm text-slate-700">IA flag</span>
                        </label>
                      </div>
                      <div className="sm:col-span-2">
                        <Field label="Disciplinary notes" textarea editing={editing} value={String(confForm.disciplinaryNotes)} onChange={(v) => setConfForm({ ...confForm, disciplinaryNotes: v })} />
                      </div>
                      <div className="sm:col-span-2">
                        <Field label="Administrator notes" textarea editing={editing} value={String(confForm.adminNotes)} onChange={(v) => setConfForm({ ...confForm, adminNotes: v })} />
                      </div>
                    </div>
                  </section>

                  {data?.accessLog && data.accessLog.length > 0 && (
                    <section>
                      <h4 className="text-xs font-bold uppercase tracking-wide text-slate-500 mb-2 flex items-center gap-1.5">
                        <History size={13} /> Access log
                      </h4>
                      <div className="rounded-xl border border-slate-200 divide-y divide-slate-100 max-h-36 overflow-y-auto">
                        {data.accessLog.map((l) => (
                          <div key={l.id} className="flex items-center gap-2 px-3 py-1.5 text-xs">
                            <Clock size={11} className="text-slate-400" />
                            <span className="text-slate-500">{format(new Date(l.createdAt), "MMM d HH:mm")}</span>
                            <Badge color={l.action === "update" ? "#F59E0B" : "#64748B"}>{l.action}</Badge>
                            <span className="text-slate-400">{l.actorRole}</span>
                          </div>
                        ))}
                      </div>
                    </section>
                  )}
                </>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
