/* ---------- Contract popup: the contract only, no employee record ----------
   Named HrContractModal, not ContractDetail: the installments module already
   owns a global ContractDetail and loads after this file. */
function HrContractModal({ row, onClose, onChanged }) {
  const { useState, useEffect } = React;
  const [editContract, setEditContract] = useState(false);
  const [newContract, setNewContract] = useState(false);
  const [past, setPast] = useState([]); // archived contracts

  const emp = row ? row.emp : null;
  const c = row ? row.c : null;

  const loadHistory = () => {
    if (!emp) return;
    API.contracts.history(emp.id).then(setPast).catch(() => setPast([]));
  };

  useEffect(() => {
    setEditContract(false); setNewContract(false); setPast([]);
    loadHistory();
  }, [emp && emp.id]);

  if (!row) return null;

  // No contract on file: there is no detail to show, so open the create form
  // directly rather than an empty shell the user has to click through.
  if (!c) {
    return (
      <ContractEditModal open={true} emp={emp} contract={null}
        onClose={onClose}
        onSaved={() => { onChanged && onChanged(); onClose(); }} />
    );
  }

  const salary = c.salary != null ? c.salary : emp.salary;
  const allowances = c.allowances || [];
  const amendments = c.amendments || [];
  const allowTotal = allowances.reduce((s, a) => s + a.amt, 0);

  return (
    <Modal open={true} onClose={onClose} title={T("hr.contract")} sub={emp.name + " · " + TV(emp.role)} width={720}
      footer={
        <div className="je-foot">
          <span className="btnrow">
            <Btn icon="edit" onClick={() => setEditContract(true)}>{T("hr.editContract")}</Btn>
            <Btn variant="primary" icon="plus" onClick={() => setNewContract(true)}>{T("hr.newContract")}</Btn>
          </span>
          <div className="btnrow"><Btn onClick={onClose}>{T("common.close")}</Btn></div>
        </div>
      }>
      <div className="ep-overview">
        <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 }) : "—"}</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">{money(salary + allowTotal)}</span><span className="ep-stat-l">{T("hr.contractPayPerMonth")}</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) + (c.probationPassed ? " · " + T("hr.passed") : " · " + T("hr.inProgress"))} />
          <KV k={T("hr.noticePeriod")} v={TV(c.notice)} />
          <KV k={T("hr.hoursPerWeek")} v={<HoursHM h={c.hours} />} mono />
          <KV k={T("hr.baseSalaryPerMonth")} v={money(salary)} mono />
          {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: c.leaveEntitlement })} />
          <KV k={T("hr.sickLeave")} v={T("hr.daysPerYear", { n: c.sickEntitlement })} />
          {c.permit ? <KV k={T("hr.workPermit")} v={T("hr.permitExpires", { no: c.permit.no, exp: c.permit.exp })} mono /> : null}
        </div>

        {past.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>
              {past.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}

        {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>
            {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>

      <ContractEditModal open={editContract} emp={emp} contract={c}
        onClose={() => setEditContract(false)} onSaved={() => {
          setEditContract(false);
          onChanged && onChanged();
          loadHistory();
        }} />
      <ContractEditModal open={newContract} emp={emp} contract={c} mode="new"
        onClose={() => setNewContract(false)} onSaved={() => {
          setNewContract(false);
          onChanged && onChanged();
          loadHistory();
        }} />
    </Modal>
  );
}

window.HrContractModal = HrContractModal;
