// ============================================================
// Nami Order Portal — Variant builder (step 5) + Preview (step 6)
// ============================================================

const StepVariants = ({ deal, onUpdate, onOpenPreview, layout = "two-column" }) => {
  const variants = window.NAMI_DATA.VARIANTS;
  const trim = deal.trim || "premier";
  const addons = deal.addons || [];
  const selected = deal.variants || {};
  const [expanded, setExpanded] = React.useState({});

  const setVariant = (id, value) => {
    const next = { ...selected };
    if (value == null || value === false || (Array.isArray(value) && !value.length)) {
      delete next[id];
    } else {
      next[id] = value;
    }
    const patch = { variants: next };
    // Payment-terms variant doubles as the source-of-truth for
    // `deal.netTerms` so existing consumers (DocuSign HTML doc, Stripe
    // due-date math, customer review) don't need to chase the variant
    // separately.
    if (id === "v11-payment-terms") {
      patch.netTerms = value === "net45" ? "Net 45" : value === "net60" ? "Net 60" : "Net 30";
    }
    onUpdate(patch);
  };

  const isEligible = (v) => {
    if (!v.tierFilter.includes(trim)) return false;
    if (v.requires?.addon && !addons.includes(v.requires.addon)) return false;
    return true;
  };

  return (
    <div style={{ margin: -28, marginTop: -28 }}>
      <div className={`variant-builder ${layout === "single-column" ? "variant-builder--single" : ""}`}>
        <div className="variant-builder__menu">
          {variants.map((v) => {
            const eligible = isEligible(v);
            const value = selected[v.id];
            const hasValue = value != null && value !== false && !(Array.isArray(value) && !value.length);
            const isFlagged = hasValue && v.kind === "radio" && v.options.find((o) => o.value === value)?.legal;

            return (
              <div
                key={v.id}
                className={`variant-card ${hasValue ? "is-active" : ""} ${!eligible ? "is-disabled" : ""} ${isFlagged ? "is-flagged" : ""}`}
              >
                <div className="variant-card__head">
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="variant-card__title">{v.category}</div>
                    <div className="variant-card__section">{v.section}</div>
                  </div>
                  <span className="variant-card__tier">{v.tier}</span>
                </div>
                <div className="variant-card__desc">{v.desc}</div>

                {!eligible && (
                  <div className="variant-card__lock">
                    <Icon name="lock" size={13} />
                    Requires {v.tier}
                    {v.requires?.addon && !addons.includes(v.requires.addon) ? ` + ${v.requiresLabel || v.requires.addon}` : ""}
                  </div>
                )}

                {eligible && (
                  <div className="variant-card__controls">
                    <VariantControl variant={v} value={value} onChange={(val) => setVariant(v.id, val)} />
                  </div>
                )}

                {isFlagged && (
                  <div className="variant-card__flag">
                    <Icon name="warn" size={13} />
                    Will route to Legal Review
                  </div>
                )}

                {eligible && (
                  <>
                    <button className="variant-card__expand" onClick={() => setExpanded({ ...expanded, [v.id]: !expanded[v.id] })}>
                      {expanded[v.id] ? "Hide" : "Preview"} replacement language
                      <Icon name={expanded[v.id] ? "chevronUp" : "chevronDown"} size={12} />
                    </button>
                    {expanded[v.id] && (
                      <div className="variant-card__lang">
                        "{previewLang(v, value)}"
                      </div>
                    )}
                  </>
                )}
              </div>
            );
          })}
        </div>

        <div className="variant-builder__preview">
          <div className="preview__head">
            <div className="preview__title">Amendment Addendum — live preview</div>
            <button className="btn btn--ghost btn--sm" onClick={onOpenPreview} disabled={!onOpenPreview}>
              <Icon name="eye" size={13} /> Full preview
            </button>
          </div>

          <div className="preview__doc">
            <h1>Amendment Addendum</h1>
            <div className="doc-meta">{deal.customer || "Customer"} · {deal.name || "Deal name"}</div>

            {renderedAmendments(deal, variants).length === 0 ? (
              <div className="preview__empty">
                <Icon name="files" size={28} color="var(--strokes)" />
                <div style={{ marginTop: 12, fontWeight: 600, color: "var(--navy)" }}>No variants selected yet</div>
                <div style={{ marginTop: 4 }}>The standard Terms of Service apply with no modifications. Pick from the menu on the left to amend specific sections.</div>
              </div>
            ) : (
              renderedAmendments(deal, variants).map((a, i) => (
                <div key={a.id} className="amend">
                  <div className="amend__h">{i + 1}. {a.category}</div>
                  <div className="amend__sec">{a.section}</div>
                  <div className="amend__lang">"{a.text}"</div>
                </div>
              ))
            )}
          </div>

          <div style={{ fontSize: 11.5, color: "var(--dark-grey)", lineHeight: 1.5, padding: "0 4px" }}>
            The Amendment Addendum is auto-numbered and embedded in the Service Order PDF. Customers see this language verbatim.
          </div>
        </div>
      </div>
    </div>
  );
};

