// Shared: the payroll period these modals act on (always the current month).
const HR_MONTHS = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"];
function periodLabel() {
  const x = String(API.fmt.period()).split("-");
  return HR_MONTHS[(+x[1] || 1) - 1] + " " + x[0];
}

// HR edit forms: contract, attendance fix, documents, request edit, payroll adjustment
function ContractEditModal({ open, emp, contract, mode, onClose, onSaved }) {
  const { useState, useEffect } = React;
  // Three modes: edit in place, replace the active contract with a new one
  // (archiving the old), and write an employee's *first* contract. The last one
  // has no `contract` to seed from, so it falls back to statutory defaults —
  // without it a new hire could never get a contract at all.
  const isFirst = !contract;
  const isNew = mode === "new" || isFirst;
  const [f, setF] = useState(null);
  useEffect(() => {
    if (!open) return;
    const today = API.fmt.prettyFull(new Date().toISOString().slice(0, 10));
    if (isFirst) {
      setF({ type: "Permanent", start: today, end: "", probation: "None", probationPassed: "In progress",
             hours: "40", notice: "30 days", salary: String(emp.salary != null ? emp.salary : 0),
             leaveEntitlement: "21", sickEntitlement: "14" });
      return;
    }
    const sal = String(contract.salary != null ? contract.salary : emp.salary);
    setF(isNew
      ? { type: "Fixed-term", start: today, end: "", probation: "None", probationPassed: "Passed",
          hours: String(contract.hours), notice: contract.notice, salary: sal,
          leaveEntitlement: String(contract.leaveEntitlement), sickEntitlement: String(contract.sickEntitlement) }
      : { type: contract.type, start: contract.start, end: contract.end || "",
          probation: contract.probation, probationPassed: contract.probationPassed ? "Passed" : "In progress",
          hours: String(contract.hours), notice: contract.notice, salary: sal,
          leaveEntitlement: String(contract.leaveEntitlement), sickEntitlement: String(contract.sickEntitlement) });
  }, [open, contract, isNew, isFirst]);
  if (!open || !f) return null;
  const set = (p) => setF((x) => ({ ...x, ...p }));
  const save = () => {
    const end = f.type === "Permanent" ? null : (f.end.trim() || null);
    let daysLeft = null;
    let endLabel = end;
    if (end) {
      // Through toIso first: the field hands back either ISO or a dd/mm/yyyy
      // label, and Date() reads the latter as month-first (or not at all).
      const iso = API.fmt.toIso(end);
      const d = iso ? new Date(iso + "T00:00:00") : new Date(NaN);
      if (!isNaN(d)) {
        daysLeft = Math.max(0, Math.round((d - new Date()) / 86400000));
        endLabel = API.fmt.prettyFull(iso);
      } else {
        daysLeft = contract ? contract.daysLeft : null;
      }
    }
    const salary = Math.round(parseFloat(f.salary)) || emp.salary;
    const payload = {
      type: f.type, start: f.start.trim(), end: end ? endLabel : null, daysLeft,
      probation: f.probation.trim(), probationPassed: f.probationPassed === "Passed",
      hours: parseInt(f.hours, 10) || 40, notice: f.notice, salary,
      leaveEntitlement: parseInt(f.leaveEntitlement, 10) || 21, sickEntitlement: parseInt(f.sickEntitlement, 10) || 14
    };
    // save first, notify onSaved after \u2014 the caller reloads from the server
    // activate_new archives the *current* contract; there is none to archive on a first contract.
    API.contracts.save(emp.id, payload, isNew && !isFirst)
      .then(() => {
        notify(isFirst ? T("hr.contractAddedFor", { name: emp.name })
             : isNew ? T("hr.contractActivatedFor", { name: emp.name })
             : T("hr.contractUpdatedFor", { name: emp.name }));
        onSaved();
      })
      .catch((ex) => notify(T("hr.contractSaveFailed", { error: ex.message })));
  };
  return (
    <Modal open={true} onClose={onClose} width={560} z={130}
      title={isFirst ? T("hr.addContract") : isNew ? T("hr.newContract") : T("hr.editContract")}
      sub={isFirst ? emp.name + " \u00b7 " + T("hr.firstContractSub") : isNew ? emp.name + " \u00b7 " + T("hr.newContractSub") : emp.name}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={save}>{isFirst ? T("hr.addContract") : isNew ? T("hr.activateContract") : T("hr.saveContract")}</Btn></div>}>
      <div className="formgrid">
        <Field label={T("hr.contractType")}>
          <SearchSelect options={["Permanent", "Fixed-term", "Part-time", "Consultant"]} value={f.type} onChange={(v) => set({ type: v })} />
        </Field>
        <Field label={T("hr.probation")}>
          <SearchSelect options={["Passed", "In progress"]} value={f.probationPassed} onChange={(v) => set({ probationPassed: v })} />
        </Field>
      </div>
      <div className="formgrid">
        {/* The API hands dates over pre-formatted ("Aug 03, 2026"), which no date
            control can display, so seed both through toIso — it passes ISO
            straight back and parses the pretty form, so an existing contract
            opens with its real date selected. */}
        <Field label={T("hr.startDate")}>
          <DateField value={API.fmt.toIso(f.start) || ""} onChange={(v) => set({ start: v })} />
        </Field>
        {/* A permanent contract has no end date to pick. Say that in the field
            rather than parking an empty picker the user can't fill. */}
        <Field label={T("hr.endDate")}>
          {f.type === "Permanent"
            ? <Input value={T("hr.openEnded")} disabled readOnly />
            : <DateField value={API.fmt.toIso(f.end) || ""} onChange={(v) => set({ end: v })} clearable />}
        </Field>
      </div>
      <div className="formgrid">
        <Field label={T("hr.salaryMonth")}><Input type="number" min="0" step="100" value={f.salary} onChange={(e) => set({ salary: e.target.value })} /></Field>
        <Field label={T("hr.hoursWeek")}><Input type="number" min="1" max="60" value={f.hours} onChange={(e) => set({ hours: e.target.value })} /></Field>
      </div>
      <div className="formgrid">
        <Field label={T("hr.noticePeriod")}>
          <SearchSelect options={["14 days", "30 days", "60 days", "90 days"]} value={f.notice} onChange={(v) => set({ notice: v })} />
        </Field>
      </div>
      <div className="formgrid">
        <Field label={T("hr.annualLeaveDaysYr")}><Input type="number" min="0" value={f.leaveEntitlement} onChange={(e) => set({ leaveEntitlement: e.target.value })} /></Field>
        <Field label={T("hr.sickLeaveDaysYr")}><Input type="number" min="0" value={f.sickEntitlement} onChange={(e) => set({ sickEntitlement: e.target.value })} /></Field>
      </div>
    </Modal>
  );
}

