/* ============================================================
   바른셈 — 급여 계산 결과 분해 뷰 (통상임금 → 가산 → 공제 → 실지급)
   ============================================================ */
function Calc({ ctx }) {
  const { clients, statusOf, go, t, period } = ctx;
  const client = clients.find((c) => c.id === (ctx.params.clientId || clients[0].id)) || clients[0];
  const st = statusOf(client.id);
  const rs = ctx.rulesetFor(client.id);            // 스냅샷(동결) 또는 현재 유효 룰셋
  const snap = ctx.snapOf(client.id) || ctx.appliedRuleset();
  const recalc = ctx.recalcNeeded(client.id);
  const ovr = ctx.gov.overrides;
  const idx = window.BARUNSEM.FLOW.findIndex((f) => f.key === st);
  const previewMode = idx < 4; // 아직 계산 전(draft~locked) — 하드 차단 대신 미리보기

  const rsKey = JSON.stringify([rs.npRate, rs.npHigh, rs.npLow, rs.hiRate, rs.ltcRate, rs.eiRate, rs.workHours, rs.roundPolicy, rs.otSur, rs.ntSur, rs.holInSur, rs.holOverSur]);
  // 화면은 단일 진입점 runFor만 호출한다 (runPayroll/runNet 직접 호출 금지 — W0-1)
  const runs = useMemo(() => client.employees.map((e) => {
    const run = window.BARUNSEM.runFor(e, client, period.ym, rs);
    return { e, run, netSteps: run.netSteps, netTarget: run.netTarget };
  }), [client.id, period.ym, rsKey]);
  const [selId, setSelId] = useState(runs[0].e.id);
  useEffect(() => { setSelId(client.employees[0].id); }, [client.id]);
  const sel = runs.find((r) => r.e.id === selId) || runs[0];

  const cTot = runs.reduce((a, r) => ({ gross: a.gross + r.run.gross, ded: a.ded + r.run.deductTotal, net: a.net + r.run.net }), { gross: 0, ded: 0, net: 0 });


  const { e, run } = sel;
  const maxGross = Math.max(...runs.map((r) => r.run.gross));

  return (
    <div className="page page-wide rise">
      {previewMode && (
        <div className="card card-pad" style={{ display: "flex", alignItems: "center", gap: 13, marginBottom: 16, background: "var(--accent-soft)", border: "1px solid var(--accent-line)" }}>
          <Ms name="visibility" style={{ color: "var(--accent)", fontSize: 22, flex: "none" }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 650, fontSize: 13.5, color: "var(--accent-ink)" }}>{st === "locked" ? "계산 실행 전 미리보기" : "검수·잠금 전 미리보기"}</div>
            <div style={{ fontSize: 12.5, color: "var(--accent-ink)", opacity: .85, marginTop: 2, lineHeight: 1.5 }}>
              현재 입력·유효 룰셋 기준 <b>추정치</b>입니다 — 확정값 아님. {st === "locked" ? "입력은 잠겼고, 계산을 실행하면 이 시점 룰셋으로 스냅샷이 박제됩니다." : "변동분 검수·잠금이 끝나야 확정 계산됩니다. 입력이 바뀌면 수치도 바뀝니다."}
            </div>
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => go("review", { clientId: client.id })}>
            <Ms name={st === "locked" ? "calculate" : "fact_check"} />{st === "locked" ? "검수 화면에서 계산 실행" : "변동분 검수로"}
          </button>
        </div>
      )}
      <div className="page-head" style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
        <span className="tag tag-accent" style={{ height: 26 }} title={previewMode ? "아직 동결되지 않은 현재 유효 룰셋 — 계산 실행 시 스냅샷으로 박제됩니다" : "산정 시점 룰셋 버전 스냅샷 — 이 요율로 결정성 있게 재현됩니다"}>
          <Ms name={previewMode ? "visibility" : "lock"} style={{ fontSize: 14 }} />{previewMode ? "현재 유효 룰셋" : "룰셋 스냅샷"} {snap.firmId} · 표준 {snap.stdId}
          {(() => { const h = ctx.snapHistoryOf ? ctx.snapHistoryOf(client.id) : []; return h.length > 1
            ? <span className="muted" style={{ fontSize: 10.5, marginLeft: 6 }} title={h.map((x) => `${x.at} · ${x.stdId} · ${x.actor}`).join("\n")}>스냅샷 {h.length}회 (이력 보존)</span> : null; })()}
        </span>
        {snap.stdId && <span className="tag" style={{ height: 26 }} title="이 버전으로 실제 계산됨">국민연금 {window.BARUNSEM.pctLabel(rs.npRate)} 적용</span>}
        {ovr["단수처리"] && <span className="tag tag-accent" style={{ height: 26 }} title={ovr["단수처리"].note}><Ms name="tune" style={{ fontSize: 12 }} />법인 정책 · 단수처리</span>}
        {recalc && (
          <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--warn-soft)", border: "1px solid var(--warn-line)", borderRadius: 8, padding: "4px 10px" }}>
            <Ms name="sync_problem" style={{ fontSize: 16, color: "color-mix(in oklab, var(--warn) 70%, black)" }} />
            <span style={{ fontSize: 11.5, fontWeight: 600, color: "color-mix(in oklab, var(--warn) 58%, black)" }}>룰셋이 변경됨 — 재계산 권장</span>
            <button className="btn btn-primary btn-sm" style={{ height: 24 }} onClick={() => ctx.recompute(client.id)}><Ms name="refresh" style={{ fontSize: 14 }} />재계산</button>
          </div>
        )}
        {!recalc && ["confirmed", "distributed"].includes(st) && (() => {
          const ar = ctx.appliedRuleset(snap.ym || period.ym);
          const stale = snap.ovr && (snap.stdId !== ar.stdId || JSON.stringify(snap.ovr || {}) !== JSON.stringify(ovr));
          if (!stale) return null;
          return (
            <div style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface-2)", border: "1px solid var(--line-2)", borderRadius: 8, padding: "4px 10px" }}>
              <Ms name="ac_unit" style={{ fontSize: 16, color: "var(--ink-3)" }} />
              <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--ink-2)" }}>확정 동결 — 당시 버전 유지 (룰셋 변경 미반영)</span>
              <button className="btn btn-default btn-sm" style={{ height: 24 }} onClick={() => ctx.unlockForRecalc(client.id, "룰셋 변경 반영 — 확정 동결 해제")}><Ms name="lock_open" style={{ fontSize: 14 }} />해제 후 재계산</button>
            </div>
          );
        })()}
      </div>

      {/* 고객사 합계 */}
      <div className="kpi-grid kpi-3" style={{ marginBottom: 18 }}>
        <div className="kpi"><div className="kpi-label"><Ms name="add_circle" />총지급액</div><div className="kpi-val num">{KRW(cTot.gross)}<small> 원</small></div></div>
        <div className="kpi"><div className="kpi-label"><Ms name="remove_circle" style={{ color: "var(--danger)" }} />공제 합계</div><div className="kpi-val num" style={{ color: "var(--danger)" }}>{KRW(cTot.ded)}<small> 원</small></div></div>
        <div className="kpi" style={{ background: "var(--accent-soft)", borderColor: "var(--accent-line)" }}><div className="kpi-label" style={{ color: "var(--accent-ink)" }}><Ms name="account_balance_wallet" style={{ color: "var(--accent)" }} />실지급 합계</div><div className="kpi-val num" style={{ color: "var(--accent-ink)" }}>{KRW(cTot.net)}<small> 원</small></div></div>
      </div>

      <div className="l-master" style={{ "--master": "264px" }}>
        {/* 근로자 리스트 */}
        <div className="card">
          <CardHead icon="groups" title="근로자" sub={`${runs.length}명`} />
          <div className="pick-list" style={{ maxHeight: 620, overflowY: "auto" }}>
            {runs.map(({ e, run }) => (
              <button key={e.id} onClick={() => setSelId(e.id)} style={{
                display: "flex", alignItems: "center", gap: 11, padding: "12px 16px", width: "100%", textAlign: "left", border: "none",
                borderBottom: "1px solid var(--line)", background: e.id === selId ? "var(--accent-soft)" : "transparent", cursor: "pointer",
                borderLeft: e.id === selId ? "3px solid var(--accent)" : "3px solid transparent",
              }}>
                <div className="avatar" style={{ width: 32, height: 32, fontSize: 12, background: "var(--bg-sunken)", color: "var(--ink-2)" }}>{e.name[0]}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 650, fontSize: 13.5 }}>{e.name}</div>
                  <div className="muted" style={{ fontSize: 11.5 }}>{e.scheme} · {e.dept}</div>
                </div>
                <div style={{ textAlign: "right" }}><div className="num" style={{ fontWeight: 700, fontSize: 13 }}>{KRW(run.net)}</div><div className="muted num" style={{ fontSize: 10.5 }}>실지급</div></div>
              </button>
            ))}
          </div>
        </div>

        {/* 분해 */}
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          {/* 급여체계 확장 데모 (네트제 / 포괄임금제) */}
          {e.experimental && <SchemeDemo entry={sel} />}
          {/* 통상임금 산정 */}
          <div className="card card-pad" style={{ background: "linear-gradient(180deg, var(--accent-soft), var(--surface))" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
              <Ms name="schema" style={{ color: "var(--accent)", fontSize: 20 }} />
              <h3 style={{ fontSize: 14.5, fontWeight: 700 }}>① 통상임금 산정</h3>
              <span className="muted" style={{ fontSize: 12 }}>계약(포함여부) + 법규(산정방법)</span>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
              <CalcChip label="통상임금 월액" value={KRW(run.commonWageMonthly) + "원"} note={"기본급 + 통상수당"} />
              <Ms name="east" style={{ color: "var(--ink-4)" }} />
              <CalcChip label="÷ 월 소정근로" value={rs.workHours + "h"} note={"표준 " + snap.stdId} />
              <Ms name="east" style={{ color: "var(--ink-4)" }} />
              <CalcChip label="통상시급" value={KRW(run.ordinaryHourly) + "원"} accent note="가산수당 base" />
            </div>
            <div style={{ marginTop: 14, display: "flex", gap: 8, flexWrap: "wrap" }}>
              <span className="muted" style={{ fontSize: 12, alignSelf: "center" }}>포함 항목:</span>
              <span className="tag tag-accent">기본급</span>
              {e.allowances.filter((a) => a.common).map((a) => <span key={a.name} className="tag tag-accent">{a.name}</span>)}
              {e.allowances.filter((a) => !a.common).map((a) => <span key={a.name} className="tag" style={{ opacity: .7 }}>{a.name} <span style={{ textDecoration: "line-through" }}>제외</span></span>)}
              {!e.fiveOrMore && <span className="tag tag-warn"><Ms name="info" style={{ fontSize: 12 }} />5인 미만 — 가산 적용 제외</span>}
            </div>
          </div>

          {/* 지급/공제 분해 */}
          <div className="card">
            <CardHead icon="account_tree" title="② 지급·공제 분해" sub={`${e.name} · ${e.title}`}
              right={
                <div className="seg">
                  <button className={t.calcLayout === "waterfall" ? "on" : ""} onClick={() => ctx.setTweak("calcLayout", "waterfall")}>워터폴</button>
                  <button className={t.calcLayout === "table" ? "on" : ""} onClick={() => ctx.setTweak("calcLayout", "table")}>표</button>
                </div>
              } />
            <div className="card-pad">
              {t.calcLayout === "waterfall"
                ? <Waterfall run={run} maxVal={Math.max(maxGross, run.gross)} />
                : <PayTable run={run} />}
            </div>
          </div>
        </div>
      </div>

      {/* 다음 단계 안내 — 계산 탭이 막다른 길이 되지 않도록 (확정 액션은 급여대장·명세서 탭에 있다) */}
      {(st === "calculated" || st === "pending_approval") && (
        <div className="card card-pad action-bar" style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 18, position: "sticky", bottom: 16, boxShadow: "var(--sh-2)" }}>
          <Ms name={st === "calculated" ? "rule" : "hourglass_top"} style={{ color: st === "calculated" ? "var(--teal)" : "var(--warn)", fontSize: 26 }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 650 }}>{st === "calculated" ? "계산 완료 — 결과를 검토했으면 확정 단계로" : "승인 대기 중 — 팀장·대표 승인 필요"}</div>
            <div className="muted" style={{ fontSize: 12.5 }}>확정·승인 상신·명세서 발송은 <b>급여대장·명세서</b> 탭에서 진행합니다.</div>
          </div>
          <button className="btn btn-primary btn-lg" onClick={() => go("documents", { clientId: client.id })}>
            <Ms name="description" />급여대장·명세서로
          </button>
        </div>
      )}
    </div>
  );
}