// ---- variant controls (radio / toggle / checkboxes) ----
const VariantControl = ({ variant, value, onChange }) => {
  if (variant.kind === "radio") {
    return (
      <div className="radio-group">
        {variant.options.map((o) => (
          <div
            key={o.value}
            className={`radio-row ${value === o.value ? "is-selected" : ""} ${o.legal ? "flag-legal" : ""}`}
            onClick={() => onChange(o.value)}
          >
            <span className="radio-circle" />
            <div style={{ flex: 1 }}>
              <div className="radio-row__label">{o.label}</div>
              {o.hint && <div className="radio-row__hint">{o.hint}</div>}
            </div>
          </div>
        ))}
      </div>
    );
  }
  if (variant.kind === "toggle") {
    return (
      <div className="toggle-row">
        <span style={{ fontSize: 13.5, color: "var(--navy)", fontWeight: 500 }}>{variant.toggleLabel}</span>
        <button className={`toggle ${value ? "is-on" : ""}`} onClick={() => onChange(!value)}>
          <span className="toggle__thumb" />
        </button>
      </div>
    );
  }
  if (variant.kind === "checkboxes") {
    const arr = Array.isArray(value) ? value : [];
    return (
      <div className="checkbox-group">
        {variant.options.map((o) => {
          const on = arr.includes(o.value);
          return (
            <div
              key={o.value}
              className={`checkbox-row ${on ? "is-checked" : ""}`}
              onClick={() => onChange(on ? arr.filter((x) => x !== o.value) : [...arr, o.value])}
            >
              <span className="checkbox-box">{on && <Icon name="check" size={12} />}</span>
              <span className="checkbox-row__label">{o.label}</span>
            </div>
          );
        })}
      </div>
    );
  }
  return null;
};

const previewLang = (v, value) => {
  const sample = value != null && value !== false && !(Array.isArray(value) && !value.length)
    ? value
    : (v.kind === "radio" ? v.options[0].value : v.kind === "toggle" ? true : [v.options[0].value]);
  return v.langTemplate(sample) || "(this variant adds no amendment when left at the standard option)";
};

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