function AttnFixModal({ open, emp, day, onClose, onSaved }) {
  const { useState, useEffect } = React;
  const [f, setF] = useState({ in: "", out: "" });
  useEffect(() => { if (open && day) setF({ in: day.in || "", out: day.out || "" }); }, [open, day]);
  if (!open || !day) return null;
  const save = () => {
    // Seconds are optional — typing 08:00 records 08:00:00.
    const ok = (v) => /^\d{1,2}:\d{2}(:\d{2})?$/.test(v);
    if (!ok(f.in) || !ok(f.out)) { notify("Use HH:MM or HH:MM:SS format for both times"); return; }
    // Patch the punch event that exists; create one for a side that was never recorded.
    const one = (id, time, type) => (id
      ? API.timeLogs.setTime(id, time)
      : API.timeLogs.addPunch(emp.id, day.dateIso, time, type));
    Promise.all([
      day.in !== f.in || !day.inId ? one(day.inId, f.in, "check_in") : null,
      day.out !== f.out || !day.outId ? one(day.outId, f.out, "check_out") : null
    ].filter(Boolean))
      .then(() => { notify(T("hr.attendanceCorrectedFor", { day: day.day })); onSaved(); })
      .catch((ex) => notify(T("hr.correctionSaveFailed", { error: ex.message })));
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.correctAttendance")} sub={emp.name + " · " + day.day} width={400} z={130}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={save}>{T("hr.saveCorrection")}</Btn></div>}>
      <div className="formgrid">
        <Field label={T("ess.checkIn")}><Input placeholder="08:00:00" value={f.in} onChange={(e) => setF({ ...f, in: e.target.value })} /></Field>
        <Field label={T("ess.checkOut")}><Input placeholder="17:00:00" value={f.out} onChange={(e) => setF({ ...f, out: e.target.value })} /></Field>
      </div>
      <p className="formhint">{T("hr.manualCorrectionsAreFlaggedOnThe")}</p>
    </Modal>
  );
}

