"use client";

import { useMemo, useRef, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  DatePicker,
  EmptyState,
  Input,
  Modal,
  MonthPicker,
  PageHeader,
  PageLoader,
  Pagination,
  Select,
  StatCard,
  StatusBadge,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { formatBDT, formatDate } from "@/lib/utils";
import {
  ATTENDANCE_STATUSES,
  STAFF_SIDE_ROLES,
  PAYMENT_METHODS,
  STAFF_DEPARTMENTS,
  STAFF_DESIGNATIONS,
} from "@/lib/constants";
import {
  IconBriefcase,
  IconCamera,
  IconCheck,
  IconDollar,
  IconEdit,
  IconFile,
  IconActivity,
  IconPlus,
  IconTrash,
  IconUserCheck,
  IconUsers,
} from "@/components/icons";
import { CredentialsPanel, type PersonOption } from "@/components/CredentialsPanel";
import { emsConfirm } from "@/components/ConfirmDialog";

interface StaffRow {
  id: number;
  employeeCode: string;
  name: string;
  nameBn: string | null;
  gender: string;
  phone: string;
  email: string | null;
  designation: string;
  department: string | null;
  joinDate: string | null;
  monthlySalary: number;
  photoUrl: string | null;
  signatureUrl: string | null;
  status: string;
  todayStatus: string | null;
}

interface HrData {
  staff: StaffRow[];
  summary: {
    totalStaff: number;
    activeStaff: number;
    presentToday: number;
    onLeaveToday: number;
    pendingLeaves: number;
    month: string;
    payroll: number;
    paidThisMonth: number;
    dueThisMonth: number;
  };
}

interface AttendanceData {
  date: string;
  entries: {
    staffId: number;
    employeeCode: string;
    name: string;
    designation: string;
    status: string | null;
  }[];
  counts: { marked: number; present: number; absent: number; leave: number };
}

interface LeaveRow {
  id: number;
  staffName: string;
  employeeCode: string;
  designation: string;
  fromDate: string;
  toDate: string;
  days: number;
  reason: string;
  status: string;
}

interface SalaryData {
  month: string;
  rows: {
    staffId: number;
    employeeCode: string;
    name: string;
    designation: string;
    salary: number;
    paidAmount: number;
    paid: boolean;
    method: string | null;
    details: Record<string, string> | null;
    paidAt: string | null;
  }[];
  summary: { payroll: number; paid: number; due: number; paidCount: number };
  history: {
    id: number;
    staffName: string;
    employeeCode: string;
    month: string;
    amount: number;
    method: string;
    details: Record<string, string> | null;
    paidAt: string;
  }[];
}

interface AuditRow {
  id: number;
  name: string;
  role: string | null;
  identifier: string;
  success: boolean;
  reason: string | null;
  ip: string | null;
  createdAt: string;
}

type Tab = "staff" | "attendance" | "leave" | "salary" | "audit" | "credentials";

const emptyForm = {
  employeeCode: "",
  name: "",
  nameBn: "",
  gender: "MALE",
  phone: "",
  email: "",
  designation: "TEACHER",
  department: "ACADEMIC",
  joinDate: "",
  monthlySalary: "0",
};

/** Staff photo (data URL) with initials fallback; clickable to change. */
function StaffAvatar({
  name,
  photoUrl,
  size = 36,
  onClick,
  title,
}: {
  name: string;
  photoUrl?: string | null;
  size?: number;
  onClick?: () => void;
  title?: string;
}) {
  return (
    <span
      className={`ems-avatar${onClick ? " ems-avatar-click" : ""}`}
      style={{ width: size, height: size, fontSize: Math.max(10, Math.round(size * 0.36)) }}
      onClick={onClick}
      role={onClick ? "button" : undefined}
      title={title}
    >
      {photoUrl ? <img src={photoUrl} alt={name} loading="lazy" /> : name.slice(0, 2).toUpperCase()}
    </span>
  );
}

/** Read an image file and downscale it (max 256px, JPEG) into a small data URL. */
function photoFromFile(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = () => reject(new Error("read"));
    reader.onload = () => {
      const url = String(reader.result);
      const img = new Image();
      img.onload = () => {
        const max = 256;
        const scale = Math.min(1, max / Math.max(img.width, img.height));
        const w = Math.max(1, Math.round(img.width * scale));
        const h = Math.max(1, Math.round(img.height * scale));
        const canvas = document.createElement("canvas");
        canvas.width = w;
        canvas.height = h;
        const ctx = canvas.getContext("2d");
        if (!ctx) return resolve(url);
        // Flatten transparency (PNG) onto white before JPEG encoding
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, w, h);
        ctx.drawImage(img, 0, 0, w, h);
        const resized = canvas.toDataURL("image/jpeg", 0.85);
        resolve(resized.length < url.length ? resized : url);
      };
      img.onerror = () => reject(new Error("decode"));
      img.src = url;
    };
    reader.readAsDataURL(file);
  });
}

/** compact "TrxID / bank / ref" summary for a payment details JSON */
function detailsSummary(details: Record<string, string> | null | undefined): string[] {
  if (!details) return [];
  const parts = [
    details.txnId && `TrxID: ${details.txnId}`,
    details.bankName,
    details.branch,
    details.refNo && `Ref: ${details.refNo}`,
    details.cardType,
    details.last4 && `•••• ${details.last4}`,
    details.account,
  ].filter(Boolean) as string[];
  return parts;
}