// ============================================================
// Step 6 — Preview & send
// ============================================================
const StepPreview = ({ deal, validation, onSendModal, onJump, onRequestException }) => {
  const variants = window.NAMI_DATA.VARIANTS;
  const amends = renderedAmendments(deal, variants);
  const [composer, setComposer] = React.useState(null); // ruleId being composed
  const [draft, setDraft] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const submitException = async (ruleId) => {
    if (!draft.trim() || !onRequestException) return;
    setBusy(true);
    try {
      await onRequestException(ruleId, draft.trim());
      setComposer(null);
      setDraft("");
    } finally {
      setBusy(false);
    }
  };

  const sendDisabled = validation.blocks > 0 || validation.pendingExceptions > 0;
  const sendDisabledReason = validation.blocks > 0
    ? `${validation.blocks} hard block${validation.blocks === 1 ? "" : "s"} remaining`
    : validation.pendingExceptions > 0
      ? `${validation.pendingExceptions} exception${validation.pendingExceptions === 1 ? "" : "s"} awaiting Deal Desk approval`
      : null;

  return (
    <div className="preview-step">
      <div className="doc-frame">
        <DocumentPreview deal={deal} amendments={amends} />
      </div>

      <div className="validation-panel">
        <div className="validation-panel__head">
          <h3>Validation</h3>
          {validation.blocks === 0 && validation.pendingExceptions === 0 && (
            <span className="status-badge status--signed"><span className="dot" /> Ready</span>
          )}
          {validation.pendingExceptions > 0 && (
            <span className="status-badge status--review"><span className="dot" /> Pending Deal Desk</span>
          )}
        </div>

        <div className="validation-summary">
          <div>
            <div className="num pass">{validation.passes}</div>
            <div className="label">Cleared</div>
          </div>
          <div>
            <div className="num warn">{validation.warnings}</div>
            <div className="label">Warnings</div>
          </div>
          <div>
            <div className="num blocks">{validation.blocks}</div>
            <div className="label">Hard blocks</div>
          </div>
          <div>
            <div className="num" style={{ color: "var(--blue-alloy)" }}>{validation.pendingExceptions}</div>
            <div className="label">Pending</div>
          </div>
        </div>

        <div className="validation-list">
          {validation.items.map((item) => {
            const cls = `validation-item--${item.status === "pass" ? "ok" : item.status}`;
            const iconName = item.status === "pass" || item.status === "exception-approved"
              ? "checkCircle"
              : item.status === "warn" ? "warn"
              : item.status === "exception-pending" ? "clock"
              : "alert";
            return (
              <div key={item.ruleId} className={`validation-item ${cls}`}>
                <div className="validation-item__icon">
                  <Icon name={iconName} size={14} />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="validation-item__title">
                    {item.title}
                    {item.status === "exception-pending" && (
                      <span className="validation-item__pill">
                        <Icon name="clock" size={10} /> Pending approval
                      </span>
                    )}
                    {item.status === "exception-approved" && (
                      <span className="validation-item__pill validation-item__pill--approved">
                        <Icon name="check" size={10} /> Exception approved
                      </span>
                    )}
                  </div>
                  {(item.detail || item.status === "pass" || item.status === "exception-approved") && (
                    <div className="validation-item__detail">
                      {item.status === "pass" || item.status === "exception-approved"
                        ? item.passText
                        : item.detail}
                    </div>
                  )}
                  {item.exception?.status === "approved" && (
                    <div className="validation-item__detail" style={{ marginTop: 4 }}>
                      Approved by <strong>{item.exception.resolvedBy}</strong>
                      {item.exception.resolutionNote ? ` — ${item.exception.resolutionNote}` : ""}
                    </div>
                  )}
                  {item.exception?.status === "rejected" && (
                    <div className="validation-item__detail" style={{ marginTop: 4 }}>
                      Last request rejected by <strong>{item.exception.resolvedBy}</strong>
                      {item.exception.resolutionNote ? ` — ${item.exception.resolutionNote}` : ""}
                    </div>
                  )}

                  {(item.status === "block" || item.status === "warn") && item.allowsException && (
                    composer === item.ruleId ? (
                      <div className="exception-composer">
                        <textarea
                          placeholder="Why should Deal Desk allow this? Customer context, pricing rationale, …"
                          value={draft}
                          onChange={(e) => setDraft(e.target.value)}
                          autoFocus
                        />
                        <div className="exception-composer__row">
                          <button
                            className="btn btn--ghost btn--sm"
                            disabled={busy}
                            onClick={() => { setComposer(null); setDraft(""); }}
                          >Cancel</button>
                          <button
                            className="btn btn--alloy btn--sm"
                            disabled={busy || !draft.trim()}
                            onClick={() => submitException(item.ruleId)}
                          >
                            {busy ? "Sending…" : "Request exception"}
                          </button>
                        </div>
                      </div>
                    ) : (
                      <div className="validation-item__action">
                        <button
                          className="btn btn--outline btn--sm"
                          onClick={() => { setComposer(item.ruleId); setDraft(""); }}
                        >
                          <Icon name="send" size={12} /> Request Deal Desk exception
                        </button>
                      </div>
                    )
                  )}
                </div>
              </div>
            );
          })}
        </div>

        <button
          className="btn btn--alloy btn--lg"
          style={{ width: "100%" }}
          disabled={sendDisabled}
          onClick={onSendModal}
          title={sendDisabledReason || undefined}
        >
          <Icon name="send" size={15} />
          Send to customer
        </button>
        {sendDisabledReason && (
          <div style={{ fontSize: 11.5, color: "var(--dark-grey)", textAlign: "center", marginTop: 4 }}>
            {sendDisabledReason}
          </div>
        )}

        <button className="btn btn--outline btn--sm" style={{ width: "100%" }}>
          <Icon name="download" size={13} />
          Download PDF preview
        </button>
      </div>
    </div>
  );
};