function DocAddModal({ open, emp, onClose, onSaved }) {
  const { useState, useEffect } = React;
  const [f, setF] = useState({ name: "", type: "Contract" });
  useEffect(() => { if (open) setF({ name: "", type: "Contract" }); }, [open]);
  if (!open) return null;
  const save = () => {
    const name = f.name.trim();
    if (!name) { notify("Enter a document name"); return; }
    API.docs.add(emp.id, { name: name, type: f.type })
      .then((doc) => { notify("“" + name + "” added to " + emp.name + "'s documents"); onSaved(doc); })
      .catch((ex) => notify("Couldn't add document — " + ex.message));
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.addDocument")} sub={emp.name} width={440} z={130}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="plus" onClick={save}>{T("hr.addDocument")}</Btn></div>}>
      <Field label={T("hr.documentName")}>
        <Input placeholder={T("hr.eGVisaRenewal2026Pdf")} value={f.name} autoFocus onChange={(e) => setF({ ...f, name: e.target.value })} />
      </Field>
      <Field label={T("common.type")}>
        <SearchSelect options={["Contract", "Identity", "Payroll", "Legal", "Review", "Other"]} value={f.type} onChange={(v) => setF({ ...f, type: v })} />
      </Field>
    </Modal>
  );
}

// Issuing a warning is a deliberate act — it gets its own popup, like every
// other "add" in the profile, not an inline row that can be typed into by accident.
function WarnAddModal({ open, emp, onClose, onSaved }) {
  const { useState, useEffect } = React;
  const [f, setF] = useState({ severity: "Notice", reason: "" });
  useEffect(() => { if (open) setF({ severity: "Notice", reason: "" }); }, [open]);
  if (!open || !emp) return null;
  const save = () => {
    const reason = f.reason.trim();
    if (!reason) { notify(T("hr.enterWarningReason")); return; }
    API.warnings.create(emp.id, f.severity, reason)
      .then((w) => { notify(T("hr.warningIssued", { name: emp.name })); onSaved(w); })
      .catch((ex) => notify(T("hr.warningSaveFailed", { error: ex.message })));
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.addWarning")} sub={emp.name} width={440} z={130}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="plus" onClick={save}>{T("hr.addWarning")}</Btn></div>}>
      <Field label={T("hr.severity")}>
        <SearchSelect options={["Notice", "Warning", "Final warning"]} value={f.severity} onChange={(v) => setF({ ...f, severity: v })} />
      </Field>
      <Field label={T("common.reason")}>
        <textarea className="input area" rows={3} placeholder={T("hr.reason")} value={f.reason} autoFocus
          onChange={(e) => setF({ ...f, reason: e.target.value })}></textarea>
      </Field>
    </Modal>
  );
}

function RequestEditModal({ open, req, onClose, onSave }) {
  const { useState, useEffect } = React;
  const [f, setF] = useState(null);
  useEffect(() => { if (open && req) setF({ type: req.type, from: req.from, to: req.to, days: String(req.days) }); }, [open, req]);
  if (!open || !f) return null;
  const save = () => {
    const d = parseInt(f.days, 10);
    if (isNaN(d) || d <= 0) { notify("Enter a valid number of days"); return; }
    onSave({ ...req, type: f.type, from: f.from.trim(), to: f.to.trim(), days: d });
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.editRequest")} sub={req.emp} width={440}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={save}>{T("common.saveChanges")}</Btn></div>}>
      <Field label={T("common.type")}>
        <SearchSelect options={["Annual", "Sick", "Unpaid", "Early leave"]} value={f.type} onChange={(v) => setF({ ...f, type: v })} />
      </Field>
      <div className="formgrid">
        <Field label={T("ess.from")}><Input value={f.from} onChange={(e) => setF({ ...f, from: e.target.value })} /></Field>
        <Field label={T("ess.to")}><Input value={f.to} onChange={(e) => setF({ ...f, to: e.target.value })} /></Field>
      </div>
      <Field label={T("ess.days")}><Input type="number" min="1" value={f.days} onChange={(e) => setF({ ...f, days: e.target.value })} /></Field>
    </Modal>
  );
}