export default function PortalHrPage() {
  const { t, locale } = useLang();
  const [tab, setTab] = useState<Tab>("staff");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const { data, loading, reload } = useApi<HrData>("/api/portal/hr");

  // Staff form
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState<StaffRow | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);
  const [search, setSearch] = useState("");

  // Staff profile photo modal
  const [photoStaff, setPhotoStaff] = useState<Pick<StaffRow, "id" | "name" | "photoUrl"> | null>(null);
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [photoSaving, setPhotoSaving] = useState(false);
  const photoInputRef = useRef<HTMLInputElement>(null);

  // Staff signature modal
  const [signStaff, setSignStaff] = useState<Pick<StaffRow, "id" | "name" | "signatureUrl"> | null>(null);
  const [signPreview, setSignPreview] = useState<string | null>(null);
  const [signSaving, setSignSaving] = useState(false);
  const signInputRef = useRef<HTMLInputElement>(null);

  // Login audit (HR → Login Audit tab)
  const audit = useApi<{ logs: AuditRow[] }>("/api/portal/hr/audit");

  // Attendance
  const today = new Date().toISOString().slice(0, 10);
  const [attDate, setAttDate] = useState(today);
  const { data: att, loading: attLoading, reload: attReload } = useApi<AttendanceData>(
    `/api/portal/hr/attendance?date=${attDate}`
  );
  const [attDraft, setAttDraft] = useState<Record<number, string>>({});
  const [attSaving, setAttSaving] = useState(false);

  // Leave
  const { data: leaves, loading: leavesLoading, reload: leavesReload } = useApi<{ leaves: LeaveRow[] }>(
    "/api/portal/hr/leaves"
  );
  const [leaveOpen, setLeaveOpen] = useState(false);
  const [leaveForm, setLeaveForm] = useState({ staffId: "", fromDate: today, toDate: today, reason: "" });
  const [leaveSaving, setLeaveSaving] = useState(false);

  // Salary
  const currentMonth = today.slice(0, 7);
  const [month, setMonth] = useState(currentMonth);
  const { data: salary, loading: salaryLoading, reload: salaryReload } = useApi<SalaryData>(
    `/api/portal/hr/salaries?month=${month}`
  );
  const [payStaff, setPayStaff] = useState<SalaryData["rows"][number] | null>(null);
  const [payMethod, setPayMethod] = useState("CASH");
  const [payDetails, setPayDetails] = useState<Record<string, string>>({});
  const [payNote, setPayNote] = useState("");
  const [paySaving, setPaySaving] = useState(false);
  // mobile-banking / bank / card salary payments carry reference details
  // (same fields as student fee collections); cash needs none
  const MOBILE_METHODS = ["BKASH", "NAGAD", "ROCKET"];
  function payRequiredFields(): string[] {
    if (MOBILE_METHODS.includes(payMethod)) return ["txnId"];
    if (payMethod === "BANK_TRANSFER") return ["bankName", "refNo"];
    if (payMethod === "CARD") return ["refNo"];
    return [];
  }
  const payMissing = payRequiredFields().filter((k) => !(payDetails[k] ?? "").trim());
  function setPayDetail(key: string, value: string) {
    setPayDetails((d) => ({ ...d, [key]: value }));
  }

  const staff = useMemo(() => {
    if (!data) return [];
    const q = search.trim().toLowerCase();
    if (!q) return data.staff;
    return data.staff.filter(
      (s) =>
        s.name.toLowerCase().includes(q) ||
        s.employeeCode.toLowerCase().includes(q) ||
        s.designation.toLowerCase().includes(q)
    );
  }, [data, search]);

  const staffPager = usePagination(staff, 10);
  const leaveRows = leaves?.leaves ?? [];
  const leavesPager = usePagination(leaveRows, 10);
  const salaryRows = salary?.rows ?? [];
  const salaryRowsPager = usePagination(salaryRows, 10);
  const salaryHistoryRows = salary?.history ?? [];
  const salaryHistoryPager = usePagination(salaryHistoryRows, 10);
  const auditRows = audit.data?.logs ?? [];
  const auditPager = usePagination(auditRows, 10);

  function notify(type: "success" | "error", text: string) {
    setMessage({ type, text });
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function openCreate() {
    setEditing(null);
    setForm(emptyForm);
    setFormOpen(true);
  }

  function openEdit(s: StaffRow) {
    setEditing(s);
    setForm({
      employeeCode: s.employeeCode,
      name: s.name,
      nameBn: s.nameBn ?? "",
      gender: s.gender,
      phone: s.phone,
      email: s.email ?? "",
      designation: STAFF_DESIGNATIONS.includes(s.designation as never) ? s.designation : "OTHER",
      department: s.department && STAFF_DEPARTMENTS.includes(s.department as never) ? s.department : "OTHER",
      joinDate: s.joinDate ? s.joinDate.slice(0, 10) : "",
      monthlySalary: String(s.monthlySalary),
    });
    setFormOpen(true);
  }

  async function saveStaff() {
    setSaving(true);
    try {
      if (editing) {
        await api(`/api/portal/hr/${editing.id}`, {
          method: "PUT",
          body: JSON.stringify({ ...form, status: editing.status }),
        });
        notify("success", t.portal.hrPage.staffUpdated);
      } else {
        await api("/api/portal/hr", { method: "POST", body: JSON.stringify(form) });
        notify("success", t.portal.hrPage.staffCreated);
      }
      setFormOpen(false);
      reload();
    } catch (e) {
      const err = e instanceof Error ? e.message : "";
      notify("error", err === "CODE_EXISTS" ? t.portal.hrPage.codeExists : t.common.tryAgain);
    } finally {
      setSaving(false);
    }
  }

  async function removeStaff(s: StaffRow) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/portal/hr/${s.id}`, { method: "DELETE" });
      notify("success", t.common.deletedSuccessfully);
      reload();
    } catch (e) {
      const err = e instanceof Error ? e.message : "";
      notify("error", err === "IN_USE" ? t.portal.hrPage.staffInUse : t.common.tryAgain);
    }
  }

  async function saveAttendance() {
    if (!att) return;
    const entries = Object.entries(attDraft).map(([staffId, status]) => ({ staffId: Number(staffId), status }));
    if (entries.length === 0) return;
    setAttSaving(true);
    try {
      await api("/api/portal/hr/attendance", {
        method: "POST",
        body: JSON.stringify({ date: att.date, entries }),
      });
      setAttDraft({});
      attReload();
      reload();
      notify("success", t.portal.hrPage.attendanceSaved);
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setAttSaving(false);
    }
  }

  async function saveLeave() {
    setLeaveSaving(true);
    try {
      await api("/api/portal/hr/leaves", { method: "POST", body: JSON.stringify(leaveForm) });
      setLeaveOpen(false);
      setLeaveForm({ staffId: "", fromDate: today, toDate: today, reason: "" });
      leavesReload();
      reload();
      notify("success", t.portal.hrPage.leaveRequested);
    } catch (e) {
      const err = e instanceof Error ? e.message : "";
      notify("error", err === "INVALID_RANGE" ? t.portal.hrPage.invalidRange : t.common.tryAgain);
    } finally {
      setLeaveSaving(false);
    }
  }

  async function decideLeave(l: LeaveRow, approve: boolean) {
    const q = approve ? t.portal.hrPage.approveLeaveConfirm : t.portal.hrPage.rejectLeaveConfirm;
    if (!(await emsConfirm({ message: q, danger: false }))) return;
    try {
      await api(`/api/portal/hr/leaves/${l.id}`, {
        method: "PUT",
        body: JSON.stringify({ approve }),
      });
      leavesReload();
      reload();
      notify("success", t.portal.hrPage.leaveDecided);
    } catch {
      notify("error", t.common.tryAgain);
    }
  }

  async function paySalary() {
    if (!payStaff) return;
    if (!(await emsConfirm({ message: t.portal.hrPage.payConfirm, danger: false }))) return;
    setPaySaving(true);
    try {
      await api("/api/portal/hr/salaries", {
        method: "POST",
        body: JSON.stringify({
          staffId: payStaff.staffId,
          month: salary?.month ?? currentMonth,
          amount: payStaff.salary,
          method: payMethod,
          details: payDetails,
          note: payNote,
        }),
      });
      setPayStaff(null);
      setPayMethod("CASH");
      setPayDetails({});
      setPayNote("");
      salaryReload();
      reload();
      notify("success", t.portal.hrPage.salaryPaid);
    } catch (e) {
      const err = e instanceof Error ? e.message : "";
      notify("error", err === "ALREADY_PAID" ? t.portal.hrPage.alreadyPaid : t.common.tryAgain);
    } finally {
      setPaySaving(false);
    }
  }

  function openPhoto(s: Pick<StaffRow, "id" | "name" | "photoUrl">) {
    setPhotoStaff(s);
    setPhotoPreview(null);
  }

  async function handlePhotoFile(file: File | undefined) {
    if (!file) return;
    try {
      setPhotoPreview(await photoFromFile(file));
    } catch {
      notify("error", t.portal.studentsPage.photoInvalid);
    }
  }

  async function savePhoto() {
    if (!photoStaff || !photoPreview) return;
    setPhotoSaving(true);
    try {
      await api(`/api/portal/hr/${photoStaff.id}/photo`, {
        method: "POST",
        body: JSON.stringify({ photoUrl: photoPreview }),
      });
      notify("success", t.portal.studentsPage.photoSaved);
      setPhotoStaff(null);
      setPhotoPreview(null);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setPhotoSaving(false);
    }
  }

  async function removePhoto() {
    if (!photoStaff) return;
    setPhotoSaving(true);
    try {
      await api(`/api/portal/hr/${photoStaff.id}/photo`, { method: "DELETE" });
      notify("success", t.portal.studentsPage.photoRemoved);
      setPhotoStaff(null);
      setPhotoPreview(null);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setPhotoSaving(false);
    }
  }

  function openSignature(s: Pick<StaffRow, "id" | "name" | "signatureUrl">) {
    setSignStaff(s);
    setSignPreview(null);
  }

  async function handleSignatureFile(file: File | undefined) {
    if (!file) return;
    try {
      setSignPreview(await photoFromFile(file));
    } catch {
      notify("error", t.portal.studentsPage.photoInvalid);
    }
  }

  async function saveSignature() {
    if (!signStaff || !signPreview) return;
    setSignSaving(true);
    try {
      await api(`/api/portal/hr/${signStaff.id}/signature`, {
        method: "POST",
        body: JSON.stringify({ signatureUrl: signPreview }),
      });
      notify("success", t.portal.hrPage.signatureSaved);
      setSignStaff(null);
      setSignPreview(null);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setSignSaving(false);
    }
  }

  async function removeSignature() {
    if (!signStaff) return;
    setSignSaving(true);
    try {
      await api(`/api/portal/hr/${signStaff.id}/signature`, { method: "DELETE" });
      notify("success", t.portal.hrPage.signatureRemoved);
      setSignStaff(null);
      setSignPreview(null);
      reload();
    } catch {
      notify("error", t.common.tryAgain);
    } finally {
      setSignSaving(false);
    }
  }

  if (loading) return <PageLoader text={t.common.loading} />;
  const s = data?.summary;

  // Staff options for the member-credential manager (teacher & staff logins)
  const credentialPersons: PersonOption[] = (data?.staff ?? []).map((st) => ({
    id: st.id,
    label: st.name,
    sub: `${st.employeeCode} · ${t.designations[st.designation as keyof typeof t.designations] ?? st.designation}`,
    defaultUsername: st.employeeCode,
    defaultName: st.name,
  }));

  return (
    <div>
      <PageHeader title={t.portal.hrPage.title} subtitle={t.portal.hrPage.subtitle} />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      {/* Summary stats */}
      <div className="row g-3 mb-4">
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.hrPage.totalStaff} value={String(s?.totalStaff ?? 0)} icon={<IconUsers />} accent="teal" hint={`${s?.activeStaff ?? 0} ${t.common.active.toLowerCase()}`} />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.hrPage.presentToday} value={String(s?.presentToday ?? 0)} icon={<IconUserCheck />} accent="blue" />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.hrPage.onLeaveToday} value={String(s?.onLeaveToday ?? 0)} icon={<IconBriefcase />} accent="orange" hint={`${s?.pendingLeaves ?? 0} ${t.status.PENDING}`} />
        </div>
        <div className="col-xl-3 col-sm-6">
          <StatCard label={t.portal.hrPage.monthlyPayroll} value={formatBDT(s?.payroll ?? 0, locale)} icon={<IconDollar />} accent="purple" hint={`${t.portal.hrPage.paidLabel}: ${formatBDT(s?.paidThisMonth ?? 0, locale)}`} />
        </div>
      </div>

      {/* Tabs */}
      <ul className="nav nav-tabs mb-4" role="tablist">
        {(["staff", "attendance", "leave", "salary", "audit", "credentials"] as Tab[]).map((key) => {
          const labels: Record<Tab, string> = {
            staff: t.portal.hrPage.tabStaff,
            attendance: t.portal.hrPage.tabAttendance,
            leave: t.portal.hrPage.tabLeave,
            salary: t.portal.hrPage.tabSalary,
            audit: t.portal.hrPage.tabAudit,
            credentials: t.portal.credentials.tabTitle,
          };
          return (
            <li className="nav-item" key={key}>
              <button
                className={`nav-link ${tab === key ? "active" : ""}`}
                onClick={() => setTab(key)}
                type="button"
              >
                {labels[key]}
              </button>
            </li>
          );
        })}
      </ul>

      {/* ---------- Staff tab ---------- */}
      {tab === "staff" && (
        !data || data.staff.length === 0 ? (
          <div className="card">
            <EmptyState
              icon={<IconUsers />}
              title={t.portal.hrPage.noStaff}
              action={
                <Button onClick={openCreate}>
                  <IconPlus className="svg-16" />
                  <span className="ms-1">{t.portal.hrPage.newStaff}</span>
                </Button>
              }
            />
          </div>
        ) : (
          <div className="card">
            <div className="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
              <div className="has-search" style={{ maxWidth: 320 }}>
                <span className="fa fa-search form-control-feedback" />
                <input
                  className="form-control"
                  placeholder={t.common.search}
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                />
              </div>
              <Button onClick={openCreate}>
                <IconPlus className="svg-16" />
                <span className="ms-1">{t.portal.hrPage.newStaff}</span>
              </Button>
            </div>
            <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th style={{ width: 60 }}>{t.portal.studentsPage.photoCol}</th>
                    <th>{t.portal.hrPage.employeeCode}</th>
                    <th>{t.common.name}</th>
                    <th>{t.common.designation}</th>
                    <th>{t.common.phone}</th>
                    <th>{t.portal.hrPage.monthlySalary}</th>
                    <th>{t.common.status}</th>
                    <th className="text-end">{t.common.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {staffPager.paged.map((r) => (
                    <tr key={r.id} className={r.status === "INACTIVE" ? "opacity-50" : ""}>
                      <td>
                        <StaffAvatar
                          name={r.name}
                          photoUrl={r.photoUrl}
                          size={40}
                          onClick={() => openPhoto(r)}
                          title={t.portal.studentsPage.photoTitle}
                        />
                      </td>
                      <td>
                        <span className="ems-roll-badge">{r.employeeCode}</span>
                      </td>
                      <td>
                        <p className="mb-0 f-w-700">{r.name}</p>
                        {r.nameBn && <p className="mb-0 ems-fs-11 text-muted">{r.nameBn}</p>}
                        {r.department && (
                          <p className="mb-0 ems-fs-11 text-muted">
                            {t.departments[r.department as keyof typeof t.departments] ?? r.department}
                          </p>
                        )}
                      </td>
                      <td>
                        <span className="ems-type-pill">
                          {t.designations[r.designation as keyof typeof t.designations] ?? r.designation}
                        </span>
                      </td>
                      <td className="ems-fs-13">{r.phone}</td>
                      <td className="f-w-700">{formatBDT(r.monthlySalary, locale)}</td>
                      <td>
                        <StatusBadge status={r.status} label={r.status === "ACTIVE" ? t.common.active : t.common.inactive} />
                      </td>
                      <td className="text-end">
                        <button
                          className="btn btn-soft-secondary btn-sm me-1"
                          onClick={() => openSignature(r)}
                          type="button"
                          title={t.portal.hrPage.signatureTitle}
                        >
                          <IconFile className="svg-16" />
                        </button>
                        <button className="btn btn-soft-secondary btn-sm me-1" onClick={() => openEdit(r)} type="button">
                          <IconEdit className="svg-16" />
                        </button>
                        <button className="btn btn-soft-danger btn-sm" onClick={() => removeStaff(r)} type="button">
                          <IconTrash className="svg-16" />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pagination {...staffPager} onPageChange={staffPager.setPage} onSizeChange={staffPager.setSize} />
          </div>
        )
      )}

      {/* ---------- Attendance tab ---------- */}
      {tab === "attendance" && (
        <div className="card">
          <div className="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
            <div className="d-flex align-items-center gap-2">
              <DatePicker
                wrapperClassName="form-group mb-0"
                style={{ maxWidth: 180 }}
                value={attDate}
                onChange={(e) => {
                  setAttDate(e.target.value);
                  setAttDraft({});
                }}
              />
              {att && (
                <span className="badge badge-secondary">
                  {t.portal.hrPage.attendanceFor} {formatDate(att.date, locale)}
                </span>
              )}
            </div>
            <Button onClick={saveAttendance} loading={attSaving} disabled={Object.keys(attDraft).length === 0}>
              <IconCheck className="svg-16" />
              <span className="ms-1">{t.portal.hrPage.markAttendance}</span>
            </Button>
          </div>
          {attLoading || !att ? (
            <div className="card-body text-center py-4">
              <span className="spinner-border text-primary" role="status" />
            </div>
          ) : att.entries.length === 0 ? (
            <EmptyState icon={<IconUsers />} title={t.portal.hrPage.noStaff} />
          ) : (
            <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.portal.hrPage.employeeCode}</th>
                    <th>{t.common.name}</th>
                    <th>{t.common.designation}</th>
                    <th className="text-end">{t.common.status}</th>
                  </tr>
                </thead>
                <tbody>
                  {att.entries.map((e) => {
                    const current = attDraft[e.staffId] ?? e.status;
                    return (
                      <tr key={e.staffId}>
                        <td>
                          <span className="ems-roll-badge">{e.employeeCode}</span>
                        </td>
                        <td className="f-w-600">{e.name}</td>
                        <td className="ems-fs-13">
                          {t.designations[e.designation as keyof typeof t.designations] ?? e.designation}
                        </td>
                        <td className="text-end">
                          <div className="btn-group btn-group-sm" role="group">
                            {ATTENDANCE_STATUSES.map((st) => (
                              <button
                                key={st}
                                type="button"
                                className={`btn ${
                                  current === st
                                    ? st === "PRESENT"
                                      ? "btn-success"
                                      : st === "ABSENT"
                                        ? "btn-danger"
                                        : "btn-warning"
                                    : "btn-outline-secondary"
                                }`}
                                onClick={() => setAttDraft({ ...attDraft, [e.staffId]: st })}
                              >
                                {t.status[st]}
                              </button>
                            ))}
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* ---------- Leave tab ---------- */}
      {tab === "leave" && (
        <div className="card">
          <div className="card-header d-flex align-items-center justify-content-between">
            <h5 className="f-w-600 mb-0">{t.portal.hrPage.tabLeave}</h5>
            <Button onClick={() => setLeaveOpen(true)} disabled={!data || data.staff.length === 0}>
              <IconPlus className="svg-16" />
              <span className="ms-1">{t.portal.hrPage.newLeave}</span>
            </Button>
          </div>
          {leavesLoading ? (
            <div className="card-body text-center py-4">
              <span className="spinner-border text-primary" role="status" />
            </div>
          ) : !leaves || leaves.leaves.length === 0 ? (
            <EmptyState icon={<IconBriefcase />} title={t.portal.hrPage.noLeaves} />
          ) : (
            <>
            <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.common.employee}</th>
                    <th>{t.portal.hrPage.fromDate}</th>
                    <th>{t.portal.hrPage.toDate}</th>
                    <th>{t.common.days}</th>
                    <th>{t.common.reason}</th>
                    <th>{t.common.status}</th>
                    {leaves.leaves.some((l) => l.status === "PENDING") && <th className="text-end">{t.common.actions}</th>}
                  </tr>
                </thead>
                <tbody>
                  {leavesPager.paged.map((l) => (
                    <tr key={l.id}>
                      <td>
                        <p className="mb-0 f-w-700">{l.staffName}</p>
                        <p className="mb-0 ems-fs-11 text-muted">
                          {l.employeeCode} · {t.designations[l.designation as keyof typeof t.designations] ?? l.designation}
                        </p>
                      </td>
                      <td className="ems-fs-13">{formatDate(l.fromDate, locale)}</td>
                      <td className="ems-fs-13">{formatDate(l.toDate, locale)}</td>
                      <td>
                        <span className="badge badge-secondary">{l.days}</span>
                      </td>
                      <td className="ems-fs-13" style={{ maxWidth: 260 }}>{l.reason}</td>
                      <td>
                        <StatusBadge status={l.status} label={t.status[l.status as keyof typeof t.status]} />
                      </td>
                      {leaves.leaves.some((x) => x.status === "PENDING") && (
                        <td className="text-end">
                          {l.status === "PENDING" ? (
                            <div className="btn-group btn-group-sm">
                              <button className="btn btn-success" onClick={() => decideLeave(l, true)} type="button">
                                <IconCheck className="svg-14" />
                              </button>
                              <button className="btn btn-danger" onClick={() => decideLeave(l, false)} type="button">
                                <IconTrash className="svg-14" />
                              </button>
                            </div>
                          ) : (
                            "—"
                          )}
                        </td>
                      )}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <Pagination {...leavesPager} onPageChange={leavesPager.setPage} onSizeChange={leavesPager.setSize} />
            </>
          )}
        </div>
      )}

      {/* ---------- Salary tab ---------- */}
      {tab === "salary" && (
        <div>
          <div className="row g-3 mb-4">
            <div className="col-md-4">
              <div className="card">
                <div className="card-body">
                  <div className="d-flex align-items-center justify-content-between gap-2">
                    <div>
                      <p className="mb-0 ems-fs-13 text-muted">{t.portal.hrPage.monthlyPayroll}</p>
                      <h4 className="mb-0 f-w-700">{formatBDT(salary?.summary.payroll ?? 0, locale)}</h4>
                    </div>
                    <IconDollar className="svg-20 text-primary" />
                  </div>
                </div>
              </div>
            </div>
            <div className="col-md-4">
              <div className="card">
                <div className="card-body">
                  <p className="mb-0 ems-fs-13 text-muted">{t.portal.hrPage.paidLabel}</p>
                  <h4 className="mb-0 f-w-700 text-success">{formatBDT(salary?.summary.paid ?? 0, locale)}</h4>
                </div>
              </div>
            </div>
            <div className="col-md-4">
              <div className="card">
                <div className="card-body">
                  <p className="mb-0 ems-fs-13 text-muted">{t.portal.hrPage.dueLabel}</p>
                  <h4 className="mb-0 f-w-700 text-danger">{formatBDT(salary?.summary.due ?? 0, locale)}</h4>
                </div>
              </div>
            </div>
          </div>

          <div className="card mb-4">
            <div className="card-header d-flex flex-wrap align-items-center justify-content-between gap-2">
              <h5 className="f-w-600 mb-0">
                {t.portal.hrPage.payrollFor}{" "}
            <MonthPicker
              wrapperClassName="d-inline-block ms-1 mb-0"
              style={{ maxWidth: 170, verticalAlign: "middle" }}
              value={month}
              onChange={(e) => setMonth(e.target.value)}
            />
              </h5>
            </div>
            {salaryLoading || !salary ? (
              <div className="card-body text-center py-4">
                <span className="spinner-border text-primary" role="status" />
              </div>
            ) : salary.rows.length === 0 ? (
              <EmptyState icon={<IconUsers />} title={t.portal.hrPage.noStaff} />
            ) : (
              <>
              <div className="table-responsive">
                <table className="table table-hover align-middle mb-0">
                  <thead className="ems-table-head">
                    <tr>
                      <th>{t.portal.hrPage.employeeCode}</th>
                      <th>{t.common.name}</th>
                      <th>{t.portal.hrPage.monthlySalary}</th>
                      <th>{t.common.status}</th>
                      <th className="text-end">{t.common.actions}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {salaryRowsPager.paged.map((r) => (
                      <tr key={r.staffId}>
                        <td>
                          <span className="ems-roll-badge">{r.employeeCode}</span>
                        </td>
                        <td className="f-w-600">{r.name}</td>
                        <td className="f-w-700">{formatBDT(r.salary, locale)}</td>
                        <td>
                          {r.paid ? (
                            <>
                              <span className="badge badge-success">
                                {t.portal.hrPage.alreadyPaid} ({formatDate(r.paidAt, locale)})
                              </span>
                              {r.method && (
                                <p className="mb-0 ems-fs-11 text-muted mt-1">
                                  {t.methods[r.method as keyof typeof t.methods] ?? r.method}
                                  {detailsSummary(r.details).length > 0 && ` · ${detailsSummary(r.details).join(" · ")}`}
                                </p>
                              )}
                            </>
                          ) : (
                            <span className="badge badge-danger">{t.portal.hrPage.dueLabel}</span>
                          )}
                        </td>
                        <td className="text-end">
                          {r.paid ? (
                            "—"
                          ) : (
                            <Button size="sm" variant="success" onClick={() => setPayStaff(r)}>
                              <IconDollar className="svg-14" />
                              <span className="ms-1">{t.portal.hrPage.paySalary}</span>
                            </Button>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <Pagination {...salaryRowsPager} onPageChange={salaryRowsPager.setPage} onSizeChange={salaryRowsPager.setSize} />
              </>
            )}
          </div>

          <Card title={t.portal.hrPage.salaryHistory}>
            {!salary || salary.history.length === 0 ? (
              <EmptyState title={t.portal.hrPage.noSalaries} />
            ) : (
              <>
              <div className="table-responsive">
                <table className="table table-sm table-hover align-middle mb-0">
                  <thead className="ems-table-head">
                    <tr>
                      <th>{t.common.employee}</th>
                      <th>{t.common.month}</th>
                      <th>{t.common.amount}</th>
                      <th>{t.common.method}</th>
                      <th>{t.common.date}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {salaryHistoryPager.paged.map((h) => (
                      <tr key={h.id}>
                        <td className="f-w-600">
                          {h.staffName} <span className="text-muted ems-fs-11">({h.employeeCode})</span>
                        </td>
                        <td>
                          <span className="ems-type-pill">{h.month}</span>
                        </td>
                        <td className="f-w-700">{formatBDT(h.amount, locale)}</td>
                        <td className="ems-fs-13">
                          {t.methods[h.method as keyof typeof t.methods]}
                          {detailsSummary(h.details).length > 0 && (
                            <p className="mb-0 ems-fs-11 text-muted">{detailsSummary(h.details).join(" · ")}</p>
                          )}
                        </td>
                        <td className="ems-fs-13">{formatDate(h.paidAt, locale)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <Pagination {...salaryHistoryPager} onPageChange={salaryHistoryPager.setPage} onSizeChange={salaryHistoryPager.setSize} />
              </>
            )}
          </Card>
        </div>
      )}

      {/* ---------- Login audit tab ---------- */}
      {tab === "audit" && (
        <Card title={t.portal.hrPage.tabAudit} icon={<IconActivity className="svg-20" />}>
          {audit.loading ? (
            <div className="card-body text-center py-4">
              <span className="spinner-border text-primary" role="status" />
            </div>
          ) : !audit.data || audit.data.logs.length === 0 ? (
            <div className="card-body">
              <EmptyState icon={<IconActivity />} title={t.portal.hrPage.auditEmpty} />
            </div>
          ) : (
            <>
              <div className="table-responsive">
                <table className="table table-sm table-hover align-middle mb-0">
                  <thead className="ems-table-head">
                    <tr>
                      <th>{t.common.date}</th>
                      <th>{t.common.name}</th>
                      <th>{t.portal.credentials.role}</th>
                      <th>{t.portal.hrPage.auditIdentifier}</th>
                      <th>{t.common.status}</th>
                      <th>IP</th>
                    </tr>
                  </thead>
                  <tbody>
                    {auditPager.paged.map((l) => (
                      <tr key={l.id}>
                        <td className="ems-fs-12">{formatDate(l.createdAt, locale)}</td>
                        <td className="f-w-600">{l.name}</td>
                        <td>
                          {l.role ? (
                            <span className="ems-type-pill">{t.status[l.role as keyof typeof t.status] ?? l.role}</span>
                          ) : (
                            "—"
                          )}
                        </td>
                        <td className="ems-fs-12"><code className="ems-invoice-badge">{l.identifier}</code></td>
                        <td>
                          {l.success ? (
                            <span className="badge badge-success">{t.portal.hrPage.auditSuccess}</span>
                          ) : (
                            <>
                              <span className="badge badge-danger">{t.portal.hrPage.auditFailed}</span>
                              {l.reason && <p className="mb-0 ems-fs-11 text-muted">{l.reason}</p>}
                            </>
                          )}
                        </td>
                        <td className="ems-fs-12 text-muted">{l.ip ?? "—"}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <Pagination {...auditPager} onPageChange={auditPager.setPage} onSizeChange={auditPager.setSize} />
            </>
          )}
        </Card>
      )}

      {/* ---------- Credentials tab (teacher & staff logins) ---------- */}
      {tab === "credentials" && (
        <CredentialsPanel roles={[...STAFF_SIDE_ROLES]} staff={credentialPersons} />
      )}

      {/* Staff create/edit modal */}
      <Modal
        open={formOpen}
        onClose={() => setFormOpen(false)}
        title={editing ? t.portal.hrPage.editStaff : t.portal.hrPage.newStaff}
        wide
      >
        <div className="row">
          <div className="col-md-6">
            <Input label={t.portal.hrPage.employeeCode} value={form.employeeCode} onChange={(e) => setForm({ ...form, employeeCode: e.target.value })} placeholder="e.g. EMP-001" />
          </div>
          <div className="col-md-6">
            <Input label={t.common.name} value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
          </div>
          <div className="col-md-6">
            <Input label={`${t.common.name} (বাংলা)`} value={form.nameBn} onChange={(e) => setForm({ ...form, nameBn: e.target.value })} />
          </div>
          <div className="col-md-6">
            <Select label={t.portal.admissionsPage.gender} value={form.gender} onChange={(e) => setForm({ ...form, gender: e.target.value })}>
              <option value="MALE">{t.portal.admissionsPage.male}</option>
              <option value="FEMALE">{t.portal.admissionsPage.female}</option>
              <option value="OTHER">{t.portal.admissionsPage.other}</option>
            </Select>
          </div>
          <div className="col-md-6">
            <Input label={t.common.phone} value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="+880 …" />
          </div>
          <div className="col-md-6">
            <Input label={t.common.email} type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
          </div>
          <div className="col-md-6">
            <Select label={t.common.designation} value={form.designation} onChange={(e) => setForm({ ...form, designation: e.target.value })}>
              {STAFF_DESIGNATIONS.map((d) => (
                <option key={d} value={d}>
                  {t.designations[d]}
                </option>
              ))}
            </Select>
          </div>
          <div className="col-md-6">
            <Select label={t.common.department} value={form.department} onChange={(e) => setForm({ ...form, department: e.target.value })}>
              {STAFF_DEPARTMENTS.map((d) => (
                <option key={d} value={d}>
                  {t.departments[d]}
                </option>
              ))}
            </Select>
          </div>
          <div className="col-md-6">
            <DatePicker label={t.portal.hrPage.joinDate} value={form.joinDate} onChange={(e) => setForm({ ...form, joinDate: e.target.value })} />
          </div>
          <div className="col-md-6">
            <Input label={t.portal.hrPage.monthlySalary} type="number" min="0" value={form.monthlySalary} onChange={(e) => setForm({ ...form, monthlySalary: e.target.value })} />
          </div>
        </div>
        <div className="d-flex justify-content-end gap-2">
          <Button variant="secondary" onClick={() => setFormOpen(false)}>
            {t.common.cancel}
          </Button>
          <Button
            onClick={saveStaff}
            loading={saving}
            disabled={!form.employeeCode.trim() || !form.name.trim() || !form.phone.trim()}
          >
            {t.common.save}
          </Button>
        </div>
      </Modal>

      {/* Leave request modal */}
      <Modal open={leaveOpen} onClose={() => setLeaveOpen(false)} title={t.portal.hrPage.newLeave}>
        <Select label={t.common.employee} value={leaveForm.staffId} onChange={(e) => setLeaveForm({ ...leaveForm, staffId: e.target.value })}>
          <option value="">— {t.common.filter} —</option>
          {(data?.staff ?? [])
            .filter((s) => s.status === "ACTIVE")
            .map((s) => (
              <option key={s.id} value={s.id}>
                {s.employeeCode} — {s.name}
              </option>
            ))}
        </Select>
        <div className="row">
          <div className="col-md-6">
            <DatePicker label={t.portal.hrPage.fromDate} value={leaveForm.fromDate} onChange={(e) => setLeaveForm({ ...leaveForm, fromDate: e.target.value })} />
          </div>
          <div className="col-md-6">
            <DatePicker label={t.portal.hrPage.toDate} value={leaveForm.toDate} onChange={(e) => setLeaveForm({ ...leaveForm, toDate: e.target.value })} />
          </div>
        </div>
        <div className="form-group mb-3">
          <label className="col-form-label pt-0 f-w-600">{t.common.reason}</label>
          <textarea
            className="form-control"
            rows={3}
            value={leaveForm.reason}
            onChange={(e) => setLeaveForm({ ...leaveForm, reason: e.target.value })}
          />
        </div>
        <div className="d-flex justify-content-end gap-2">
          <Button variant="secondary" onClick={() => setLeaveOpen(false)}>
            {t.common.cancel}
          </Button>
          <Button onClick={saveLeave} loading={leaveSaving} disabled={!leaveForm.staffId || !leaveForm.reason.trim()}>
            {t.common.save}
          </Button>
        </div>
      </Modal>

      {/* Staff profile photo modal */}
      <Modal
        open={photoStaff !== null}
        onClose={() => {
          setPhotoStaff(null);
          setPhotoPreview(null);
        }}
        title={t.portal.studentsPage.photoTitle}
      >
        {photoStaff && (
          <div className="text-center">
            <div className="mb-3 d-flex justify-content-center">
              <StaffAvatar name={photoStaff.name} photoUrl={photoPreview ?? photoStaff.photoUrl} size={120} />
            </div>
            <p className="mb-1 f-w-700">{photoStaff.name}</p>
            <p className="mb-3 ems-fs-12 text-muted">{t.portal.studentsPage.photoHint}</p>
            <input
              ref={photoInputRef}
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="d-none"
              onChange={(e) => {
                handlePhotoFile(e.target.files?.[0]);
                e.target.value = "";
              }}
            />
            <div className="d-flex flex-wrap justify-content-center gap-2">
              <Button variant="secondary" onClick={() => photoInputRef.current?.click()}>
                <IconCamera className="svg-16" />
                <span className="ms-1">
                  {photoPreview || photoStaff.photoUrl
                    ? t.portal.studentsPage.photoChange
                    : t.portal.studentsPage.photoUpload}
                </span>
              </Button>
              {photoStaff.photoUrl && (
                <Button variant="danger" onClick={removePhoto} disabled={photoSaving}>
                  <IconTrash className="svg-16" />
                  <span className="ms-1">{t.portal.studentsPage.photoRemove}</span>
                </Button>
              )}
              {photoPreview && (
                <Button onClick={savePhoto} loading={photoSaving}>
                  {t.common.save}
                </Button>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* Staff signature modal */}
      <Modal
        open={signStaff !== null}
        onClose={() => {
          setSignStaff(null);
          setSignPreview(null);
        }}
        title={`${t.portal.hrPage.signatureTitle} — ${signStaff?.name ?? ""}`}
      >
        {signStaff && (
          <div className="text-center">
            <div
              className="mb-3 mx-auto d-flex align-items-center justify-content-center"
              style={{
                width: "100%", maxWidth: 320, minHeight: 110,
                border: "1px dashed #c7d4d0", borderRadius: 10,
                background: "#fdfefd", overflow: "hidden",
              }}
            >
              {signPreview || signStaff.signatureUrl ? (
                <img
                  src={signPreview ?? signStaff.signatureUrl ?? ""}
                  alt={signStaff.name}
                  style={{ maxWidth: "100%", maxHeight: 100, objectFit: "contain" }}
                />
              ) : (
                <span className="ems-fs-12 text-muted">{t.portal.hrPage.signatureEmpty}</span>
              )}
            </div>
            <p className="mb-3 ems-fs-12 text-muted">{t.portal.hrPage.signatureHint}</p>
            <input
              ref={signInputRef}
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="d-none"
              onChange={(e) => {
                handleSignatureFile(e.target.files?.[0]);
                e.target.value = "";
              }}
            />
            <div className="d-flex flex-wrap justify-content-center gap-2">
              <Button variant="secondary" onClick={() => signInputRef.current?.click()}>
                <IconCamera className="svg-16" />
                <span className="ms-1">
                  {signPreview || signStaff.signatureUrl
                    ? t.portal.studentsPage.photoChange
                    : t.portal.studentsPage.photoUpload}
                </span>
              </Button>
              {signStaff.signatureUrl && (
                <Button variant="danger" onClick={removeSignature} disabled={signSaving}>
                  <IconTrash className="svg-16" />
                  <span className="ms-1">{t.portal.studentsPage.photoRemove}</span>
                </Button>
              )}
              {signPreview && (
                <Button onClick={saveSignature} loading={signSaving}>
                  {t.common.save}
                </Button>
              )}
            </div>
          </div>
        )}
      </Modal>

      {/* Pay salary modal */}
      <Modal
        open={payStaff !== null}
        onClose={() => setPayStaff(null)}
        title={`${t.portal.hrPage.paySalary} — ${payStaff?.name ?? ""}`}
      >
        {payStaff && (
          <div>
            <div className="p-3 rounded mb-3 d-flex justify-content-between align-items-center" style={{ background: "rgba(36,105,92,0.07)" }}>
              <div>
                <p className="mb-0 f-w-700">{payStaff.name}</p>
                <p className="mb-0 ems-fs-12 text-muted">
                  {payStaff.employeeCode} · {salary?.month}
                </p>
              </div>
              <h5 className="mb-0 f-w-800 ems-text-teal">{formatBDT(payStaff.salary, locale)}</h5>
            </div>
            <Select
              label={t.common.method}
              value={payMethod}
              onChange={(e) => {
                setPayMethod(e.target.value);
                setPayDetails({});
              }}
            >
              {PAYMENT_METHODS.map((m) => (
                <option key={m} value={m}>
                  {t.methods[m]}
                </option>
              ))}
            </Select>

            {/* method-specific transaction details — same fields as fee collections */}
            {payMethod === "CASH" ? (
              <p className="ems-fs-11 text-muted mb-3 px-1">{t.portal.feesPage.cfCashHint}</p>
            ) : (
              <div className="p-3 mb-3 rounded" style={{ background: "rgba(36,105,92,0.05)" }}>
                <p className="ems-fs-11 f-w-700 text-uppercase text-muted mb-2">{t.portal.feesPage.cfDetailsTitle}</p>
                {MOBILE_METHODS.includes(payMethod) && (
                  <div className="row g-2">
                    <div className="col-sm-6">
                      <Input
                        label={`${t.portal.feesPage.cfTxnId} *`}
                        value={payDetails.txnId ?? ""}
                        placeholder="8N7A1B2C"
                        onChange={(e) => setPayDetail("txnId", e.target.value)}
                      />
                    </div>
                    <div className="col-sm-6">
                      <Input
                        label={t.portal.feesPage.cfAccount}
                        value={payDetails.account ?? ""}
                        placeholder="01XXXXXXXXX"
                        onChange={(e) => setPayDetail("account", e.target.value)}
                      />
                    </div>
                  </div>
                )}
                {payMethod === "BANK_TRANSFER" && (
                  <div className="row g-2">
                    <div className="col-sm-6">
                      <Input
                        label={`${t.portal.feesPage.cfBank} *`}
                        value={payDetails.bankName ?? ""}
                        onChange={(e) => setPayDetail("bankName", e.target.value)}
                      />
                    </div>
                    <div className="col-sm-6">
                      <Input
                        label={t.portal.feesPage.cfBranch}
                        value={payDetails.branch ?? ""}
                        onChange={(e) => setPayDetail("branch", e.target.value)}
                      />
                    </div>
                    <div className="col-sm-6">
                      <Input
                        label={`${t.portal.feesPage.cfRef} *`}
                        value={payDetails.refNo ?? ""}
                        onChange={(e) => setPayDetail("refNo", e.target.value)}
                      />
                    </div>
                    <div className="col-sm-6">
                      <Input
                        label={t.portal.feesPage.cfAcNo}
                        value={payDetails.account ?? ""}
                        onChange={(e) => setPayDetail("account", e.target.value)}
                      />
                    </div>
                  </div>
                )}
                {payMethod === "CARD" && (
                  <div className="row g-2">
                    <div className="col-sm-4">
                      <Select
                        label={t.portal.feesPage.cfCardType}
                        value={payDetails.cardType ?? ""}
                        onChange={(e) => setPayDetail("cardType", e.target.value)}
                      >
                        <option value="">—</option>
                        <option value="credit">{t.portal.feesPage.cfCredit}</option>
                        <option value="debit">{t.portal.feesPage.cfDebit}</option>
                        <option value="prepaid">{t.portal.feesPage.cfPrepaid}</option>
                      </Select>
                    </div>
                    <div className="col-sm-4">
                      <Input
                        label={t.portal.feesPage.cfLast4}
                        value={payDetails.last4 ?? ""}
                        placeholder="1234"
                        maxLength={4}
                        onChange={(e) => setPayDetail("last4", e.target.value.replace(/\D/g, ""))}
                      />
                    </div>
                    <div className="col-sm-4">
                      <Input
                        label={`${t.portal.feesPage.cfApproval} *`}
                        value={payDetails.refNo ?? ""}
                        onChange={(e) => setPayDetail("refNo", e.target.value)}
                      />
                    </div>
                  </div>
                )}
              </div>
            )}
            <div className="form-group mb-3">
              <label className="col-form-label pt-0 f-w-600">{t.common.note}</label>
              <textarea
                className="form-control"
                rows={2}
                value={payNote}
                onChange={(e) => setPayNote(e.target.value)}
              />
            </div>
            <div className="d-flex justify-content-end gap-2">
              <Button variant="secondary" onClick={() => setPayStaff(null)}>
                {t.common.cancel}
              </Button>
              <Button variant="success" onClick={paySalary} loading={paySaving} disabled={payMissing.length > 0}>
                <IconDollar className="svg-16" />
                <span className="ms-1">{t.portal.hrPage.paySalary}</span>
              </Button>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
}
