/* ============================================================
   resolution.jsx — right pane: totals, breakdown, draft, actions
   ============================================================ */

function MoneyCountUp({ target, run, className }) {
  const v = useCountUp(target, run, 950);
  return <span className={className}>{window.RECON.fmtMoney(v)}</span>;
}

/* clean-match resolution */
function CleanResolution({ inv, resolved, onClear }) {
  const fmt = window.RECON.fmtMoney;
  return (
    <div className="res-wrap fade-in">
      <div className="totals">
        <div className="trow"><span className="lab">Invoiced</span><span className="val">{fmt(inv.totals.invoiced)}</span></div>
        <div className="trow"><span className="lab">Contracted</span><span className="val">{fmt(inv.totals.reference)}</span></div>
        <div className="trow verified-tot"><span className="lab">Exception</span><span className="val">$0.00</span></div>
      </div>
      <div className="clean">
        <Icon name="checkCircle" size={22} />
        <div>
          <div className="t">Clean three-way match</div>
          <div className="s">Every line reconciles to {inv.po} and {inv.grn} at the contracted rate. No variance found — safe to clear in one click.</div>
        </div>
      </div>
      {resolved
        ? <div className="resolved-banner cleared"><Icon name="check" size={19} /><div>Cleared for payment<span className="sub">Marked verified · routed to AP. The system did not post or pay.</span></div></div>
        : <div className="actions">
            <div className="label"><Icon name="shield" size={13} />You clear it — nothing posts automatically</div>
            <button className="btn btn--clear" onClick={() => onClear("cleared")}><Icon name="check" size={15} />Clear for payment</button>
          </div>}
      <LedgerFoot />
    </div>
  );
}

/* missing-doc resolution */
function MissingResolution({ inv, resolved, onClear }) {
  return (
    <div className="res-wrap fade-in">
      <div className="missing-doc">
        <Icon name="alertTri" size={20} />
        <div>
          <div className="t">Can't reconcile — receipt missing</div>
          <div className="s">Quantities can't be verified without a goods-receipt note. The system won't guess a match. Route this to the warehouse to confirm receipt, or flag it for manual review.</div>
        </div>
      </div>
      {resolved
        ? <div className="resolved-banner flagged"><Icon name="flag" size={19} /><div>Flagged for review<span className="sub">Routed for a manual goods-receipt check. Nothing posted.</span></div></div>
        : <div className="actions">
            <div className="label"><Icon name="shield" size={13} />Routed to a person — no auto-match</div>
            <button className="btn btn--flag" style={{ gridColumn: "1 / -1" }} onClick={() => onClear("review")}><Icon name="flag" size={15} />Flag for manual review</button>
          </div>}
      <LedgerFoot />
    </div>
  );
}