function PayAdjustModal({ open, employees, onClose, onSave }) {
  const { useState, useEffect } = React;
  const [f, setF] = useState({ emp: "", kind: "Bonus", amount: "", note: "" });
  useEffect(() => { if (open) setF({ emp: "", kind: "Bonus", amount: "", note: "" }); }, [open]);
  if (!open) return null;
  const save = () => {
    const amt = Math.round(parseFloat(f.amount) || 0);
    if (!f.emp) { notify("Choose an employee"); return; }
    if (amt <= 0) { notify("Enter an amount above zero"); return; }
    onSave({ emp: f.emp, kind: f.kind, amount: amt, note: f.note.trim() });
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.payrollAdjustment")} sub={periodLabel() + " run"} width={440}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="plus" onClick={save}>{T("hr.addAdjustment")}</Btn></div>}>
      <Field label={T("hr.employee")}>
        <SearchSelect options={employees.map((e) => e.name)} placeholder={T("common.choose")} value={f.emp} onChange={(v) => setF({ ...f, emp: v })} />
      </Field>
      <div className="formgrid">
        <Field label={T("common.type")}>
          <SearchSelect options={["Bonus", "Overtime", "Deduction"]} value={f.kind} onChange={(v) => setF({ ...f, kind: v })} />
        </Field>
        <Field label={T("common.amount")}><Input type="number" min="0" step="50" placeholder="0" value={f.amount} onChange={(e) => setF({ ...f, amount: e.target.value })} /></Field>
      </div>
      <Field label={T("common.noteOptional")}><Input placeholder={T("hr.eGQ2SalesBonus")} value={f.note} onChange={(e) => setF({ ...f, note: e.target.value })} /></Field>
    </Modal>
  );
}
function AdvanceModal({ open, employees, onClose, onSave }) {
  const { useState, useEffect } = React;
  const [f, setF] = useState({ emp: "", amount: "", monthly: "", note: "" });
  useEffect(() => { if (open) setF({ emp: "", amount: "", monthly: "", note: "" }); }, [open]);
  if (!open) return null;
  const save = () => {
    const amt = Math.round(parseFloat(f.amount) || 0);
    const mon = Math.round(parseFloat(f.monthly) || 0);
    if (!f.emp) { notify("Choose an employee"); return; }
    if (amt <= 0) { notify("Enter an advance amount above zero"); return; }
    if (mon <= 0 || mon > amt) { notify("Monthly repayment must be between 1 and the advance amount"); return; }
    onSave({ emp: f.emp, amount: amt, monthly: mon, note: f.note.trim() });
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.newSalaryAdvance")} sub={T("hr.deductedFromMonthlyPayUntilSettled")} width={460}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="plus" onClick={save}>{T("hr.issueAdvance")}</Btn></div>}>
      <Field label={T("hr.employee")}>
        <SearchSelect options={employees.map((e) => e.name)} placeholder={T("common.choose")} value={f.emp} onChange={(v) => setF({ ...f, emp: v })} />
      </Field>
      <div className="formgrid">
        <Field label={T("hr.advanceAmount")}><Input type="number" min="0" step="100" placeholder="0" value={f.amount} onChange={(e) => setF({ ...f, amount: e.target.value })} /></Field>
        <Field label={T("hr.monthlyRepayment")}><Input type="number" min="0" step="50" placeholder="0" value={f.monthly} onChange={(e) => setF({ ...f, monthly: e.target.value })} /></Field>
      </div>
      <Field label={T("common.noteOptional")}><Input placeholder={T("hr.eGRelocationSupport")} value={f.note} onChange={(e) => setF({ ...f, note: e.target.value })} /></Field>
      {f.amount && f.monthly && parseFloat(f.monthly) > 0 ? (
        <p className="formhint">Settled in {Math.ceil((parseFloat(f.amount) || 0) / (parseFloat(f.monthly) || 1))} monthly repayments.</p>
      ) : null}
    </Modal>
  );
}

