/* ---------- Employee profile popup ---------- */
function EmployeeProfile({ emp, contract, onClose, onUpdate, onContractsChanged }) {
  const { useState } = React;
  const [tab, setTab] = useState("attendance");
  const [notes, setNotes] = useState([]);
  const [draft, setDraft] = useState("");
  const [editEmp, setEditEmp] = useState(false);
  const [editContract, setEditContract] = useState(false);
  const [newContract, setNewContract] = useState(false);
  const [fixDay, setFixDay] = useState(null); // { day, index }
  const [addDoc, setAddDoc] = useState(false);
  const [leaveFilter, setLeaveFilter] = useState("All");
  const [reqFilter, setReqFilter] = useState("All");
  const [apiAttn, setApiAttn] = useState([]);   // punch sessions, this week
  const [apiDocs, setApiDocs] = useState([]);   // documents on file
  const [pastContracts, setPastContracts] = useState([]); // archived contracts
  const [payRecords, setPayRecords] = useState([]);       // payroll records, all periods
  const [warnings, setWarnings] = useState([]);           // disciplinary warnings on record
  const [addWarn, setAddWarn] = useState(false);

  const MONTH_FULL = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  const periodName = (p) => { const x = String(p).split("-"); return TV(MONTH_FULL[(+x[1] || 1) - 1]) + " " + x[0]; };

  // Attendance window: the last 7 days ending today.
  const weekStartIso = () => {
    const d = new Date(); d.setDate(d.getDate() - 6);
    return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
  };
  const secs = (x) => { const y = String(x).split(":"); return (+y[0] * 3600) + (+y[1] * 60) + (+y[2] || 0); };
  const hm = (x) => String(x).slice(0, 5); // late/early compare on HH:MM, not the seconds
  const toSession = (r) => ({
    key: r.id, inId: r.inId, outId: r.outId, dateIso: r.dateIso, day: r.day,
    in: r.in, out: r.out, breakMin: r.breakMin, breakSec: r.breakSec,
    durSec: r.in && r.out ? secs(r.out) - secs(r.in) - r.breakSec : null,
    late: !!r.in && hm(r.in) > "08:12", early: !!r.out && hm(r.out) < "16:30",
    fixed: r.fixed, web: r.web, weekend: false
  });
  const loadAttn = () => {
    if (!emp) return;
    API.timeLogs.list({ employee: emp.id, date_after: weekStartIso() })
      .then((rows) => setApiAttn(rows.map(toSession).sort((a, b) => (a.dateIso < b.dateIso ? 1 : -1))))
      .catch(() => setApiAttn([]));
  };
  const loadDocs = () => {
    if (!emp) return;
    API.docs.list(emp.id).then(setApiDocs).catch(() => setApiDocs([]));
  };
  const loadWarnings = () => {
    if (!emp) return;
    API.warnings.list({ employee: emp.id }).then(setWarnings).catch(() => setWarnings([]));
  };
  const loadHistory = () => {
    if (!emp) return;
    API.contracts.history(emp.id).then(setPastContracts).catch(() => setPastContracts([]));
    API.pay.records.list()
      .then((rs) => setPayRecords(rs.filter((r) => r.empId === emp.id)))
      .catch(() => setPayRecords([]));
  };

  React.useEffect(() => {
    if (!emp) return;
    setTab("overview");
    setNotes([]);
    setDraft("");
    setEditEmp(false); setEditContract(false); setNewContract(false); setFixDay(null); setAddDoc(false);
    setApiAttn([]); setApiDocs([]); setPastContracts([]); setPayRecords([]);
    setWarnings([]); setAddWarn(false);
    API.notes.list(emp.id).then(setNotes).catch(() => {});
    loadAttn();
    loadDocs();
    loadHistory();
    loadWarnings();
  }, [emp && emp.id]);
  if (!emp) return null;

  const addNote = () => {
    const text = draft.trim();
    if (!text) return;
    API.notes.add(emp.id, text)
      .then((note) => {
        setNotes((ns) => [note, ...ns]);
        setDraft("");
        notify(T("hr.noteAdded", { name: emp.name }));
      })
      .catch((ex) => notify(T("hr.noteSaveFailed", { error: ex.message })));
  };

  const removeWarning = (w) => {
    API.warnings.remove(w.id)
      .then(() => { setWarnings((ws) => ws.filter((x) => x.id !== w.id)); notify(T("hr.warningRemoved")); })
      .catch((ex) => notify(T("hr.warningRemoveFailed", { error: ex.message })));
  };
  const warnTone = (sev) => (sev === "Final warning" ? "red" : sev === "Warning" ? "amber" : "blue");

  const attendance = apiAttn;
  const workedDays = attendance.filter((a) => !a.weekend);
  const totalHrs = workedDays.reduce((s, a) => s + (a.durSec || 0), 0) / 3600;
  const lateCount = workedDays.filter((a) => a.late).length;
  // Leave history: D.leaves holds the server rows (HR loads them).
  const empLeaves = (D.leaves || []).filter((l) => l.empId === emp.id);
  const earlyLeaves = empLeaves.filter((l) => l.type === "Early leave");
  const sickLeaves = empLeaves.filter((l) => l.type === "Sick");
  const otherLeaves = empLeaves.filter((l) => l.type !== "Sick" && l.type !== "Early leave");
  const sickDays = sickLeaves.filter((l) => l.status === "Approved").reduce((s, l) => s + l.days, 0);
  const otherDays = otherLeaves.filter((l) => l.status === "Approved").reduce((s, l) => s + l.days, 0);
  // What the employee has actually earned so far in their current leave cycle.
  const accrual = leaveAccrual(emp.joinedIso, (contract && contract.leaveEntitlement) || 0);
  const annualUsed = otherLeaves
    .filter((l) => l.type === "Annual" && l.status === "Approved" &&
      (!accrual.cycleStart || (l.fromIso && l.fromIso >= accrual.cycleStart && (!accrual.cycleEnd || l.fromIso <= accrual.cycleEnd))))
    .reduce((s, l) => s + l.days, 0);
  const documents = apiDocs;
  const mine = (rows) => (rows || []).filter((r) => r.empId === emp.id);
  const myLeaveReqs = mine(D.leaves);
  const myAdvances = mine(D.advances);
  // No contract is ever created for an employee behind the user's back, so a
  // missing one is a real state: the tab flags it and offers the create form.
  // ContractEditModal seeds its own defaults from `contract === null`.
  const hasContract = !!contract;

  const tabs = [
    { id: "overview", label: T("hr.overview") },
    { id: "contract", label: T("hr.contract") },
    { id: "money", label: T("hr.financials") },
    { id: "attendance", label: T("hr.attendance"), count: workedDays.length },
    { id: "leaves", label: T("hr.leaves"), count: earlyLeaves.length + sickLeaves.length + otherLeaves.length },
    { id: "requests", label: T("hr.requests"), count: myLeaveReqs.length + myAdvances.length },
    { id: "warnings", label: T("hr.warnings"), count: warnings.length },
    { id: "docs", label: T("ess.documents"), count: documents.length },
    { id: "notes", label: T("hr.notes"), count: notes.length }
  ];

  const pendingOther = otherLeaves.filter((l) => l.status === "Pending").length;
  const attendanceRate = workedDays.length ? Math.round(((workedDays.length - lateCount) / workedDays.length) * 100) : 100;

  return (
    <Modal open={!!emp} onClose={onClose} title={emp.name} sub={TV(emp.role) + " · " + TV(emp.dept)} width={1080} height="88vh"
      footer={
        <div className="je-foot">
          <Btn icon="edit" onClick={() => setEditEmp(true)}>{T("hr.editEmployee")}</Btn>
          <div className="btnrow"><Btn onClick={onClose}>{T("common.close")}</Btn></div>
        </div>
      }>
      <Tabs active={tab} onChange={setTab} tabs={tabs} />

      {tab === "overview" ? (
        <div className="ep-overview">
          <div className="ep-stats">
            <div className="ep-stat"><span className="ep-stat-v mono"><HoursHM h={totalHrs} /></span><span className="ep-stat-l">{T("ess.hoursThisWeek")}</span></div>
            <div className="ep-stat"><span className="ep-stat-v mono">{attendanceRate}%</span><span className="ep-stat-l">{T("hr.onTimeRate")}</span></div>
            <div className="ep-stat"><span className="ep-stat-v mono">{lateCount}</span><span className="ep-stat-l">{T("hr.lateArrivals")}</span></div>
            <div className="ep-stat"><span className="ep-stat-v mono">{earlyLeaves.length}</span><span className="ep-stat-l">{T("hr.earlyLeaves")}</span></div>
            <div className="ep-stat"><span className="ep-stat-v mono">{sickDays}</span><span className="ep-stat-l">{T("ess.sickDays")}</span></div>
            <div className="ep-stat"><span className="ep-stat-v mono">{otherDays}</span><span className="ep-stat-l">{T("hr.leaveDaysTaken")}</span></div>
            <div className="ep-stat"><span className="ep-stat-v mono">{pendingOther}</span><span className="ep-stat-l">{T("ess.pendingRequests")}</span></div>
            <div className="ep-stat"><span className="ep-stat-v mono">{documents.length}</span><span className="ep-stat-l">{T("ess.documents")}</span></div>
          </div>
          <div className="ep-info">
            <KV k={T("ess.employeeNo")} v={emp.no != null ? "#" + emp.no : "—"} mono />
            <KV k={T("hr.department")} v={TV(emp.dept)} />
            <KV k={T("common.status")} v={TV(emp.status)} />
            <KV k={T("hr.joined")} v={emp.joined} />
            <KV k={T("hr.salaryMonth")} v={hasContract ? money(emp.salary) : T("hr.noContract")} mono={hasContract} />
            <KV k={T("hr.annualSalary")} v={hasContract ? money(emp.salary * 12) : "—"} mono={hasContract} />
          </div>
          {!hasContract ? (
            <div className="role-locked" style={{ marginTop: 12 }}>
              <Icon name="alert" size={14} />{T("hr.noContractOnFile", { name: emp.name })}
            </div>
          ) : null}
        </div>
      ) : null}

      {tab === "contract" && !hasContract ? (
        <div className="ep-overview">
          <div className="inv-items-head" style={{ marginBottom: 10 }}>
            <span className="field-label" style={{ margin: 0 }}>{T("hr.activeContract")}</span>
            <span className="btnrow">
              <Btn small variant="primary" icon="plus" onClick={() => setEditContract(true)}>{T("hr.addContract")}</Btn>
            </span>
          </div>
          <div className="role-locked" style={{ marginBottom: 14 }}>
            <Icon name="alert" size={14} />{T("hr.noContractOnFile", { name: emp.name })}
          </div>
          {pastContracts.length ? (
            <div style={{ marginTop: 14 }}>
              <span className="field-label">{T("hr.previousContracts")}</span>
              <div className="ep-list" style={{ marginTop: 7 }}>
                <div className="ep-row ep-head ep-row-3"><span>{T("common.type")}</span><span>{T("hr.period")}</span><span>{T("hr.hours")}</span><span className="ta-r">{T("common.status")}</span></div>
                {pastContracts.map((h, i) => (
                  <div className="ep-row ep-row-3" key={h._id || i}>
                    <span><b>{TV(h.type)}</b>{h.no != null ? <span className="mono dim"> · #{h.no}</span> : null}</span>
                    <span className="mono dim">{h.start} → {h.ended || h.end || "—"}</span>
                    <span className="mono">{T("hr.hoursPerWeekShort", { n: h.hours })}</span>
                    <span className="ta-r"><Badge>{T("hr.ended")}</Badge></span>
                  </div>
                ))}
              </div>
            </div>
          ) : null}
        </div>
      ) : null}

      {tab === "contract" && hasContract ? (() => {
        const c = contract;
        return (
          <div className="ep-overview">
            <div className="inv-items-head" style={{ marginBottom: 10 }}>
              <span className="field-label" style={{ margin: 0 }}>{T("hr.activeContract")}</span>
              <span className="btnrow">
                <Btn small icon="edit" onClick={() => setEditContract(true)}>{T("hr.editContract")}</Btn>
                <Btn small variant="primary" icon="plus" onClick={() => setNewContract(true)}>{T("hr.newContract")}</Btn>
              </span>
            </div>
            <div className="ep-stats">
              <div className="ep-stat"><span className="ep-stat-v">{TV(c.type)}</span><span className="ep-stat-l">{T("hr.contractType")}</span></div>
              <div className="ep-stat"><span className="ep-stat-v mono">{c.daysLeft != null ? T("hr.daysShort", { n: c.daysLeft }) : "\u2014"}</span><span className="ep-stat-l">{c.daysLeft != null ? T("hr.untilExpiry") : T("hr.noEndDate")}</span></div>
              <div className="ep-stat"><span className="ep-stat-v mono"><HoursHM h={c.hours} /></span><span className="ep-stat-l">{T("hr.perWeek")}</span></div>
              <div className="ep-stat"><span className="ep-stat-v mono">{fmtDays(annualUsed)}/{fmtDays(accrual.accrued)}</span><span className="ep-stat-l">{T("ess.accruedBalance")}</span></div>
            </div>
            {c.daysLeft != null && c.daysLeft < 180 ? (
              <div className="role-locked" style={{ marginBottom: 14 }}><Icon name="clock" size={14} />{T("hr.contractEndsNotice", { end: c.end, notice: TV(c.notice) })}</div>
            ) : null}
            <div className="ep-info">
              <KV k={T("hr.contractNo")} v={c.no != null ? "#" + c.no : "—"} mono />
              <KV k={T("hr.startDate")} v={c.start} />
              <KV k={T("hr.endDate")} v={c.end || T("hr.openEnded")} />
              <KV k={T("hr.probation")} v={TV(c.probation) + " \u00b7 " + (c.probationPassed ? T("hr.passed") : T("hr.inProgress"))} />
              <KV k={T("hr.noticePeriod")} v={TV(c.notice)} />
              <KV k={T("hr.baseSalaryPerMonth")} v={money(emp.salary)} mono />
              {c.allowances.map((a, i) => <KV key={i} k={TV(a.name)} v={T("hr.perMonthAmount", { amount: money(a.amt) })} mono />)}
              <KV k={T("hr.annualLeave")} v={T("hr.daysPerYear", { n: fmtDays(c.leaveEntitlement) })} />
              <KV k={T("ess.accruedBalance")} v={T("ess.usedOfDays", { used: fmtDays(annualUsed), total: fmtDays(accrual.accrued) })} />
              {accrual.known && accrual.cycleStart ? <KV k={T("ess.accrualCycle")} v={T("ess.cycleRange", { from: dmy(accrual.cycleStart), to: dmy(accrual.cycleEnd) })} mono /> : null}
              <KV k={T("hr.sickLeave")} v={T("ess.usedOfDays", { used: sickDays, total: c.sickEntitlement })} />
              {c.permit ? <KV k={T("hr.workPermit")} v={T("hr.permitExpires", { no: c.permit.no, exp: c.permit.exp })} mono /> : null}
            </div>
            {pastContracts.length ? (
              <div style={{ marginTop: 14 }}>
                <span className="field-label">{T("hr.previousContracts")}</span>
                <div className="ep-list" style={{ marginTop: 7 }}>
                  <div className="ep-row ep-head ep-row-3"><span>{T("common.type")}</span><span>{T("hr.period")}</span><span>{T("hr.hours")}</span><span className="ta-r">{T("common.status")}</span></div>
                  {pastContracts.map((h, i) => (
                    <div className="ep-row ep-row-3" key={h._id || i}>
                      <span><b>{TV(h.type)}</b>{h.no != null ? <span className="mono dim"> · #{h.no}</span> : null}</span>
                      <span className="mono dim">{h.start} → {h.ended || h.end || "—"}</span>
                      <span className="mono">{T("hr.hoursPerWeekShort", { n: h.hours })}</span>
                      <span className="ta-r"><Badge>{T("hr.ended")}</Badge></span>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
            {c.amendments.length ? (
              <div className="ep-list" style={{ marginTop: 14 }}>
                <div className="ep-row ep-head ep-row-3"><span>{T("common.date")}</span><span></span><span>{T("hr.amendment")}</span><span></span></div>
                {c.amendments.map((a, i) => (
                  <div className="ep-row ep-row-3" key={i}><span className="mono">{a.date}</span><span></span><span>{a.text}</span><span></span></div>
                ))}
              </div>
            ) : null}
          </div>
        );
      })() : null}

      {tab === "money" ? (() => {
        const adjustments = (D.payAdjustments || []).filter((a) => a.empId === emp.id);
        const advances = (D.advances || []).filter((v) => v.empId === emp.id);
        const bonus = adjustments.filter((a) => a.kind !== "Deduction").reduce((s, a) => s + a.amount, 0);
        const ded = adjustments.filter((a) => a.kind === "Deduction").reduce((s, a) => s + a.amount, 0);
        const advRepay = advances.filter((v) => v.status === "Active").reduce((s, v) => s + Math.min(v.monthly, v.amount - v.repaid), 0);
        const advBalance = advances.filter((v) => v.status === "Active").reduce((s, v) => s + (v.amount - v.repaid), 0);
        // Payroll history comes from the server's records — periods are never invented.
        const cur = API.fmt.period();
        const curRec = payRecords.find((r) => r.period === cur);
        const net = curRec && curRec.computed ? curRec.net : emp.salary + bonus - ded - advRepay;
        const curStatus = curRec ? curRec.status : "Pending";
        const history = payRecords.filter((r) => r.period !== cur).sort((a, b) => (a.period < b.period ? 1 : -1));
        const tone = (s) => (s === "Paid" ? "green" : s === "Processing" ? "blue" : "amber");
        return (
          <div className="ep-overview">
            <div className="ep-stats">
              <div className="ep-stat"><span className="ep-stat-v mono">{money(net)}</span><span className="ep-stat-l">{T("ess.netPay")} · {periodName(cur)}</span></div>
              <div className="ep-stat"><span className="ep-stat-v mono" style={{ color: bonus ? "var(--green)" : undefined }}>{bonus ? "+" + money(bonus) : "—"}</span><span className="ep-stat-l">{T("hr.bonuses")}</span></div>
              <div className="ep-stat"><span className="ep-stat-v mono" style={{ color: ded ? "var(--red)" : undefined }}>{ded ? "−" + money(ded) : "—"}</span><span className="ep-stat-l">{T("hr.deductions")}</span></div>
              <div className="ep-stat"><span className="ep-stat-v mono">{advBalance ? money(advBalance) : "—"}</span><span className="ep-stat-l">{T("hr.advanceBalance")}</span></div>
            </div>
            <div className="ep-list">
              <div className="ep-row ep-head ep-row-3"><span>{T("hr.period")}</span><span>{T("ess.paidOn")}</span><span>{T("common.amount")}</span><span className="ta-r">{T("common.status")}</span></div>
              <div className="ep-row ep-row-3">
                <span><b>{periodName(cur)}</b></span>
                <span className="mono dim">{(curRec && curRec.paidOn) || "—"}</span>
                <span className="mono strong">{money(net)}</span>
                <span className="ta-r"><Badge tone={tone(curStatus)}>{curStatus}</Badge></span>
              </div>
              {history.map((p) => (
                <div className="ep-row ep-row-3" key={p.id}>
                  <span>{periodName(p.period)}</span>
                  <span className="mono dim">{p.paidOn || "—"}</span>
                  <span className="mono">{money(p.net)}</span>
                  <span className="ta-r"><Badge tone={tone(p.status)}>{p.status}</Badge></span>
                </div>
              ))}
            </div>
            {adjustments.length ? (
              <div style={{ marginTop: 14 }}>
                <span className="field-label">{T("hr.bonusesDeductions")} · {periodName(cur)}</span>
                <div className="ep-list" style={{ marginTop: 7 }}>
                  {adjustments.map((a, i) => (
                    <div className="ep-row ep-row-3" key={i}>
                      <span><b>{TV(a.kind)}</b></span>
                      <span className="dim">{a.note || "—"}</span>
                      <span></span>
                      <span className="ta-r mono strong" style={{ color: a.kind === "Deduction" ? "var(--red)" : "var(--green)" }}>{a.kind === "Deduction" ? "−" : "+"}{money(a.amount)}</span>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
            {advances.length ? (
              <div style={{ marginTop: 14 }}>
                <span className="field-label">{T("hr.salaryAdvances")}</span>
                <div className="ep-list" style={{ marginTop: 7 }}>
                  <div className="ep-row ep-head ep-row-3"><span>{T("hr.refIssued")}</span><span>{T("hr.repaid")}</span><span>{T("hr.balance")}</span><span className="ta-r">{T("common.status")}</span></div>
                  {advances.map((v, i) => (
                    <div className="ep-row ep-row-3" key={i}>
                      <span><b>{refNo(v.id)}</b> <span className="dim">{v.issued}</span></span>
                      <span className="mono" style={{ color: "var(--green)" }}>{money(v.repaid)}</span>
                      <span className="mono strong">{money(v.amount - v.repaid)}</span>
                      <span className="ta-r"><Badge tone={v.status === "Active" ? "amber" : "green"}>{v.status}</Badge></span>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
          </div>
        );
      })() : null}

      {tab === "attendance" ? (
        attendance.length === 0 ? (
          <p className="ep-empty">{T("hr.noPunchesRecordedInTheLast")}</p>
        ) : (
        <div className="ep-list">
          <div className="ep-row ep-head">
            <span>{T("hr.day")}</span><span className="ta-c">{T("ess.checkIn")}</span><span className="ta-c">{T("ess.checkOut")}</span><span className="ta-r">{T("hr.duration")}</span>
          </div>
          {attendance.map((a, i) => (
            a.weekend ? (
              <div className="ep-row ep-weekend" key={i}><span>{a.day}</span><span className="ep-rest">{T("hr.weekend")}</span></div>
            ) : (
              <div className="ep-row" key={a.key || i}>
                <span><span className="nw mono">{dmy(a.dateIso) || a.day}</span>{a.web ? <span className="ep-flag early">{T("ess.webFlag")}</span> : null}</span>
                <span className="ta-c mono"><TimeSec t={a.in} />{a.late ? <span className="ep-flag late">{T("ess.lateFlag")}</span> : null}</span>
                <span className="ta-c mono"><TimeSec t={a.out} />{a.early ? <span className="ep-flag early">{T("ess.earlyFlag")}</span> : null}</span>
                <span className="ta-r mono strong ep-hours">
                  {a.durSec == null ? <span className="dim">—</span> : <DurSec s={a.durSec} />}
                  {a.fixed ? <span className="ep-flag paid" title={T("hr.manuallyCorrected")}>{T("ess.fixedFlag")}</span> : null}
                  <button type="button" className="ep-fix" title={T("hr.correctEntry")} onClick={() => setFixDay({ day: a })}>
                    <Icon name="edit" size={13} />
                  </button>
                </span>
              </div>
            )
          ))}
        </div>
        )
      ) : null}

      {tab === "leaves" ? (() => {
        // `kind` stays English — it is the chip's filter id. `label` is what shows.
        const LEAVE_LABEL = {
          "Early leave": T("hr.earlyLeave"),
          "Sick leave": T("hr.sickLeave"),
          "Other leave": T("hr.otherLeave")
        };
        const all = [
          ...earlyLeaves.map((l) => ({ kind: "Early leave", from: l.from, to: l.to, detail: l.note || T("hr.earlyLeave"), time: null, days: l.days || null, status: l.status })),
          ...sickLeaves.map((l) => ({ kind: "Sick leave", from: l.from, to: l.to, detail: l.note || T("hr.sickLeave"), time: null, days: l.days, status: l.status })),
          ...otherLeaves.map((l) => ({ kind: "Other leave", from: l.from, to: l.to, detail: TV(l.type), time: null, days: l.days, status: l.status }))
        ];
        const shown = leaveFilter === "All" ? all : all.filter((r) => r.kind === leaveFilter);
        return (
          <div>
            <div className="toolbar page-toolbar">
              <Chips active={leaveFilter} onChange={setLeaveFilter} options={[
                { id: "All", label: T("hr.all"), count: all.length },
                { id: "Early leave", label: T("hr.earlyLeave"), count: earlyLeaves.length },
                { id: "Sick leave", label: T("hr.sickLeave"), count: sickLeaves.length },
                { id: "Other leave", label: T("hr.otherLeave"), count: otherLeaves.length }
              ]} />
            </div>
            {shown.length === 0 ? <p className="ep-empty">{leaveFilter === "All" ? T("hr.noLeaveRecorded") : T("hr.noLeaveKindRecorded", { kind: LEAVE_LABEL[leaveFilter] })}</p> : (
              <div className="ep-list">
                <div className="ep-row ep-head ep-row-5">
                  <span>{T("common.type")}</span><span>{T("ess.from")}</span><span>{T("hr.toTime")}</span><span>{T("hr.details")}</span><span className="ta-r">{T("hr.daysStatus")}</span>
                </div>
                {shown.map((r, i) => (
                  <div className="ep-row ep-row-5" key={i}>
                    <span><b>{LEAVE_LABEL[r.kind]}</b></span>
                    <span className="mono">{r.from}</span>
                    <span className="mono dim">{r.to || r.time || "—"}</span>
                    <span>{r.detail}</span>
                    <span className="ta-r">{r.days ? <span className="mono strong" style={{ marginRight: 8 }}>{T("hr.daysShort", { n: r.days })}</span> : null}<Badge tone={r.status === "Pending" ? "amber" : undefined}>{r.status}</Badge></span>
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })() : null}

      {tab === "requests" ? (() => {
        // `kind` stays English \u2014 it is the chip's filter id. `label` is what shows.
        const REQ_LABEL = { "Leave": T("hr.leave"), "Salary advance": T("hr.salaryAdvance") };
        const all = [
          ...myLeaveReqs.map((l) => ({ kind: "Leave", ref: refNo(l.id), detail: TV(l.type) + " \u00b7 " + l.from + " \u2192 " + l.to + (l.days ? " \u00b7 " + TP("hr.daysCount", l.days) : ""), amount: null, status: l.status })),
          ...myAdvances.map((v) => ({ kind: "Salary advance", ref: refNo(v.id), detail: (v.note || T("hr.advance")) + " \u00b7 " + T("hr.advanceRepaymentIssued", { amount: money(v.monthly), date: v.issued }), amount: v.amount, status: v.status }))
        ];
        const shown = reqFilter === "All" ? all : all.filter((r) => r.kind === reqFilter);
        const tone = (s) => (s === "Pending" ? "amber" : s === "Declined" ? "red" : s === "Active" ? "blue" : undefined);
        return (
          <div>
            <div className="toolbar page-toolbar">
              <Chips active={reqFilter} onChange={setReqFilter} options={[
                { id: "All", label: T("hr.all"), count: all.length },
                { id: "Leave", label: T("hr.leave"), count: all.filter((r) => r.kind === "Leave").length },
                { id: "Salary advance", label: T("hr.salaryAdvance"), count: all.filter((r) => r.kind === "Salary advance").length }
              ]} />
            </div>
            {shown.length === 0 ? <p className="ep-empty">{T("hr.noRequestsRecorded")}</p> : (
              <div className="ep-list">
                <div className="ep-row ep-head ep-row-5">
                  <span>{T("common.type")}</span><span>{T("hr.ref")}</span><span>{T("hr.details")}</span><span>{T("common.amount")}</span><span className="ta-r">{T("common.status")}</span>
                </div>
                {shown.map((r, i) => (
                  <div className="ep-row ep-row-5" key={i}>
                    <span><b>{REQ_LABEL[r.kind]}</b></span>
                    <span className="mono dim">{r.ref}</span>
                    <span>{r.detail}</span>
                    <span className="mono strong">{r.amount ? money(r.amount) : "\u2014"}</span>
                    <span className="ta-r"><Badge tone={tone(r.status)}>{r.status}</Badge></span>
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })() : null}

      {tab === "warnings" ? (
        <div>
          <div className="inv-items-head" style={{ marginBottom: 10 }}>
            <span className="field-label" style={{ margin: 0 }}>{T("hr.warningsOnRecord")}</span>
            <Btn small variant="primary" icon="plus" onClick={() => setAddWarn(true)}>{T("hr.addWarning")}</Btn>
          </div>
          {warnings.length === 0 ? <p className="ep-empty">{T("hr.noWarningsOnRecord")}</p> : (
            <div className="ep-list">
              <div className="ep-row ep-head ep-warn-row">
                <span>{T("hr.severity")}</span><span>{T("common.reason")}</span><span>{T("common.date")}</span><span></span>
              </div>
              {warnings.map((w) => (
                <div className="ep-row ep-warn-row" key={w.id}>
                  <span><Badge tone={warnTone(w.severity)}>{TV(w.severity)}</Badge></span>
                  <span>{w.reason}</span>
                  <span className="mono dim">{w.date}</span>
                  <span className="ta-r">
                    <button type="button" className="inv-del" title={T("common.remove")} onClick={() => removeWarning(w)}>
                      <Icon name="trash" size={14} />
                    </button>
                  </span>
                </div>
              ))}
            </div>
          )}
        </div>
      ) : null}

      {tab === "docs" ? (
        <div className="ep-docs">
          <div className="inv-items-head" style={{ marginBottom: 10 }}>
            <span className="field-label" style={{ margin: 0 }}>{T("hr.documentsOnFile")}</span>
            <Btn small variant="primary" icon="plus" onClick={() => setAddDoc(true)}>{T("hr.addDocument")}</Btn>
          </div>
          {documents.length === 0 ? <p className="ep-empty">{T("hr.noDocumentsOnFile")}</p> : documents.map((d, i) => (
            <div className="ep-doc" key={d.id || i}>
              <span className="ep-doc-ic"><Icon name="file" size={18} /></span>
              <span className="ep-doc-main">
                <b>{d.name}</b>
                <small>{TV(d.type)} · {d.size} · {d.date}</small>
              </span>
              <button type="button" className="ep-doc-btn" onClick={() => notify(T("ess.downloadingFile", { name: d.name }))} title={T("common.download")}>
                <Icon name="download" size={16} />
              </button>
              <button type="button" className="ep-doc-btn ep-doc-del" title={T("common.remove")}
                onClick={() => {
                  API.docs.remove(d.id)
                    .then(() => { setApiDocs((ds) => ds.filter((x) => x.id !== d.id)); notify(T("hr.documentRemoved", { name: d.name })); })
                    .catch((ex) => notify(T("hr.documentRemoveFailed", { error: ex.message })));
                }}>
                <Icon name="trash" size={15} />
              </button>
            </div>
          ))}
        </div>
      ) : null}

      {tab === "notes" ? (
        <div className="ep-notes">
          <div className="ep-note-add">
            <textarea className="input area" rows={3} placeholder={T("hr.addNoteAbout", { name: emp.name })}
              value={draft} onChange={(e) => setDraft(e.target.value)}></textarea>
            <div className="ep-note-actions">
              <Btn variant="primary" icon="plus" onClick={addNote} disabled={!draft.trim()}>{T("hr.addNote")}</Btn>
            </div>
          </div>
          {notes.length === 0 ? (
            <p className="ep-empty">{T("hr.noNotesYetAddTheFirst")}</p>
          ) : (
            <ul className="ep-note-list">
              {notes.map((n, i) => (
                <li className="ep-note" key={i}>
                  <Avatar name={n.by} size={30} />
                  <div className="ep-note-body">
                    <div className="ep-note-meta"><b>{n.by}</b><span className="dim">{n.date}</span></div>
                    <p>{n.text}</p>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      ) : null}

      <AddEmployeeModal open={editEmp} existing={D.employees} initial={emp}
        onClose={() => setEditEmp(false)}
        onAdd={(patch) => { setEditEmp(false); onUpdate && onUpdate({ ...emp, ...patch }); notify(T("hr.recordUpdated", { name: patch.name })); }} />
      <ContractEditModal open={editContract} emp={emp} contract={contract}
        onClose={() => setEditContract(false)} onSaved={() => {
          setEditContract(false);
          onContractsChanged && onContractsChanged();
          loadHistory();
        }} />
      <ContractEditModal open={newContract} emp={emp} contract={contract} mode="new"
        onClose={() => setNewContract(false)} onSaved={() => {
          setNewContract(false);
          onContractsChanged && onContractsChanged();
          loadHistory();
        }} />
      <AttnFixModal open={!!fixDay} emp={emp} day={fixDay ? fixDay.day : null}
        onClose={() => setFixDay(null)} onSaved={() => { setFixDay(null); loadAttn(); }} />
      <DocAddModal open={addDoc} emp={emp} onClose={() => setAddDoc(false)}
        onSaved={(doc) => { setAddDoc(false); setApiDocs((ds) => [doc, ...ds]); }} />
      <WarnAddModal open={addWarn} emp={emp} onClose={() => setAddWarn(false)}
        onSaved={(w) => { setAddWarn(false); setWarnings((ws) => [w, ...ws]); }} />
    </Modal>
  );
}


window.EmployeeProfile = EmployeeProfile;