/* exception resolution */
function ExceptionResolution({ inv, resolved, resolveKind, onResolve, onEvidence, animate }) {
  const fmt = window.RECON.fmtMoney;
  const exceptions = inv.lines.filter((l) => l.verdict === "exception");
  const [draft, draftDone] = useTypewriter(inv.draft, animate && !resolved);
  const isCredit = inv.totals.exceptionType === "credit";

  return (
    <div className="res-wrap fade-in">
      <div className="totals">
        <div className="trow"><span className="lab">Invoiced total</span><span className="val">{fmt(inv.totals.invoiced)}</span></div>
        <div className="trow"><span className="lab">Contracted total</span><span className="val">{fmt(inv.totals.reference)}</span></div>
        <div className="trow exception">
          <span className="lab">{isCredit ? "Credit owed to you" : "Exception"}</span>
          <MoneyCountUp target={inv.totals.exception} run={animate} className="val" />
        </div>
      </div>

      <div>
        <div className="section-lbl">Why <span className="cnt">{exceptions.length}</span></div>
        <div className="why">
          {exceptions.map((ln) => (
            <div className="item" key={ln.id}>
              <div className="h">
                <span className="name">{ln.svc}</span>
                <span className="amt">{fmt(Math.abs(ln.delta), !isCredit)}</span>
              </div>
              <div className="desc">{ln.detail}.</div>
              <span className="ev" onClick={() => onEvidence(ln.evidence)}><Icon name="external" size={11} />evidence — clause · PO · receipt</span>
            </div>
          ))}
        </div>
      </div>

      <div className="draft">
        <div className="dh">
          <span className="t"><Icon name="mail" size={13} />Draft {isCredit ? "credit request" : "dispute note"}</span>
          <button className="copy"><Icon name="copy" size={11} />copy</button>
        </div>
        <div className="dbody">
          {resolved ? inv.draft : draft}
          {animate && !resolved && !draftDone && <span className="cur"></span>}
        </div>
      </div>

      {resolved
        ? <ResolvedBanner kind={resolveKind} />
        : <div className="actions">
            <div className="label"><Icon name="shield" size={13} />You decide — the system never posts or pays</div>
            <button className="btn btn--clear" onClick={() => onResolve("cleared")}><Icon name="check" size={15} />Clear (accept as billed)</button>
            <div className="act-row">
              <button className="btn btn--dispute" onClick={() => onResolve("disputed")}><Icon name="send" size={15} />Dispute</button>
              <button className="btn btn--flag" onClick={() => onResolve("review")}><Icon name="flag" size={15} />Flag</button>
            </div>
          </div>}
      <LedgerFoot />
    </div>
  );
}

function ResolvedBanner({ kind }) {
  if (kind === "disputed") return <div className="resolved-banner disputed"><Icon name="send" size={19} /><div>Dispute sent to vendor<span className="sub">Draft queued to the vendor · invoice held. Nothing posted to the ledger.</span></div></div>;
  if (kind === "review") return <div className="resolved-banner flagged"><Icon name="flag" size={19} /><div>Flagged for review<span className="sub">Escalated to a colleague. No payment actioned.</span></div></div>;
  return <div className="resolved-banner cleared"><Icon name="check" size={19} /><div>Cleared for payment<span className="sub">Accepted as billed · routed to AP. The system did not pay.</span></div></div>;
}

function LedgerFoot() {
  return (
    <div className="res-foot">
      <Icon name="lock" size={13} />
      <span>Every outcome is yours to action. This tool surfaces and drafts — it never posts to the ledger and never pays a supplier.</span>
    </div>
  );
}

function Resolution({ inv, processing, resolved, resolveKind, onResolve, onEvidence }) {
  if (!inv) {
    return (
      <div className="pane">
        <div className="pane-hd"><div className="row"><h2>Resolution</h2></div><div className="sub">Decision &amp; draft</div></div>
        <div className="pane-body"><div className="res-empty">Totals, the plain-language breakdown and your Clear / Dispute / Flag controls appear here once an invoice is analysed.</div></div>
      </div>
    );
  }
  return (
    <div className="pane">
      <div className="pane-hd">
        <div className="row"><h2>Resolution</h2>
          <span className="mono" style={{ fontSize: 11, color: "var(--rmai-fg-mut)" }}>{inv.id}</span>
        </div>
        <div className="sub">Decision &amp; draft · human-in-the-loop</div>
      </div>
      <div className="pane-body">
        {processing
          ? <div className="res-wrap"><div className="shimmer-row" style={{ height: 120 }}></div><div className="shimmer-row" style={{ height: 70 }}></div><div className="shimmer-row" style={{ height: 90 }}></div></div>
          : inv.kind === "missing-doc"
            ? <MissingResolution inv={inv} resolved={resolved} onClear={onResolve} />
            : inv.kind === "clean"
              ? <CleanResolution inv={inv} resolved={resolved} onClear={onResolve} />
              : <ExceptionResolution inv={inv} resolved={resolved} resolveKind={resolveKind} onResolve={onResolve} onEvidence={onEvidence} animate={true} />}
      </div>
    </div>
  );
}

Object.assign(window, { Resolution });