function RepayModal({ open, advance, onClose, onSave }) {
  const { useState, useEffect } = React;
  const [amt, setAmt] = useState("");
  useEffect(() => { if (open && advance) setAmt(String(Math.min(advance.monthly, advance.amount - advance.repaid))); }, [open, advance]);
  if (!open || !advance) return null;
  const balance = advance.amount - advance.repaid;
  const save = () => {
    const a = Math.round(parseFloat(amt) || 0);
    if (a <= 0 || a > balance) { notify("Enter an amount between 1 and " + money(balance)); return; }
    onSave(a);
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.recordRepayment")} sub={advance.emp + " · " + refNo(advance.id) + " · balance " + money(balance)} width={400}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={save}>{T("hr.recordRepayment")}</Btn></div>}>
      <Field label={T("hr.repaymentAmount")}>
        <Input type="number" min="1" max={balance} value={amt} onChange={(e) => setAmt(e.target.value)} autoFocus />
      </Field>
    </Modal>
  );
}
function PayEditModal({ open, emp, status, paidOn, onClose, onSave }) {
  const { useState, useEffect } = React;
  const [sal, setSal] = useState("");
  const [st, setSt] = useState("Pending");
  const [date, setDate] = useState("");
  useEffect(() => {
    if (open && emp) { setSal(String(emp.salary)); setSt(status || "Pending"); setDate(paidOn || ""); }
  }, [open, emp]);
  if (!open || !emp) return null;
  const save = () => {
    const s = Math.round(parseFloat(sal) || 0);
    if (s <= 0) { notify("Enter a base salary above zero"); return; }
    onSave({ salary: s, status: st, paidOn: paidOn || null });
  };
  const MONTH_FULL = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  const per = String(API.fmt.period()).split("-");
  return (
    <Modal open={true} onClose={onClose} title={T("hr.editPayRecord")}
      sub={emp.name + " · " + MONTH_FULL[(+per[1] || 1) - 1] + " " + per[0]} width={480} z={130}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={save}>{T("common.saveChanges")}</Btn></div>}>
      <div className="formgrid">
        <Field label={T("hr.baseSalaryMonth")}><Input type="number" min="0" step="100" value={sal} onChange={(e) => setSal(e.target.value)} /></Field>
      </div>
      <p className="formhint">{T("hr.statusAndPaidOnAreComputed")}</p>
      <p className="formhint">{T("hr.bonusesDeductionsAreManaged")}</p>
    </Modal>
  );
}