// ---- mini document preview (compact, in the wizard) ----
const DocumentPreview = ({ deal, amendments }) => {
  const trims = window.NAMI_DATA.TRIM_TIERS;
  const t = trims[deal.trim || "premier"];

  return (
    <>
      <div className="doc-page">
        <div style={{ fontSize: 10, fontWeight: 700, color: "var(--blue-alloy)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Service Order</div>
        <h1 style={{ fontSize: 22, margin: "4px 0", fontWeight: 800 }}>Nami ML — Subscription Services</h1>
        <div className="doc-h-rule" />
        <div style={{ fontSize: 11.5, color: "var(--dark-grey)" }}>
          Between Nami ML Inc. ("Nami") and {deal.customer || "Customer"} ("Customer"). Effective as of {fmtDate(deal.startDate)}.
        </div>

        <h2>1. Subscription Term</h2>
        <div style={{ fontSize: 11 }}>
          Initial Term of <strong>{deal.termYears || 3} {(deal.termYears || 3) === 1 ? "year" : "years"}</strong> commencing {fmtDate(deal.startDate)} and ending {fmtDate(deal.endDate)}.
        </div>

        <h2>2. Services & Trim</h2>
        <div style={{ fontSize: 11 }}>
          {t.name} subscription at <strong>${(deal.cpm || t.cpmRepresentative).toFixed(2)} CPM</strong>.
          Support level: <strong style={{ textTransform: "capitalize" }}>{deal.support || "standard"}</strong>.
        </div>

        <div style={{ marginTop: 10, fontSize: 10.5 }}>
          <div style={{ fontWeight: 700, color: "var(--blue-alloy)", textTransform: "uppercase", letterSpacing: "0.05em", fontSize: 9.5, marginBottom: 4 }}>Functionality included</div>
          <ul style={{ margin: 0, paddingLeft: 16, columns: 2, columnGap: 16 }}>
            {window.NAMI_PRICING.featuresForTrim(t.key).map((f, i) => <li key={i}>{f}</li>)}
          </ul>
        </div>

        <h2>3. Volume Commitments and Fees</h2>
        <table style={{ width: "100%", fontSize: 10.5, borderCollapse: "collapse", marginTop: 8 }}>
          <thead>
            <tr style={{ background: "var(--alice-grey)" }}>
              <th style={{ padding: "6px 8px", textAlign: "left", fontSize: 9.5, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--dark-grey)" }}>Period</th>
              <th style={{ padding: "6px 8px", textAlign: "left", fontSize: 9.5, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--dark-grey)" }}>Commitment</th>
              <th style={{ padding: "6px 8px", textAlign: "right", fontSize: 9.5, textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--dark-grey)" }}>Fees</th>
            </tr>
          </thead>
          <tbody>
            {(deal.commits || [t.minCommit * 1_000_000]).map((c, i) => (
              <tr key={i} style={{ borderBottom: "1px solid var(--strokes)" }}>
                <td style={{ padding: "6px 8px" }}>Year {i + 1}</td>
                <td style={{ padding: "6px 8px" }}>{fmtImpressions(c)} impressions</td>
                <td style={{ padding: "6px 8px", textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{money((c / 1000) * (deal.cpm || t.cpmRepresentative))}</td>
              </tr>
            ))}
            {(() => {
              const { lineItems } = window.NAMI_PRICING.computeDealTcv(deal);
              const addonAndDiscount = lineItems.filter((li) => li.kind === "addon" || li.kind === "discount");
              return addonAndDiscount.map((li, i) => (
                <tr key={`adj-${i}`} style={{ borderBottom: "1px solid var(--strokes)" }}>
                  <td style={{ padding: "6px 8px", color: li.kind === "discount" ? "var(--kelp)" : "var(--blue-alloy)" }}>{li.label}</td>
                  <td></td>
                  <td style={{ padding: "6px 8px", textAlign: "right", fontVariantNumeric: "tabular-nums", color: li.kind === "discount" ? "var(--kelp)" : undefined }}>
                    {li.amount < 0 ? "−" : ""}{money(Math.abs(li.amount))}
                  </td>
                </tr>
              ));
            })()}
            <tr>
              <td style={{ padding: "8px 8px", fontWeight: 700 }}>Total Contract Value</td>
              <td></td>
              <td style={{ padding: "8px 8px", textAlign: "right", fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{money(deal.tcv || 0)}</td>
            </tr>
          </tbody>
        </table>

        <h2>4. Payment Terms</h2>
        <div style={{ fontSize: 11 }}>
          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 || "Net 30"}</strong>.
        </div>
      </div>

      {amendments.length > 0 && (
        <div className="doc-page">
          <div style={{ fontSize: 10, fontWeight: 700, color: "var(--blue-alloy)", letterSpacing: "0.1em", textTransform: "uppercase" }}>Amendment Addendum</div>
          <h1 style={{ fontSize: 22, margin: "4px 0", fontWeight: 800 }}>Modifications to Terms of Service</h1>
          <div className="doc-h-rule" />
          <div style={{ fontSize: 11, color: "var(--dark-grey)" }}>
            The following modifications to Nami's standard Terms of Service have been agreed by the parties and form part of this Agreement.
          </div>
          {amendments.map((a, i) => (
            <div key={a.id} style={{ marginTop: 14 }}>
              <div style={{ fontWeight: 700, fontSize: 11.5 }}>{i + 1}. {a.category}</div>
              <div style={{ fontSize: 10, color: "var(--dark-grey)", textTransform: "uppercase", letterSpacing: "0.05em", fontWeight: 600 }}>{a.section}</div>
              <div style={{ marginTop: 6, fontSize: 11, fontStyle: "italic", padding: "8px 12px", borderLeft: "3px solid var(--blue-alloy)", background: "var(--alice-grey)" }}>
                {a.text}
              </div>
            </div>
          ))}
        </div>
      )}
    </>
  );
};

window.StepVariants = StepVariants;
window.StepPreview = StepPreview;