function BackBar({ go }) {
  return <button className="btn-ghost btn btn-sm" style={{ padding: "0 8px", marginBottom: 10, marginLeft: -8 }} onClick={() => go("dashboard")}><Ms name="arrow_back" />대시보드</button>;
}

function CalcChip({ label, value, note, accent }) {
  return (
    <div style={{ background: accent ? "var(--accent)" : "var(--surface)", color: accent ? "#fff" : "var(--ink)", border: accent ? "none" : "1px solid var(--line-2)", borderRadius: 11, padding: "10px 16px", boxShadow: "var(--sh-1)" }}>
      <div style={{ fontSize: 11.5, opacity: accent ? .85 : 1, color: accent ? "#fff" : "var(--ink-3)", fontWeight: 600 }}>{label}</div>
      <div className="num" style={{ fontSize: 20, fontWeight: 750, letterSpacing: "-0.02em", marginTop: 2 }}>{value}</div>
      {note && <div style={{ fontSize: 10.5, opacity: .75, marginTop: 1 }}>{note}</div>}
    </div>
  );
}

/* 워터폴 */
function Waterfall({ run, maxVal }) {
  const pct = (v) => Math.max(2, (Math.abs(v) / maxVal) * 100);
  const earnPos = run.earnings.filter((x) => x.amount >= 0);
  return (
    <div className="wf">
      <SectionLabel icon="add" text="지급 항목" color="var(--accent)" />
      {run.earnings.map((x) => (
        <div className="wf-row" key={x.key}>
          <div className="wf-name">{x.name}
            {x.common && <span className="tag tag-accent" style={{ height: 17, fontSize: 10, padding: "0 5px" }}>통상</span>}
            {x.nonTax && <span className="tag tag-ok" style={{ height: 17, fontSize: 10, padding: "0 5px" }}>비과세</span>}
            {x.premium && <span className="tag tag-warn" style={{ height: 17, fontSize: 10, padding: "0 5px" }}>가산</span>}
          </div>
          <div className="wf-bar-track"><div className={"wf-bar " + (x.minus ? "wf-ded" : x.premium ? "wf-add" : "wf-base")} style={{ width: pct(x.amount) + "%", opacity: x.minus ? .7 : 1 }} /></div>
          <div className={"wf-amt" + (x.minus ? " minus" : "")}>{x.amount < 0 ? "−" : ""}{KRW(Math.abs(x.amount))}</div>
        </div>
      ))}
      <div className="wf-row wf-total">
        <div className="wf-name" style={{ fontWeight: 700, color: "var(--ink)" }}>총지급액</div>
        <div className="wf-bar-track" />
        <div className="wf-amt" style={{ fontSize: 16 }}>{KRW(run.gross)}</div>
      </div>
      <div style={{ display: "flex", gap: 10, margin: "12px 0 4px", fontSize: 12 }}>
        <span className="tag tag-ok">비과세 {KRW(run.nonTax)}</span>
        <span className="tag">과세 대상 {KRW(run.taxable)}</span>
      </div>

      <SectionLabel icon="remove" text="공제 항목" color="var(--danger)" />
      {run.deductions.map((x) => (
        <div className="wf-row" key={x.key}>
          <div className="wf-name">{x.name} <span className="muted" style={{ fontSize: 11 }}>{x.rate}</span></div>
          <div className="wf-bar-track"><div className="wf-bar wf-ded" style={{ width: pct(x.amount) + "%" }} /></div>
          <div className="wf-amt minus">−{KRW(x.amount)}</div>
        </div>
      ))}
      <div className="wf-row wf-total">
        <div className="wf-name" style={{ fontWeight: 700, color: "var(--ink)" }}>공제 합계</div>
        <div className="wf-bar-track" />
        <div className="wf-amt minus" style={{ fontSize: 16 }}>−{KRW(run.deductTotal)}</div>
      </div>

      <div style={{ marginTop: 16, padding: "16px 20px", background: "var(--accent)", borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "space-between", color: "#fff", boxShadow: "var(--sh-2)" }}>
        <div><div style={{ fontSize: 12.5, opacity: .85 }}>실지급액 = 총지급 − 공제</div><div style={{ fontSize: 12, opacity: .7, marginTop: 1 }}>{window.BARUNSEM.PERIOD.payDate} 지급 예정</div></div>
        <div className="num" style={{ fontSize: 28, fontWeight: 800, letterSpacing: "-0.03em" }}>{KRW(run.net)}원</div>
      </div>
    </div>
  );
}