// Pay adjustments only. Disciplinary warnings are part of the personnel record,
// not the payroll run — they live in the employee profile.
function EmpAdjustModal({ open, emp, adjustments, onClose, onSave }) {
  const { useState, useEffect } = React;
  const [adjs, setAdjs] = useState([]);
  const [na, setNa] = useState({ kind: "Bonus", amount: "", note: "" });
  useEffect(() => {
    if (open && emp) {
      setAdjs(adjustments.filter((a) => a.empId === emp.id));
      setNa({ kind: "Bonus", amount: "", note: "" });
    }
  }, [open, emp]);
  if (!open || !emp) return null;
  const addAdj = () => {
    const amt = Math.round(parseFloat(na.amount) || 0);
    if (amt <= 0) { notify("Enter an amount above zero"); return; }
    setAdjs((xs) => [...xs, { emp: emp.name, kind: na.kind, amount: amt, note: na.note.trim() }]);
    setNa({ kind: "Bonus", amount: "", note: "" });
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.bonusesDeductions")} sub={emp.name + " · " + periodLabel()} width={620} z={130}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={() => onSave({ adjs })}>{T("common.saveChanges")}</Btn></div>}>

      <div className="field">
        <span className="field-label">{T("hr.bonusesDeductions")}</span>
        {adjs.length === 0 ? <p className="dim" style={{ margin: "6px 0 8px", fontSize: 13 }}>{T("hr.noneThisRun")}</p> : (
          <div className="ep-list" style={{ margin: "6px 0 8px" }}>
            {adjs.map((a, i) => (
              <div className="ep-row pe-adj-row" key={i}>
                <span><b>{a.kind}</b></span>
                <span className="dim">{a.note || "—"}</span>
                <span className="ta-r mono strong" style={{ color: a.kind === "Deduction" ? "var(--red)" : "var(--green)" }}>{a.kind === "Deduction" ? "−" : "+"}{money(a.amount)}</span>
                <button type="button" className="inv-del" onClick={() => setAdjs((xs) => xs.filter((_, j) => j !== i))} title={T("common.remove")}><Icon name="trash" size={14} /></button>
              </div>
            ))}
          </div>
        )}
        <div className="pe-add-labels"><span>{T("common.type")}</span><span>{T("common.amount")}</span><span>{T("hr.note")}</span><span></span></div>
        <div className="pe-add">
          <Select options={["Bonus", "Overtime", "Deduction"]} value={na.kind} onChange={(e) => setNa({ ...na, kind: e.target.value })} />
          <Input type="number" min="0" step="50" placeholder={T("common.amount")} value={na.amount} onChange={(e) => setNa({ ...na, amount: e.target.value })} />
          <Input placeholder={T("common.noteOptional")} value={na.note} onChange={(e) => setNa({ ...na, note: e.target.value })} />
          <Btn small icon="plus" onClick={addAdj}>{T("common.add")}</Btn>
        </div>
      </div>
    </Modal>
  );
}
function DecideModal({ open, info, onClose, onConfirm }) {
  const { useState, useEffect } = React;
  const [note, setNote] = useState("");
  useEffect(() => { if (open) setNote(""); }, [open]);
  if (!open || !info) return null;
  const l = info.leave;
  const approve = info.action === "Approved";
  // api.js renders from/to in English. Format from the ISO dates it carries
  // alongside them so the summary follows the active language.
  const day = (iso, fallback) => {
    const d = iso ? new Date(iso + "T00:00:00") : null;
    return d && !isNaN(d) ? d.toLocaleDateString(uiLocale(), { month: "short", day: "2-digit" }) : fallback;
  };
  const sub = [l.emp, TV(l.type), day(l.fromIso, l.from) + " → " + day(l.toIso, l.to)]
    .concat(l.days ? [TP("hr.daysCount", l.days)] : []).join(" · ");
  return (
    <Modal open={true} onClose={onClose} width={440}
      title={approve ? T("hr.approveRequest") : T("hr.declineRequest")}
      sub={sub}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={() => onConfirm(note.trim())}>{approve ? T("hr.approve") : T("hr.decline")}</Btn></div>}>
      <Field label={T("hr.noteToPerson", { name: l.emp.split(" ")[0] })}>
        <textarea className="input area" rows={3} placeholder={approve ? T("hr.approveNoteEg") : T("hr.declineNoteEg")}
          value={note} onChange={(e) => setNote(e.target.value)}></textarea>
      </Field>
    </Modal>
  );
}
function RecordPayModal({ open, emp, remaining, onClose, onSave }) {
  const { useState, useEffect } = React;
  const [f, setF] = useState({ amount: "", method: "Bank transfer" });
  useEffect(() => { if (open) setF({ amount: String(remaining || ""), method: "Bank transfer" }); }, [open, remaining]);
  if (!open || !emp) return null;
  const save = () => {
    const a = Math.round(parseFloat(f.amount) || 0);
    if (a <= 0 || a > remaining) { notify("Enter an amount between 1 and " + money(remaining)); return; }
    onSave({ amount: a, method: f.method });
  };
  return (
    <Modal open={true} onClose={onClose} title={T("hr.recordSalaryPayment")} sub={emp.name + " · " + periodLabel() + " · " + money(remaining) + " outstanding"} width={420} z={130}
      footer={<div className="btnrow"><Btn onClick={onClose}>{T("common.cancel")}</Btn><Btn variant="primary" icon="check" onClick={save}>{T("hr.recordPayment")}</Btn></div>}>
      <div className="formgrid">
        <Field label={T("common.amount")}><Input type="number" min="1" max={remaining} value={f.amount} onChange={(e) => setF({ ...f, amount: e.target.value })} autoFocus /></Field>
        <Field label={T("inst.method")}>
          <Select options={["Bank transfer", "Cash", "Cheque"]} value={f.method} onChange={(e) => setF({ ...f, method: e.target.value })} />
        </Field>
      </div>
    </Modal>
  );
}
Object.assign(window, { ContractEditModal, AttnFixModal, DocAddModal, WarnAddModal, RequestEditModal, PayAdjustModal, AdvanceModal, RepayModal, PayEditModal, EmpAdjustModal, DecideModal, RecordPayModal });
