// ============================================================
// Nami Order Portal — Customer-facing review surface
// ============================================================

const CustomerReview = ({ deal, onExit, onApprove, onSendBack, onSubmitComment, onSendForSignature, onSaveCustomerEdits, remoteMode }) => {
  const variants = window.NAMI_DATA.VARIANTS;
  const trims = window.NAMI_DATA.TRIM_TIERS;
  const t = trims[deal.trim || "premier"];

  const [comments, setComments] = React.useState(deal.comments || []);
  React.useEffect(() => {
    setComments(deal.comments || []);
  }, [deal.comments]);
  const [decisions, setDecisions] = React.useState({}); // amendId -> 'accept' | 'change'
  const [active, setActive] = React.useState(null); // {anchor, label}
  const [draft, setDraft] = React.useState("");

  // group comments
  const byAnchor = React.useMemo(() => {
    const m = {};
    comments.forEach((c) => { (m[c.anchor] = m[c.anchor] || []).push(c); });
    return m;
  }, [comments]);

  const amendments = variants
    .map((v) => {
      const val = (deal.variants || {})[v.id];
      if (val == null || val === false || (Array.isArray(val) && !val.length)) return null;
      const text = v.langTemplate(val);
      if (!text) return null;
      return { variant: v, text };
    })
    .filter(Boolean);

  const commits = deal.commits || [50_000_000];
  const cpm = deal.cpm || t.cpmRepresentative;

  const openComposer = (anchor, label) => {
    setActive({ anchor, label });
    setDraft("");
    setTimeout(() => {
      const el = document.getElementById("composer-input");
      if (el) el.focus();
    }, 50);
  };

  const submitComment = () => {
    if (!draft.trim() || !active) return;
    const optimistic = {
      id: "new-" + Date.now(),
      anchor: active.anchor,
      anchorLabel: active.label,
      author: deal.contractAdmin?.name || "Reviewer",
      role: "customer",
      time: "just now",
      body: draft.trim(),
      status: "open",
    };
    setComments([...comments, optimistic]);
    setDraft("");
    setActive(null);
    if (onSubmitComment) {
      onSubmitComment(optimistic);
    }
  };

  const setDecision = (id, val) => {
    setDecisions((d) => ({ ...d, [id]: d[id] === val ? null : val }));
  };

  const scrollTo = (anchor) => {
    const el = document.querySelector(`[data-anchor="${anchor}"]`);
    if (el) {
      el.scrollIntoView({ block: "center", behavior: "smooth" });
      setActive({ anchor, label: el.dataset.anchorLabel });
    }
  };

  const openComments = comments.filter((c) => c.status === "open").length;
  const allDecisionsMade = amendments.every((a) => decisions[a.variant.id]);
  const [showApproveConfirm, setShowApproveConfirm] = React.useState(false);
  const pendingDecisions = amendments.filter((a) => !decisions[a.variant.id]).length;

  const [showForward, setShowForward] = React.useState(false);
  const [showRequestChanges, setShowRequestChanges] = React.useState(false);
  const [showEditDetails, setShowEditDetails] = React.useState(false);

  return (
    <div className="review-shell" data-screen-label="05 Customer review surface">
      {/* DRAFT banner — always visible so the customer never confuses
          this surface with the binding DocuSign envelope. */}
      <div className="draft-banner">
        <Icon name="warn" size={14} />
        <span><strong>Draft — not yet binding.</strong> This document becomes binding only when you trigger DocuSign signature below and both parties sign.</span>
      </div>

      {/* Navy topbar */}
      <div className="review-topbar">
        <img src="assets/nami-wordmark-white.svg" alt="Nami" />
        <span className="divider" />
        <div className="who">
          You're reviewing on behalf of <strong>{deal.customer}</strong>
        </div>
        <div className="review-topbar__spacer" />
        <span className="help">
          <Icon name="info" size={13} />
          Sent by Marcus Reid · Nami ML
        </span>
        <button className="btn btn--ghost btn--sm" style={{ color: "rgba(255,255,255,0.85)" }} onClick={onExit}>
          <Icon name="x" size={14} /> Exit review
        </button>
      </div>

      {/* Sub-bar */}
      <div className="review-subbar">
        <div className="review-subbar__deal">
          <DealLogo deal={deal} size={40} />
          <div>
            <div className="title">{deal.name}</div>
            <div className="sub">Service Order package · 4 pages · {amendments.length} pre-approved amendments</div>
            <div className="chips">
              <TrimChip trim={deal.trim} />
              <span className="trim-chip" style={{ background: "var(--alice-grey)", color: "var(--dark-grey)", border: "1px solid var(--strokes)" }}>{deal.termYears}-year term</span>
              <span className="trim-chip" style={{ background: "var(--alice-grey)", color: "var(--dark-grey)", border: "1px solid var(--strokes)" }}>{money(deal.tcv, { compact: true })} TCV</span>
            </div>
          </div>
        </div>

        <div className="review-subbar__actions">
          <button className="btn btn--ghost btn--sm" onClick={() => setShowEditDetails(true)}>
            <Icon name="edit" size={13} /> Edit my details
          </button>
          <button className="btn btn--ghost btn--sm" onClick={() => setShowForward(true)}>
            <Icon name="send" size={13} /> Forward draft
          </button>
          <button className="btn btn--outline btn--sm" onClick={() => setShowRequestChanges(true)}>
            <Icon name="edit" size={13} /> Request changes
          </button>
          <button
            className="btn btn--alloy btn--sm"
            disabled={openComments > 0}
            onClick={() => setShowApproveConfirm(true)}
          >
            <Icon name="docusign" size={13} /> Send for signature
          </button>
        </div>
      </div>

      <div className="review-main">
        {/* Document */}
        <div className="review-doc">
          <ReviewDoc
            deal={deal}
            amendments={amendments}
            commits={commits}
            cpm={cpm}
            t={t}
            byAnchor={byAnchor}
            active={active?.anchor}
            onClauseClick={openComposer}
            decisions={decisions}
            setDecision={setDecision}
          />
        </div>

        {/* Comments rail */}
        <aside className="review-rail">
          <div className="review-rail__head">
            <div className="review-rail__title">
              Comments
              {comments.length > 0 && <span className="review-rail__count">{comments.length}</span>}
            </div>
            <button className="btn btn--ghost btn--sm" style={{ height: 24, padding: "0 8px", fontSize: 11 }}>
              <Icon name="filter" size={11} /> Open
            </button>
          </div>

          {active && (
            <div className="composer">
              <div className="composer__head">Adding comment on</div>
              <div style={{ fontSize: 12.5, color: "var(--blue-alloy)", fontWeight: 600, marginBottom: 6 }}>
                {active.label}
              </div>
              <textarea
                id="composer-input"
                placeholder="What's your concern, or your sign-off?"
                value={draft}
                onChange={(e) => setDraft(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) submitComment();
                }}
              />
              <div className="composer__actions">
                <div className="composer__anchor">
                  Anchored to <strong>{active.label.split("—")[0].trim()}</strong>
                </div>
                <div style={{ display: "flex", gap: 6 }}>
                  <button className="btn btn--ghost btn--sm" style={{ height: 28, padding: "0 12px", fontSize: 12 }} onClick={() => setActive(null)}>Cancel</button>
                  <button className="btn btn--alloy btn--sm" style={{ height: 28, padding: "0 12px", fontSize: 12 }} disabled={!draft.trim()} onClick={submitComment}>
                    Post comment
                  </button>
                </div>
              </div>
            </div>
          )}

          {amendments.length > 0 && (
            <div className="review-decision">
              <h4>Quick decisions on amendments</h4>
              {amendments.map((a) => {
                const d = decisions[a.variant.id];
                return (
                  <div className="review-decision__row" key={a.variant.id}>
                    <div className="name">{a.variant.category}</div>
                    <div className="accept-row">
                      <button
                        className={d === "accept" ? "is-on--accept" : ""}
                        onClick={() => setDecision(a.variant.id, "accept")}
                      >Accept</button>
                      <button
                        className={d === "change" ? "is-on--change" : ""}
                        onClick={() => setDecision(a.variant.id, "change")}
                      >Needs change</button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {comments.length === 0 && !active && (
            <div className="review-rail__empty">
              <Icon name="files" size={28} color="var(--strokes)" />
              <div style={{ marginTop: 12, fontWeight: 600, color: "var(--navy)" }}>No comments yet</div>
              <div style={{ marginTop: 4, fontSize: 12.5 }}>Hover any section in the document and click the comment icon to leave inline feedback.</div>
            </div>
          )}

          <div className="flex-col gap-2">
            {comments.map((c) => (
              <div
                key={c.id}
                className={`comment is-${c.role} ${c.anchor === active?.anchor ? "is-anchored" : ""}`}
              >
                <div className="comment__anchor" onClick={() => scrollTo(c.anchor)}>{c.anchorLabel}</div>
                <div className="comment__head">
                  <div className="comment__avatar" style={{ background: c.role === "customer" ? "var(--nami-blue)" : "var(--kelp)" }}>
                    {c.author.split(" ").map((n) => n[0]).slice(0, 2).join("")}
                  </div>
                  <div className="comment__author">{c.author}</div>
                  <div className="comment__time">{c.time}</div>
                </div>
                <div className="comment__body">{c.body}</div>
                <div className={`comment__status comment__status--${c.status}`}>
                  <Icon name={c.status === "open" ? "alert" : "check"} size={10} />
                  {c.status === "open" ? "Open" : c.status === "accepted" ? "Accepted" : "Resolved"}
                </div>
              </div>
            ))}
          </div>
        </aside>
      </div>

      {showApproveConfirm && (
        <ApproveConfirmModal
          deal={deal}
          amendments={amendments}
          decisions={decisions}
          pendingDecisions={pendingDecisions}
          openComments={openComments}
          onCancel={() => setShowApproveConfirm(false)}
          onConfirm={() => {
            setShowApproveConfirm(false);
            // New workflow: confirming the modal triggers DocuSign
            // directly. Old `onApprove` is the offline-fallback path.
            if (onSendForSignature) onSendForSignature();
            else onApprove();
          }}
        />
      )}

      {showForward && (
        <ForwardDraftModal
          deal={deal}
          onCancel={() => setShowForward(false)}
          onSubmit={() => setShowForward(false)}
        />
      )}

      {showRequestChanges && (
        <RequestChangesModal
          deal={deal}
          onCancel={() => setShowRequestChanges(false)}
          onSubmit={() => { setShowRequestChanges(false); onSendBack(); }}
        />
      )}

      {showEditDetails && (
        <EditDetailsModal
          deal={deal}
          onCancel={() => setShowEditDetails(false)}
          onSubmit={async (patch) => {
            try { if (onSaveCustomerEdits) await onSaveCustomerEdits(patch); }
            catch { /* error surfaced inside the modal */ }
            setShowEditDetails(false);
          }}
        />
      )}
    </div>
  );
};

// Confirmation dialog before the customer commits to signing. The button
// in the sub-bar is the primary visual; this modal is the safety check so
// nobody approves a $1M deal by mis-clicking.
const ApproveConfirmModal = ({ deal, amendments, decisions, pendingDecisions, openComments, onCancel, onConfirm }) => {
  const accepted = amendments.filter((a) => decisions[a.variant.id] === "accept").length;
  const needsChange = amendments.filter((a) => decisions[a.variant.id] === "change").length;

  return (
    <div className="approve-modal__scrim" onClick={onCancel}>
      <div className="approve-modal" onClick={(e) => e.stopPropagation()}>
        <div className="approve-modal__head">
          <Icon name="checkCircle" size={20} color="var(--kelp)" />
          <h2>Approve and proceed to signature?</h2>
        </div>

        <p className="approve-modal__lede">
          By approving, you're confirming that {deal.customer} has reviewed
          the package and is ready to receive it for signature via DocuSign.
        </p>

        <div className="approve-modal__summary">
          <div className="row">
            <span className="label">Deal</span>
            <span className="value">{deal.name}</span>
          </div>
          <div className="row">
            <span className="label">Total contract value</span>
            <span className="value">{money(deal.tcv)}</span>
          </div>
          {amendments.length > 0 && (
            <div className="row">
              <span className="label">Amendments</span>
              <span className="value">
                {accepted} accepted{needsChange > 0 ? `, ${needsChange} flagged "needs change"` : ""}
              </span>
            </div>
          )}
        </div>

        {(pendingDecisions > 0 || needsChange > 0) && (
          <div className="approve-modal__warn">
            <Icon name="alert" size={14} />
            <div>
              {pendingDecisions > 0 && (
                <div>{pendingDecisions} amendment{pendingDecisions === 1 ? "" : "s"} still need{pendingDecisions === 1 ? "s" : ""} a decision. Approving will leave them un-marked.</div>
              )}
              {needsChange > 0 && (
                <div>{needsChange} amendment{needsChange === 1 ? "" : "s"} marked "needs change" — those won't be addressed by approving. Send back with comments instead.</div>
              )}
            </div>
          </div>
        )}

        <div className="approve-modal__actions">
          <button className="btn btn--ghost btn--sm" onClick={onCancel}>
            Cancel
          </button>
          <button className="btn btn--alloy btn--sm" onClick={onConfirm}>
            <Icon name="check" size={13} /> Yes, send for signature
          </button>
        </div>
      </div>
    </div>
  );
};

// Customer-side "Edit my details" modal. Lets the customer fix the
// fields most likely to be wrong on a freshly-sent draft — legal entity
// name, addresses, signatory, billing contact — without going through a
// full change-request round-trip. Edits accumulate on
// `envelope.customerEdits` and are picked up by send-for-signature.
const EditDetailsModal = ({ deal, onCancel, onSubmit }) => {
  const [form, setForm] = React.useState({
    customerLegal: deal.customerLegal || "",
    customerAddress: deal.customerAddress || "",
    noticeAddress: deal.noticeAddress || "",
    contractAdmin: {
      name: deal.contractAdmin?.name || "",
      title: deal.contractAdmin?.title || "",
      email: deal.contractAdmin?.email || "",
    },
    billingContact: {
      name: deal.billingContact?.name || "",
      email: deal.billingContact?.email || "",
    },
  });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const setTop = (key, val) => setForm((f) => ({ ...f, [key]: val }));
  const setNested = (parent, key, val) =>
    setForm((f) => ({ ...f, [parent]: { ...f[parent], [key]: val } }));

  const handleSubmit = async () => {
    setBusy(true);
    setErr(null);
    try {
      await onSubmit(form);
    } catch (e) {
      setErr(String(e?.message || e));
      setBusy(false);
    }
  };

  return (
    <div className="approve-modal__scrim" onClick={onCancel}>
      <div className="approve-modal" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 620 }}>
        <div className="approve-modal__head">
          <Icon name="edit" size={20} color="var(--blue-alloy)" />
          <h2>Edit customer details</h2>
        </div>
        <p className="approve-modal__lede">
          Fix anything the Nami AE got slightly wrong — legal entity name, the address on the contract, who's actually signing. Your edits flow into the DocuSign envelope when you trigger signature. Your AE sees the diff on their end.
        </p>

        <div className="field">
          <label className="field__label">Customer legal entity</label>
          <input
            className="input"
            value={form.customerLegal}
            onChange={(e) => setTop("customerLegal", e.target.value)}
            placeholder="Acme Holdings, Inc., a Delaware corporation"
          />
        </div>

        <div className="field">
          <label className="field__label">Customer address</label>
          <textarea
            className="input"
            rows={2}
            value={form.customerAddress}
            onChange={(e) => setTop("customerAddress", e.target.value)}
            style={{ fontFamily: "inherit", resize: "vertical" }}
            placeholder="Street, city, state, ZIP"
          />
        </div>

        <div className="field">
          <label className="field__label">Legal Notices</label>
          <input
            className="input"
            value={form.noticeAddress}
            onChange={(e) => setTop("noticeAddress", e.target.value)}
            placeholder="Attn: General Counsel, …"
          />
        </div>

        <div style={{ marginTop: 6, marginBottom: 6, fontSize: 11, fontWeight: 700, color: "var(--blue-alloy)", textTransform: "uppercase", letterSpacing: "0.06em" }}>
          Signatory
        </div>
        <div className="row">
          <div className="field">
            <label className="field__label">Name</label>
            <input
              className="input"
              value={form.contractAdmin.name}
              onChange={(e) => setNested("contractAdmin", "name", e.target.value)}
              placeholder="Devon Park"
            />
          </div>
          <div className="field">
            <label className="field__label">Title</label>
            <input
              className="input"
              value={form.contractAdmin.title}
              onChange={(e) => setNested("contractAdmin", "title", e.target.value)}
              placeholder="VP, Finance"
            />
          </div>
        </div>
        <div className="field">
          <label className="field__label">Email</label>
          <input
            className="input"
            type="email"
            value={form.contractAdmin.email}
            onChange={(e) => setNested("contractAdmin", "email", e.target.value)}
            placeholder="signer@yourcompany.com"
          />
        </div>

        <div style={{ marginTop: 6, marginBottom: 6, fontSize: 11, fontWeight: 700, color: "var(--blue-alloy)", textTransform: "uppercase", letterSpacing: "0.06em" }}>
          A/P email address
        </div>
        <div className="field">
          <label className="field__label">Email</label>
          <input
            className="input"
            type="email"
            value={form.billingContact.email}
            onChange={(e) => setNested("billingContact", "email", e.target.value)}
            placeholder="ap@yourcompany.com"
          />
          <div className="field__hint">Where Stripe invoices for this deal will be sent.</div>
        </div>

        {err && (
          <div className="approve-modal__warn" style={{ background: "rgba(216,58,88,0.10)", borderColor: "rgba(216,58,88,0.30)" }}>
            <Icon name="alert" size={14} color="#b3273f" />
            <div style={{ color: "#b3273f" }}>{err}</div>
          </div>
        )}

        <div className="approve-modal__actions">
          <button className="btn btn--ghost btn--sm" onClick={onCancel} disabled={busy}>Cancel</button>
          <button className="btn btn--alloy btn--sm" onClick={handleSubmit} disabled={busy}>
            {busy ? "Saving…" : <><Icon name="check" size={13} /> Save edits</>}
          </button>
        </div>
      </div>
    </div>
  );
};

// Forward draft to another reviewer (or yourself). Email + optional note;
// real send is stubbed — captured in TODO.md.
const ForwardDraftModal = ({ deal, onCancel, onSubmit }) => {
  const [email, setEmail] = React.useState("");
  const [note, setNote] = React.useState("");
  const [sent, setSent] = React.useState(false);
  return (
    <div className="approve-modal__scrim" onClick={onCancel}>
      <div className="approve-modal" onClick={(e) => e.stopPropagation()}>
        <div className="approve-modal__head">
          <Icon name="send" size={20} color="var(--blue-alloy)" />
          <h2>Forward this draft</h2>
        </div>
        {!sent ? (
          <>
            <p className="approve-modal__lede">
              Send a read-only copy of this draft to a colleague (legal counsel, procurement, finance). They'll receive their own one-time link — no Nami account needed.
            </p>
            <div className="field">
              <label className="field__label">Recipient email</label>
              <input
                type="email"
                className="input"
                placeholder="counsel@yourcompany.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoFocus
              />
            </div>
            <div className="field">
              <label className="field__label">Note (optional)</label>
              <textarea
                className="input"
                placeholder="Why you're sending this — e.g. 'Need your sign-off on the liability cap.'"
                rows={3}
                value={note}
                onChange={(e) => setNote(e.target.value)}
                style={{ fontFamily: "inherit", resize: "vertical" }}
              />
            </div>
            <div className="approve-modal__actions">
              <button className="btn btn--ghost btn--sm" onClick={onCancel}>Cancel</button>
              <button
                className="btn btn--alloy btn--sm"
                disabled={!email.includes("@")}
                onClick={() => setSent(true)}
              >
                <Icon name="send" size={13} /> Send copy
              </button>
            </div>
          </>
        ) : (
          <div style={{ textAlign: "center", padding: "12px 0 4px" }}>
            <div style={{ width: 52, height: 52, borderRadius: "50%", background: "rgba(102,204,153,0.18)", color: "#1e7849", margin: "0 auto 14px", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="check" size={26} />
            </div>
            <h2 style={{ fontSize: 17 }}>Copy sent to {email}.</h2>
            <p style={{ fontSize: 13, color: "var(--dark-grey)" }}>
              They'll get a one-time link to this same draft. Any changes they request route back through you.
            </p>
            <div className="approve-modal__actions" style={{ justifyContent: "center" }}>
              <button className="btn btn--alloy btn--sm" onClick={onSubmit}>Done</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Request structured changes to the draft — kicks the workflow back to
// Nami's AE. v1 wraps the existing "send back" semantics; v2 will let the
// customer edit specific fields (address, signatory, etc.) inline and
// roll those into the change request — captured in TODO.md.
const RequestChangesModal = ({ deal, onCancel, onSubmit }) => {
  const [body, setBody] = React.useState("");
  return (
    <div className="approve-modal__scrim" onClick={onCancel}>
      <div className="approve-modal" onClick={(e) => e.stopPropagation()}>
        <div className="approve-modal__head">
          <Icon name="edit" size={20} color="#8a5d00" />
          <h2>Request changes</h2>
        </div>
        <p className="approve-modal__lede">
          Describe what needs to change. Your Nami AE will review your request, update the draft, and send a revised version back. No signature is collected until you trigger DocuSign.
        </p>
        <div className="approve-modal__warn" style={{ background: "rgba(11, 74, 142, 0.06)", borderColor: "rgba(11, 74, 142, 0.25)" }}>
          <Icon name="info" size={14} color="var(--blue-alloy)" />
          <div style={{ color: "var(--navy)" }}>
            Common request types: change signatory, update A/P email or legal notices, adjust commit volume, request a payment-terms variant (e.g. Net 45), redline an amendment.
          </div>
        </div>
        <div className="field">
          <textarea
            className="input"
            placeholder="What needs to change?"
            rows={5}
            value={body}
            onChange={(e) => setBody(e.target.value)}
            style={{ fontFamily: "inherit", resize: "vertical" }}
            autoFocus
          />
        </div>
        <div className="approve-modal__actions">
          <button className="btn btn--ghost btn--sm" onClick={onCancel}>Cancel</button>
          <button
            className="btn btn--alloy btn--sm"
            disabled={!body.trim()}
            onClick={onSubmit}
          >
            <Icon name="send" size={13} /> Send request to Nami
          </button>
        </div>
      </div>
    </div>
  );
};

// ----- Document body, with clickable clauses -----
const ReviewDoc = ({ deal, amendments, commits, cpm, t, byAnchor, active, onClauseClick, decisions, setDecision }) => {
  const C = ({ anchor, label, children }) => (
    <div
      className={`clause ${byAnchor[anchor]?.length ? "has-comments" : ""} ${active === anchor ? "is-active" : ""}`}
      data-anchor={anchor}
      data-anchor-label={label}
      onClick={() => onClauseClick(anchor, label)}
    >
      {children}
      <button className="clause__icon" onClick={(e) => { e.stopPropagation(); onClauseClick(anchor, label); }} title="Add comment">
        {byAnchor[anchor]?.length
          ? <span className="clause__icon-count">{byAnchor[anchor].length}</span>
          : <Icon name="plus" size={12} />
        }
      </button>
    </div>
  );

  return (
    <div>
      {/* Service Order summary */}
      <div className="review-doc-page">
        <div style={{ fontSize: 10.5, fontWeight: 700, color: "var(--blue-alloy)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Service Order — for review</div>
        <h1 style={{ fontSize: 28, fontWeight: 800, margin: "4px 0 6px", letterSpacing: "-0.025em" }}>Subscription Services Agreement</h1>
        <div style={{ height: 4, background: "var(--gradient-blue)", borderRadius: 9999, width: 56, marginBottom: 22 }} />

        <div style={{ color: "var(--dark-grey)", marginBottom: 16 }}>
          Between Nami ML Inc. ("Nami") and {deal.customer} ("Customer"). This document contains the commercial terms; the standard Terms of Service, DPA, and SLA are referenced and incorporated by link.
        </div>

        <C anchor="service-order-section-2" label="Service Order §2 — Term">
          <h2 className="pdf-h2" style={{ marginTop: 0 }}>2. Subscription Term</h2>
          <div>Initial Term of <strong>{deal.termYears} years</strong> commencing {fmtDate(deal.startDate)} and ending {fmtDate(deal.endDate)}.</div>
        </C>

        <C anchor="service-order-section-3" label="Service Order §3 — Services">
          <h2 className="pdf-h2">3. Services &amp; Trim</h2>
          <div>{t.name} subscription at <strong>${cpm.toFixed(2)} CPM</strong>. Support: <strong style={{ textTransform: "capitalize" }}>{deal.support || "standard"}</strong>.</div>
          <div style={{ marginTop: 10, fontSize: 11, color: "var(--dark-grey)" }}>
            <strong style={{ color: "var(--navy)" }}>Functionality:</strong>{" "}
            {window.NAMI_PRICING.featuresForTrim(t.key).join(" · ")}
          </div>
        </C>

        <C anchor="service-order-section-4" label="Service Order §4 — Volume Commitments">
          <h2 className="pdf-h2">4. Volume Commitments &amp; Fees</h2>
          <table className="pdf-tbl">
            <thead>
              <tr><th>Year</th><th>Commitment</th><th className="num">Annual Fees</th></tr>
            </thead>
            <tbody>
              {commits.map((c, i) => (
                <tr key={i}>
                  <td>Year {i + 1}</td>
                  <td>{c.toLocaleString()} impressions</td>
                  <td className="num">{money((c / 1000) * cpm)}</td>
                </tr>
              ))}
              {(() => {
                const { lineItems } = window.NAMI_PRICING.computeDealTcv(deal);
                return lineItems
                  .filter((li) => li.kind === "addon" || li.kind === "discount")
                  .map((li, i) => (
                    <tr key={`adj-${i}`}>
                      <td colSpan={2} style={{ color: li.kind === "discount" ? "var(--kelp)" : "var(--blue-alloy)" }}>{li.label}</td>
                      <td className="num" style={{ color: li.kind === "discount" ? "var(--kelp)" : undefined }}>
                        {li.amount < 0 ? "−" : ""}{money(Math.abs(li.amount))}
                      </td>
                    </tr>
                  ));
              })()}
              <tr style={{ background: "var(--alice-grey)" }}>
                <td colSpan={2} style={{ fontWeight: 700 }}>Total Contract Value</td>
                <td className="num" style={{ fontWeight: 700 }}>{money(deal.tcv)}</td>
              </tr>
            </tbody>
          </table>
        </C>

        <C anchor="service-order-section-5" label="Service Order §5 — Payment Terms">
          <h2 className="pdf-h2">5. Payment Terms</h2>
          <div>
            Invoiced <strong>{(deal.cadence || "annual") === "usage" ? "monthly in arrears against usage" : (deal.cadence || "annual") === "quarterly" ? "quarterly in advance" : "annually in advance"}</strong>, payable <strong>{deal.netTerms}</strong>.
            {deal.stripeAutoInvoice && <> First invoice issued via Stripe on the Effective Date.</>}
          </div>
        </C>
      </div>

      {/* Amendment Addendum */}
      {amendments.length > 0 && (
        <div className="review-doc-page">
          <div style={{ fontSize: 10.5, fontWeight: 700, color: "var(--blue-alloy)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Amendment Addendum</div>
          <h1 style={{ fontSize: 24, fontWeight: 800, margin: "4px 0 6px", letterSpacing: "-0.025em" }}>Modifications to Terms of Service</h1>
          <div style={{ height: 4, background: "var(--gradient-blue)", borderRadius: 9999, width: 56, marginBottom: 22 }} />
          <div style={{ color: "var(--dark-grey)", marginBottom: 14, fontSize: 12 }}>
            These provisions modify the standard Terms of Service. In case of conflict, this Addendum prevails. Use Accept / Needs change inline, or comment on the language.
          </div>

          {amendments.map((a, i) => {
            const d = decisions[a.variant.id];
            return (
              <C key={a.variant.id} anchor={`amendment-${i + 1}`} label={`Amendment ${i + 1} — ${a.variant.category}`}>
                <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 700, color: "var(--navy)" }}>{i + 1}. {a.variant.category}</div>
                    <div style={{ fontSize: 10.5, color: "var(--dark-grey)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600, marginTop: 2 }}>{a.variant.section}</div>
                  </div>
                  <div style={{ display: "flex", gap: 4 }} onClick={(e) => e.stopPropagation()}>
                    <button
                      className={d === "accept" ? "is-on--accept" : ""}
                      style={{ background: d === "accept" ? "rgba(102,204,153,0.18)" : "transparent", border: "1px solid var(--strokes)", borderRadius: 9999, fontSize: 11, padding: "3px 10px", color: d === "accept" ? "#1e7849" : "var(--dark-grey)", fontWeight: 600, cursor: "pointer" }}
                      onClick={() => setDecision(a.variant.id, "accept")}
                    >Accept</button>
                    <button
                      className={d === "change" ? "is-on--change" : ""}
                      style={{ background: d === "change" ? "rgba(255,91,116,0.14)" : "transparent", border: "1px solid var(--strokes)", borderRadius: 9999, fontSize: 11, padding: "3px 10px", color: d === "change" ? "#b3273f" : "var(--dark-grey)", fontWeight: 600, cursor: "pointer" }}
                      onClick={() => setDecision(a.variant.id, "change")}
                    >Needs change</button>
                  </div>
                </div>
                <div style={{ marginTop: 8, fontSize: 11.5, fontStyle: "italic", padding: "10px 14px", borderLeft: "3px solid var(--blue-alloy)", background: "var(--alice-grey)", borderRadius: "0 6px 6px 0", lineHeight: 1.6 }}>
                  "{a.text}"
                </div>
              </C>
            );
          })}
        </div>
      )}

      {/* Standard docs reference */}
      <div className="review-doc-page">
        <h2 className="pdf-h2" style={{ marginTop: 0 }}>Standard Documents Incorporated</h2>
        <div style={{ fontSize: 12, marginBottom: 10 }}>
          The following standard Nami documents apply unmodified except as expressly amended above. Open each to read the full text.
        </div>
        <C anchor="schedule-a" label="Schedule A — Master Subscription Agreement">
          <h3 className="pdf-h3" style={{ marginTop: 0 }}>Schedule A — Master Subscription Agreement (Terms of Service v2026.04)</h3>
          <div style={{ fontSize: 12, color: "var(--dark-grey)" }}>Standard SaaS terms. Click to open the full ToS.</div>
        </C>
        <C anchor="schedule-b" label="Schedule B — Service Level Addendum">
          <h3 className="pdf-h3">Schedule B — Service Level Addendum (SLA v2.0)</h3>
          <div style={{ fontSize: 12, color: "var(--dark-grey)" }}>99.999% uptime for Elite + Carrier-Grade; 15-minute P1 response under Concierge.</div>
        </C>
        <C anchor="schedule-c" label="Schedule C — Data Protection Addendum">
          <h3 className="pdf-h3">Schedule C — Data Protection Addendum (DPA v2.0)</h3>
          <div style={{ fontSize: 12, color: "var(--dark-grey)" }}>2021 SCCs + UK IDTA Annex. Expanded Applicable Data Protection Laws definition.</div>
        </C>
      </div>
    </div>
  );
};

window.CustomerReview = CustomerReview;