function SectionLabel({ icon, text, color }) {
  return <div style={{ display: "flex", alignItems: "center", gap: 6, margin: "8px 0 2px", fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em", color }}><Ms name={icon} style={{ fontSize: 16 }} />{text}</div>;
}

/* 표 레이아웃 (급여명세서 형식) — 양 열 셀 높이 정렬 보장 */
function PayTable({ run }) {
  const rows = Math.max(run.earnings.length, run.deductions.length);
  const RH = 38;
  const headSt = { display: "flex", alignItems: "center", height: 40, padding: "0 16px", fontWeight: 700, fontSize: 13 };
  const cellSt = { display: "flex", alignItems: "center", justifyContent: "space-between", height: RH, padding: "0 16px", borderTop: "1px solid var(--line)", fontSize: 13 };
  const fillSt = { height: RH, borderTop: "1px solid var(--line)" };
  const totSt = { display: "flex", alignItems: "center", justifyContent: "space-between", height: 44, padding: "0 16px", borderTop: "2px solid var(--line-2)", background: "var(--surface-2)", fontWeight: 700 };
  const col = ({ title, items, headBg, headColor, totalLabel, totalVal, right }) => (
    <div style={right ? null : { borderRight: "1px solid var(--line)" }}>
      <div style={{ ...headSt, background: headBg, color: headColor }}>{title}</div>
      {items.map((x) => (
        <div key={x.key} style={cellSt}>
          <span style={{ color: "var(--ink-2)" }}>{x.name}</span>
          <span className="num" style={{ fontWeight: 600, color: x.minus ? "var(--danger)" : "inherit" }}>{x.minus ? "−" : ""}{KRW(Math.abs(x.amount))}</span>
        </div>
      ))}
      {Array.from({ length: rows - items.length }).map((_, i) => <div key={i} style={fillSt} />)}
      <div style={totSt}><span>{totalLabel}</span><span className="num">{KRW(totalVal)}</span></div>
    </div>
  );
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", border: "1px solid var(--line)", borderRadius: 10, overflow: "hidden" }}>
      {col({ title: "지급 항목", items: run.earnings, headBg: "var(--accent-soft)", headColor: "var(--accent-ink)", totalLabel: "총지급", totalVal: run.gross })}
      {col({ title: "공제 항목", items: run.deductions, headBg: "var(--danger-soft)", headColor: "var(--danger)", totalLabel: "공제 합계", totalVal: run.deductTotal, right: true })}
      <div style={{ gridColumn: "1 / 3", display: "flex", justifyContent: "space-between", alignItems: "center", padding: "14px 18px", background: "var(--accent)", color: "#fff" }}>
        <span style={{ fontWeight: 700 }}>실지급액</span><span className="num" style={{ fontSize: 22, fontWeight: 800 }}>{KRW(run.net)}원</span>
      </div>
    </div>
  );
}

/* 급여체계 확장 데모 — 네트제(그로스업) / 포괄임금제 */
function SchemeDemo({ entry }) {
  const { e, run, netSteps, netTarget } = entry;
  const isNet = e.scheme === "네트제";
  return (
    <div className="card" style={{ borderColor: "var(--warn-line)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 22px", borderBottom: "1px solid var(--line)", background: "var(--warn-soft)" }}>
        <Ms name="science" style={{ color: "color-mix(in oklab, var(--warn) 70%, black)", fontSize: 20 }} />
        <h3 style={{ fontSize: 14.5, fontWeight: 700, color: "color-mix(in oklab, var(--warn) 55%, black)" }}>
          {isNet ? "네트제 — 실지급 고정·세전 그로스업 역산" : "포괄임금제 — 고정 시간외수당 포함"}
        </h3>
        <span className="pill pill-warn" style={{ marginLeft: "auto" }}><Ms name="bolt" style={{ fontSize: 13 }} />실험 · 후순위</span>
      </div>

      {isNet ? (
        <div className="card-pad">
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 16 }}>
            <CalcChip label="보장 실지급액 (고정)" value={KRW(netTarget) + "원"} />
            <Ms name="sync" style={{ color: "var(--ink-4)", alignSelf: "center" }} />
            <CalcChip label="역산 세전 (그로스업)" value={KRW(run.gross) + "원"} accent note={`공제 ${KRW(run.deductTotal)}원 부담`} />
          </div>
          <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-3)", letterSpacing: ".03em", marginBottom: 8 }}>
            <Ms name="repeat" style={{ fontSize: 14, verticalAlign: "-3px" }} /> 4대보험·세금 반복계산 수렴 과정
          </div>
          <table className="tbl tbl-cards" style={{ fontSize: 12.5 }}>
            <thead><tr><th style={{ width: 56 }}>회차</th><th className="r">세전(가정)</th><th className="r">공제 합계</th><th className="r">실지급</th><th className="r">목표와의 차이</th></tr></thead>
            <tbody>
              {netSteps.map((s, i) => {
                const done = Math.abs(s.diff) <= 10;
                return (
                  <tr key={i}>
                    <td className="tc-name"><span className="kbd num">#{s.iter}</span></td>
                    <td className="r num" data-label="세전(가정)">{KRW(s.gross)}</td>
                    <td className="r num" data-label="공제 합계" style={{ color: "var(--danger)" }}>−{KRW(s.deduct)}</td>
                    <td className="r num" data-label="실지급" style={{ fontWeight: 650 }}>{KRW(s.net)}</td>
                    <td className="r num" data-label="목표와의 차이">{done
                      ? <span className="pill pill-ok" style={{ height: 20 }}><Ms name="check" style={{ fontSize: 12 }} />수렴</span>
                      : <span style={{ color: s.diff > 0 ? "var(--warn)" : "var(--teal)", fontWeight: 650 }}>{s.diff > 0 ? "+" : "−"}{KRW(Math.abs(s.diff))}</span>}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div className="muted" style={{ fontSize: 11.5, marginTop: 12, lineHeight: 1.6 }}>
            실지급액을 고정하면 세전 금액이 미지수가 됩니다. 4대보험·소득세는 세전 기준으로 부과되므로 <b>반복 대입으로 역산</b>합니다. 회사가 공제분까지 부담하는 구조 — 정확한 비용 추정을 위해 결정성 있는 수렴 계산이 필요합니다.
          </div>
        </div>
      ) : (
        <div className="card-pad">
          {(() => {
            const fix = e.allowances.find((a) => a.fixedHours);
            // 약정액이 법정 연장수당에 미달하면 그 부분은 무효 — 차액 지급 의무가 남는다(커널 FIXED_OT_SHORT와 같은 식).
            const legal = fix ? Math.round(run.ordinaryHourly * 1.5 * fix.fixedHours) : 0;
            const short = fix ? Math.max(0, legal - fix.amount) : 0;
            return (
              <>
                <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: 14 }}>
                  <CalcChip label="기본급" value={KRW(e.base) + "원"} />
                  <Ms name="add" style={{ color: "var(--ink-4)", alignSelf: "center" }} />
                  <CalcChip label="고정 시간외수당" value={fix ? KRW(fix.amount) + "원" : "—"} accent note={fix ? `약정 ${fix.fixedHours}h 정액 포함` : ""} />
                  {fix && <><Ms name="balance" style={{ color: "var(--ink-4)", alignSelf: "center" }} />
                    <CalcChip label="법정 하한 (통상시급×1.5×약정h)" value={KRW(legal) + "원"} note={short ? `미달 ${KRW(short)}원 — 별도 지급 의무` : "약정액이 하한 이상"} /></>}
                </div>
                <div className="grid-2">
                  <div style={{ padding: "12px 14px", background: short ? "var(--danger-soft)" : "var(--surface-2)", borderRadius: 10, border: "1px solid " + (short ? "var(--danger-line)" : "var(--line)") }}>
                    <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 4, color: short ? "var(--danger)" : "inherit" }}>
                      <Ms name={short ? "error" : "check_circle"} style={{ fontSize: 15, color: short ? "var(--danger)" : "var(--ok)", verticalAlign: "-3px" }} /> {short ? "약정액이 법정 하한에 미달" : "약정 범위 내"}
                    </div>
                    <div className="muted" style={{ fontSize: 12, lineHeight: 1.5 }}>
                      {short ? <>약정 {fix.fixedHours}h의 법정 연장수당은 <b>{KRW(legal)}원</b>인데 약정액은 {KRW(fix.amount)}원 — <b>차액 {KRW(short)}원</b>은 포괄 약정으로 배제되지 않고 지급 의무가 남습니다.</>
                             : "고정 시간외 한도까지는 실제 연장근로와 무관하게 정액 지급 — 매월 동일."}
                    </div>
                  </div>
                  <div style={{ padding: "12px 14px", background: "var(--warn-soft)", borderRadius: 10, border: "1px solid var(--warn-line)" }}>
                    <div style={{ fontSize: 12, fontWeight: 700, marginBottom: 4, color: "color-mix(in oklab, var(--warn) 55%, black)" }}><Ms name="warning" style={{ fontSize: 15, verticalAlign: "-3px" }} /> 약정 초과분</div>
                    <div style={{ fontSize: 12, lineHeight: 1.5, color: "color-mix(in oklab, var(--warn) 50%, black)" }}>한도를 넘는 실근로는 통상시급 기준으로 <b>별도 추가 정산</b>해야 함 (포괄 약정으로 배제 불가).</div>
                  </div>
                </div>
                <div className="muted" style={{ fontSize: 11.5, marginTop: 12, lineHeight: 1.6 }}>
                  포괄임금제는 고정 시간외수당을 임금에 포함하되, <b>약정 시간을 초과한 실근로</b>와 <b>법정 하한 미달분</b>은 추가 지급 의무가 남습니다.
                </div>
              </>
            );
          })()}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Calc, BackBar });
