// T2 Falcon Admin — Contracts & Cost Management: details tabs

const { useState: useStateCD, useMemo: useMemoCD } = React;

// ---- Status pill (matches the screenshot: outline white pill for active,
//      gray for pending, red for expired). ----
const ContractStatusPill = ({ status, t }) => {
  const map = {
    active:  { cls: 'active',  label: t.cmStatusActive  || 'Active'  },
    pending: { cls: 'pending', label: t.cmStatusPending || 'Pending' },
    expired: { cls: 'expired', label: t.cmStatusExpired || 'Expired' },
  };
  const m = map[status] || map.active;
  return <span className={`cm-pill ${m.cls}`}>{m.label}</span>;
};

// ---- Tab strip — uses the global .tabs-bar / .tab classes (same as Hierarchy) ----
const ContractTabs = ({ tab, setTab, t }) => {
  const tabs = [
    { id: 'info',    label: t.cmTabInfo    || 'Contract Information' },
    { id: 'rate',    label: t.cmTabRate    || 'Rate Card' },
    { id: 'details', label: t.cmTabDetails || 'Contract Details' },
    { id: 'addons',  label: t.cmTabAddons  || 'Addons' },
  ];
  return (
    <div className="tabs-bar cm-tabs-bar">
      {tabs.map(tb => (
        <button
          key={tb.id}
          className={`tab ${tab === tb.id ? 'active' : ''}`}
          onClick={() => setTab(tb.id)}
        >
          {tb.label}
        </button>
      ))}
    </div>
  );
};

// ---- TAB 1: Contract Information ----
const formatMoney = (n) => {
  if (n === null || n === undefined) return '---';
  return new Intl.NumberFormat('en-US').format(n);
};

// ---- TAB 1: Contract Information — Hierarchy "Information" panel layout ----
// Two sections inside a card:
//   1. Basic info (Contract ID · Name · Reference ID · Status)
//   2. Dates & Value (Creation/Start/Expiration · Value · Remaining)
//
// View mode: bold value under muted label.
// Edit mode: EVERY field renders an input. Non-editable fields (Contract ID,
// Creation Date, Remaining) use a disabled grey style. Date fields use a
// calendar icon prefix so users see the same date affordance from the wizard.
const CmCalIcon = (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="4" width="18" height="18" rx="2"/>
    <line x1="16" y1="2" x2="16" y2="6"/>
    <line x1="8"  y1="2" x2="8"  y2="6"/>
    <line x1="3" y1="10" x2="21" y2="10"/>
  </svg>
);

// ---- App-wide date helpers. Canonical display format is DD-MMM-YYYY; the
// native <input type="date"> works in ISO yyyy-mm-dd, so we convert at the edge.
const CM_MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
window.cmIsoToLabel = function (iso) {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso || '');
  return m ? `${m[3]}-${CM_MONTHS[parseInt(m[2], 10) - 1]}-${m[1]}` : '';
};
window.cmLabelToIso = function (label) {
  const m = /^(\d{1,2})-([A-Za-z]{3})-(\d{4})$/.exec((label || '').trim());
  if (!m) return '';
  const mi = CM_MONTHS.findIndex(x => x.toLowerCase() === m[2].toLowerCase());
  if (mi < 0) return '';
  return `${m[3]}-${String(mi + 1).padStart(2, '0')}-${String(parseInt(m[1], 10)).padStart(2, '0')}`;
};

// ---- Reusable date field: DISPLAYS dd-mmm-yyyy and opens a Falcon-themed
// (teal) calendar popup, reading/writing values in DD-MMM-YYYY.
const CM_MONTH_FULL = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const CM_WEEKDAYS = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
const cmStartOfDay = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; };
const cmSameDay = (a, b) => !!(a && b) && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
const cmChevron = (dir) => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <polyline points={dir === 'prev' ? '15 18 9 12 15 6' : '9 18 15 12 9 6'} />
  </svg>
);
const CmDateField = ({ value, onChange, min, placeholder, disabled }) => {
  const ref = React.useRef(null);
  const [open, setOpen] = React.useState(false);
  const [up, setUp] = React.useState(false);
  const selDate = React.useMemo(() => { const iso = window.cmLabelToIso(value); return iso ? new Date(iso + 'T00:00:00') : null; }, [value]);
  const minDate = React.useMemo(() => { const iso = window.cmLabelToIso(min); return iso ? new Date(iso + 'T00:00:00') : null; }, [min]);
  const [view, setView] = React.useState(() => selDate || new Date());
  React.useEffect(() => { if (open) setView(selDate || new Date()); }, [open]);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);
  React.useEffect(() => { if (!open || !ref.current) return; const r = ref.current.getBoundingClientRect(); setUp((window.innerHeight - r.bottom) < 360); }, [open]);

  const toggle = () => { if (!disabled) setOpen((v) => !v); };
  const y = view.getFullYear(), m = view.getMonth();
  const firstDow = new Date(y, m, 1).getDay();
  const daysInMonth = new Date(y, m + 1, 0).getDate();
  const minDay = minDate ? cmStartOfDay(minDate) : null;
  const today = cmStartOfDay(new Date());
  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(y, m, d));
  while (cells.length % 7 !== 0) cells.push(null);
  const pick = (d) => {
    onChange && onChange(window.cmIsoToLabel(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`));
    setOpen(false);
  };

  return (
    <div className="cm-datefield-wrap" ref={ref}>
      <div
        className={`cm-datefield${disabled ? ' is-disabled' : ''}${open ? ' is-open' : ''}`}
        onClick={toggle}
        role="button"
        tabIndex={disabled ? -1 : 0}
        onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); } }}
      >
        <span className="cm-datefield-cal">{CmCalIcon}</span>
        <span className={`cm-datefield-text${value ? '' : ' is-placeholder'}`}>{value || placeholder || 'dd-mmm-yyyy'}</span>
      </div>
      {open && !disabled && (
        <div className={`dp-pop cm-dp-pop ${up ? 'up' : ''}`}>
          <div className="dp-head">
            <button type="button" className="dp-nav" onClick={() => setView(new Date(y, m - 1, 1))} aria-label="Previous month">{cmChevron('prev')}</button>
            <div className="dp-title">{CM_MONTH_FULL[m]} {y}</div>
            <button type="button" className="dp-nav" onClick={() => setView(new Date(y, m + 1, 1))} aria-label="Next month">{cmChevron('next')}</button>
          </div>
          <div className="dp-dow">{CM_WEEKDAYS.map((d, i) => <span key={i}>{d}</span>)}</div>
          <div className="dp-grid">
            {cells.map((d, i) => {
              if (!d) return <span key={i} className="dp-cell empty" />;
              const dis = !!(minDay && cmStartOfDay(d) < minDay);
              const sel = cmSameDay(d, selDate);
              const isToday = cmSameDay(d, today);
              return (
                <button key={i} type="button" disabled={dis} className={`dp-cell ${dis ? 'disabled' : ''} ${sel ? 'selected' : ''} ${isToday ? 'today' : ''}`} onClick={() => { if (!dis) pick(d); }}>
                  {d.getDate()}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};
window.CmDateField = CmDateField;

const CmInfoField = ({ label, value, onChange, readonly, editing, options, prefixIcon, type }) => {
  // In edit mode: editable fields render an input/select. Non-editable fields
  // (Contract ID, Creation Date, Remaining) render a DISABLED input with the
  // same shape — just greyed out — so the layout stays consistent.
  // In view mode: everything is plain text (with optional prefix icon).
  return (
    <div className="ac-field info-field">
      <label className="ac-label info-field-label">{label}</label>
      {editing ? (
        readonly ? (
          <input
            className="ac-input is-disabled"
            value={value || ''}
            disabled
            readOnly
          />
        ) : type === 'date' ? (
          <CmDateField value={value} onChange={(v) => onChange && onChange(v)} placeholder="dd-mmm-yyyy" />
        ) : options ? (
          window.TplDropdown ? (
            <window.TplDropdown
              value={value || ''}
              onChange={(v) => onChange && onChange(v)}
              options={options}
            />
          ) : (
            <select className="ac-input" value={value || ''} onChange={(e) => onChange && onChange(e.target.value)}>
              {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          )
        ) : prefixIcon ? (
          <div className="cm-info-prefix-wrap">
            <span className="cm-info-prefix-icon">{prefixIcon}</span>
            <input
              className="ac-input cm-info-prefix-input"
              type={type || 'text'}
              value={value || ''}
              onChange={(e) => onChange && onChange(e.target.value)}
            />
          </div>
        ) : (
          <input
            className="ac-input"
            type={type || 'text'}
            value={value || ''}
            onChange={(e) => onChange && onChange(e.target.value)}
          />
        )
      ) : (
        prefixIcon ? (
          <span className="info-field-value cm-info-prefix-view">
            <span className="cm-info-prefix-icon">{prefixIcon}</span>
            <span>{value || '—'}</span>
          </span>
        ) : (
          <span className="info-field-value">{value || '—'}</span>
        )
      )}
    </div>
  );
};

const TabContractInfo = ({ contract, t, editing, draft, setDraft }) => {
  const get = (key, fallback) => (draft && draft[key] !== undefined) ? draft[key] : (contract[key] !== undefined ? contract[key] : fallback);
  const set = (key, v) => setDraft && setDraft({ ...(draft || {}), [key]: v });

  const statusLabel = ({
    active:  t.cmStatusActive  || 'Active',
    pending: t.cmStatusPending || 'Pending',
    expired: t.cmStatusExpired || 'Expired',
  })[get('status', 'active')] || '';

  return (
    <div className={`info-panel ${editing ? 'is-editing' : ''}`}>
      <div className="info-panel-header">{t.information || 'Information'}</div>
      <div className="info-panel-body">
        {/* Top section — basic info */}
        <div className="info-grid info-grid-top">
          <CmInfoField
            label={t.cmContractId || 'Contract ID'}
            value={get('contractId')}
            readonly editing={editing}
          />
          <CmInfoField
            label={t.cmContractName || 'Contract Name'}
            value={get('name')}
            editing={editing}
            onChange={(v) => set('name', v)}
          />
          <CmInfoField
            label={t.cmReferenceId || 'Reference ID'}
            value={get('farabiReferenceId', get('contractId'))}
            editing={editing}
            onChange={(v) => set('farabiReferenceId', v)}
          />
          <CmInfoField
            label={t.cmStatus || 'Status'}
            value={statusLabel}
            readonly editing={editing}
          />
        </div>
        {/* Bottom section — dates & value */}
        <div className="info-grid info-grid-bottom">
          <div className="info-section-title">{t.cmDatesValue || 'Dates & Value'}</div>
          <CmInfoField
            label={t.cmCreationDate || 'Creation Date'}
            value={get('creationDate')}
            readonly editing={editing}
          />
          <CmInfoField
            label={t.cmStartDate || 'Start Date'}
            value={get('startDate')}
            editing={editing}
            onChange={(v) => set('startDate', v)}
            type="date"
          />
          <CmInfoField
            label={t.cmExpirationDate || 'Expiration Date'}
            value={get('expirationDate')}
            editing={editing}
            onChange={(v) => set('expirationDate', v)}
            type="date"
          />
          <CmInfoField
            label={t.cmValue || 'Value'}
            value={(draft && draft.value !== undefined) ? draft.value : formatMoney(contract.value)}
            editing={editing}
            onChange={(v) => set('value', v)}
            prefixIcon={<IcRiyal size={13} />}
          />
          <CmInfoField
            label={t.cmRemaining || 'Remaining'}
            value={contract.remaining === null ? 'NA' : formatMoney(contract.remaining)}
            readonly editing={editing}
          />
        </div>
      </div>
    </div>
  );
};

// ---- TAB 2: Rate Card — uses Hierarchy's .apps-panel + .apps-table chrome ----
const TabRateCard = ({ contract, t, editing, readOnly, draft, setDraft }) => {
  const rows = (draft && draft.rateCard) || contract.rateCard || window.seedRateCard;
  const unitOpts = ['One KSA Transaction', 'One KSA Second', 'One API Call', 'One International Transaction', 'Per Minute', 'Per Message'];
  const update = (idx, patch) => {
    const next = rows.map((r, i) => i === idx ? { ...r, ...patch } : r);
    setDraft && setDraft({ ...(draft || {}), rateCard: next });
  };
  const [page, setPage] = useStateCD(1);
  const [pageSize, setPageSize] = useStateCD(20);
  const visible = rows.slice((page - 1) * pageSize, page * pageSize);
  return (
    <div className="apps-panel">
      <div className="apps-panel-header">{t.cmTabRate || 'Rate Card'}</div>
      <div className="table-scroll">
        <table className="apps-table">
          <thead>
            <tr>
              <th>{t.cmRcName  || 'Name'}</th>
              <th>{t.cmRcUnit  || 'Price Unit'}</th>
              <th>{t.cmRcValue || 'Price Value'}</th>
            </tr>
          </thead>
          <tbody>
            {visible.map((r, idx) => (
              <tr key={r.name}>
                <td className="name-cell">{r.name}</td>
                <td>
                  {editing ? (
                    window.TplDropdown ? (
                      <window.TplDropdown
                        value={r.unit}
                        onChange={(v) => update((page - 1) * pageSize + idx, { unit: v })}
                        options={unitOpts.map(u => ({ value: u, label: u }))}
                      />
                    ) : (
                      <select className="cm-edit-select" value={r.unit} onChange={(e) => update((page - 1) * pageSize + idx, { unit: e.target.value })}>
                        {unitOpts.map(u => <option key={u} value={u}>{u}</option>)}
                      </select>
                    )
                  ) : (
                    <span className="cm-edit-readonly">{r.unit}</span>
                  )}
                </td>
                <td>
                  {editing ? (
                    <span className="cm-price-cell">
                      <IcRiyal size={13} />
                      <input
                        className="cm-edit-input cm-price-input"
                        type="text"
                        value={(r.value || '').replace(/\s*SAR\s*$/i, '').trim()}
                        onChange={(e) => update((page - 1) * pageSize + idx, { value: window.cmNumDecimal(e.target.value) })}
                      />
                    </span>
                  ) : (
                    /* View mode — plain text, no field box (matches Price Unit) */
                    <span className="cm-money">
                      <IcRiyal size={13} /> {(r.value || '').replace(/\s*SAR\s*$/i, '').trim()}
                    </span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <TablePagination
        total={rows.length}
        page={page}
        pageSize={pageSize}
        onPageChange={setPage}
        onPageSizeChange={(n) => { setPageSize(n); setPage(1); }}
        t={t}
      />
    </div>
  );
};

// ---- TAB 3: Contract Details (per channel) ----
const TabContractDetails = ({ contract, t, editing, readOnly, draft, setDraft }) => {
  const channels = ['Voice', 'WhatsApp', 'AI Service'];
  const [channel, setChannel] = useStateCD('Voice');
  const overrides = (draft && draft.detailsOverrides) || contract.detailsOverrides || {};
  const baseData = window.seedContractDetails[channel];
  const data = overrides[channel] || baseData;
  const setOverride = (next) => {
    setDraft && setDraft({ ...(draft || {}), detailsOverrides: { ...overrides, [channel]: next } });
  };
  const setMatrixCell = (rIdx, cIdx, v) => {
    const nextRows = data.rows.map((r, i) => i === rIdx ? { ...r, values: r.values.map((vv, j) => j === cIdx ? v : vv) } : r);
    setOverride({ ...data, rows: nextRows });
  };
  const [page, setPage] = useStateCD(1);
  const [pageSize, setPageSize] = useStateCD(20);
  // Reset to page 1 if the row count drops (e.g. channel change)
  const allRows = data.rows || [];
  const visibleRows = allRows.slice((page - 1) * pageSize, page * pageSize);

  return (
    <div className="apps-panel">
      <div className="apps-panel-header">{t.cmTabDetails || 'Contract Details'}</div>
      <div className="cm-details-control-row">
        <div className="cm-details-control">
          <div className="lbl">{t.cmCurrency || 'Currency'}</div>
          {/* Currency is fixed (SAR) — shown as plain text in BOTH view and edit
              modes; no radio button in edit mode (per request). */}
          <div className="info-field-value">{data.currency}</div>
        </div>
        <div className="cm-details-control">
          <div className="lbl">{t.cmApplication || 'Application'}</div>
          {window.TplDropdown ? (
            <window.TplDropdown
              value={data.application}
              onChange={(v) => setOverride({ ...data, application: v })}
              options={[
                'Basic Send Transaction Application',
                'Premium Send Transaction Application',
                'Notification Application',
                'Marketing Campaign Application',
                'OTP Verification Application',
                'Customer Support Application',
              ].map(a => ({ value: a, label: a }))}
            />
          ) : (
            <select
              className="cm-edit-select"
              value={data.application}
              onChange={(e) => setOverride({ ...data, application: e.target.value })}
            >
              {['Basic Send Transaction Application','Premium Send Transaction Application','Notification Application','Marketing Campaign Application','OTP Verification Application','Customer Support Application'].map(a => <option key={a} value={a}>{a}</option>)}
            </select>
          )}
        </div>
        <div className="cm-details-control">
          <div className="lbl">{t.cmCommChannel || 'CommChannel'}</div>
          {window.TplDropdown ? (
            <window.TplDropdown
              value={channel}
              onChange={(v) => setChannel(v)}
              options={channels.map(c => ({ value: c, label: c }))}
            />
          ) : (
            <select className="cm-edit-select" value={channel} onChange={(e) => setChannel(e.target.value)}>
              {channels.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          )}
        </div>
      </div>

      {data.kind === 'matrix' ? (
        <div className="table-scroll">
          <table className="apps-table cm-matrix">
            <thead>
              <tr>
                <th>{t.cmPriorityType || 'Priority/Type'}</th>
                {data.columns.map(c => <th key={c}>{c}</th>)}
              </tr>
            </thead>
            <tbody>
              {visibleRows.map((r, idx) => {
                const rIdx = (page - 1) * pageSize + idx;
                return (
                  <tr key={r.label}>
                    <td className="name-cell">{r.label}</td>
                    {r.values.map((v, cIdx) => (
                      <td key={cIdx}>
                        <input
                          type="text"
                          className={`cm-cell-input ${editing ? '' : 'is-view'}`}
                          value={String(v)}
                          title={String(v)}
                          readOnly={!editing}
                          inputMode="decimal"
                          onChange={editing ? ((e) => setMatrixCell(rIdx, cIdx, window.cmNumDecimal(e.target.value))) : undefined}
                        />
                      </td>
                    ))}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="table-scroll">
          <table className="apps-table">
            <tbody>
              {visibleRows.map((r, idx) => {
                const i = (page - 1) * pageSize + idx;
                return (
                  <tr key={r.label}>
                    <td className="name-cell" style={{ width: 240 }}>{r.label}</td>
                    <td>
                      <input
                        type="text"
                        className={`cm-cell-input ${editing ? '' : 'is-view'}`}
                        value={String(r.value)}
                        readOnly={!editing}
                        onChange={editing ? ((e) => {
                          const nextRows = data.rows.map((rr, j) => j === i ? { ...rr, value: e.target.value } : rr);
                          setOverride({ ...data, rows: nextRows });
                        }) : undefined}
                      />
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
      <TablePagination
        total={allRows.length}
        page={page}
        pageSize={pageSize}
        onPageChange={setPage}
        onPageSizeChange={(n) => { setPageSize(n); setPage(1); }}
        t={t}
      />
    </div>
  );
};

// ---- TAB 4: Addons — uses Hierarchy's .apps-panel chrome ----
// View mode renders the values as information (label + bold value, no box).
// Edit mode swaps them for inputs prefixed with the Saudi Riyal glyph.
const CmAddonBlock = ({ title, items, editing, onChange }) => {
  return (
    <div className="apps-panel cm-addon-panel">
      <div className="apps-panel-header">{title}</div>
      <div className="cm-addon-panel-body">
        {(items || []).map((it, idx) => {
          // 'amount' is used by entitlements, 'value' by rate-card. The
          // original (contracted) figure is stored under .original and shown
          // as a faint /N suffix so users can see the baseline at a glance.
          const isRateCard = it.value !== undefined && it.amount === undefined;
          const value = isRateCard ? (it.value || '') : (it.amount || '');
          const original = it.original || '';
          const onValueChange = (v) => {
            onChange && onChange(idx, isRateCard ? { ...it, value: v } : { ...it, amount: v });
          };
          return (
            <div key={it.id || idx} className="cm-addon-section-field">
              <label className="ac-label info-field-label">{it.name || 'Voice/Sender Name'}</label>
              {editing ? (
                original ? (
                  // Entitlement (consumed/offered): TWO separate fields. The
                  // consumed value (e.g. 50,000) is FIXED and DISABLED; only the
                  // OFFERED value after the "/" (e.g. 120,000) is editable.
                  <div className="cm-addon-section-pair">
                    <div className="cm-addon-section-input is-disabled">
                      <span className="cm-addon-section-currency"><IcRiyal size={14} /></span>
                      <input type="text" value={value} disabled readOnly aria-label="consumed (fixed)" />
                    </div>
                    <span className="cm-addon-section-slash">/</span>
                    <div className="cm-addon-section-input">
                      <span className="cm-addon-section-currency"><IcRiyal size={14} /></span>
                      <input
                        type="text"
                        value={original}
                        aria-label="offered"
                        onChange={(e) => onChange && onChange(idx, { ...it, original: window.cmFmtThousands(e.target.value) })}
                      />
                    </div>
                  </div>
                ) : (
                  // Rate card (single value, no consumed/offered split)
                  <div className="cm-addon-section-input">
                    <span className="cm-addon-section-currency"><IcRiyal size={14} /></span>
                    <input
                      type="text"
                      value={value}
                      onChange={(e) => onValueChange(window.cmFmtThousands(e.target.value))}
                    />
                  </div>
                )
              ) : (
                <div className="cm-addon-section-value">
                  <span className="cm-addon-section-currency"><IcRiyal size={14} /></span>
                  <span className="num">{value}</span>
                  {original && <span className="cm-addon-section-original">/{original}</span>}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

const TabAddons = ({ contract, t, editing, draft, setDraft }) => {
  const entitlements = (draft && draft.addons)           || contract.addons          || window.seedAddons.entitlements;
  const rateCard     = (draft && draft.addonsRateCard)   || contract.addonsRateCard  || window.seedAddons.rateCard;
  const updEnt = (idx, next) => setDraft && setDraft({ ...(draft || {}), addons: entitlements.map((it, i) => i === idx ? next : it) });
  const updRC  = (idx, next) => setDraft && setDraft({ ...(draft || {}), addonsRateCard: rateCard.map((it, i) => i === idx ? next : it) });

  return (
    <div className="cm-addons-stack">
      <CmAddonBlock
        title={t.cmAddons || 'Addons'}
        items={entitlements}
        editing={editing}
        onChange={updEnt}
      />
      <CmAddonBlock
        title={t.cmAddonsRateCard || 'Addons Rate Card'}
        items={rateCard}
        editing={editing}
        onChange={updRC}
      />
    </div>
  );
};

// ---- Wrapper: contract details page (4 tabs + View/Edit mode) ----
// Layout mirrors Hierarchy: tabs at the top of the content panel, then a
// header row with client avatar + name on the left and Edit / Cancel+Save on
// the right. The Edit button is hidden in Falcon view (read-only perspective).
const ContractDetailsPage = ({ contract, scopeNode, onBack, t, lang, pushToast, readOnly }) => {
  const [tab, setTab] = useStateCD('info');
  const [mode, setMode] = useStateCD('view'); // 'view' | 'edit'
  const [draft, setDraft] = useStateCD(null);

  const startEdit = () => { setDraft({}); setMode('edit'); };
  const cancelEdit = () => { setDraft(null); setMode('view'); };
  const saveEdit = () => {
    if (draft) Object.assign(contract, draft);
    setDraft(null);
    setMode('view');
    pushToast && pushToast(t.cmContractSaved || 'Contract updated ✓');
  };

  const editing = mode === 'edit';

  const ScopeAvatar = () => {
    if (!scopeNode) return null;
    if (scopeNode.id === 'falcon' || scopeNode.type === 'root') return <span className="node-avatar"><IcFalcon size={18} /></span>;
    if (scopeNode.type === 'client') return <BrandLogo brand={scopeNode.brand} size={32} />;
    return (
      <span className="node-avatar" style={{ background: '#0d3f44', color: 'white' }}>
        <span style={{ fontSize: 12, fontWeight: 700 }}>{(scopeNode.name || 'N').slice(0, 1)}</span>
      </span>
    );
  };

  return (
    <>
      <ContractTabs tab={tab} setTab={setTab} t={t} />
      <div className="content-body">
        <div className="node-header">
          <div className={`node-title ${scopeNode && (scopeNode.id === 'falcon' || scopeNode.type === 'root') ? 'falcon' : ''}`}>
            <ScopeAvatar />
            <span>{scopeNode ? scopeNode.name : ''}</span>
          </div>
          <div className="node-actions">
            <button className="btn btn-secondary" onClick={onBack}>
              <IcArrowLeft size={12} stroke={1.7} /> {t.cmBackToList || 'Back to list'}
            </button>
            {!readOnly && !editing && (
              <button type="button" className="btn btn-primary" onClick={startEdit}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                {t.cmEdit || 'Edit'}
              </button>
            )}
            {!readOnly && editing && (
              <>
                <button type="button" className="btn btn-secondary" onClick={cancelEdit}>{t.cancel || 'Cancel'}</button>
                <button type="button" className="btn btn-primary" onClick={saveEdit}>{t.save || 'Save'}</button>
              </>
            )}
          </div>
        </div>

        <div className="cm-tab-body">
          {tab === 'info'    && <TabContractInfo     contract={contract} t={t} editing={editing} draft={draft} setDraft={setDraft} />}
          {tab === 'rate'    && <TabRateCard          contract={contract} t={t} editing={editing} readOnly={readOnly} draft={draft} setDraft={setDraft} />}
          {tab === 'details' && <TabContractDetails   contract={contract} t={t} editing={editing} readOnly={readOnly} draft={draft} setDraft={setDraft} />}
          {tab === 'addons'  && <TabAddons            contract={contract} t={t} editing={editing} draft={draft} setDraft={setDraft} />}
        </div>
      </div>
    </>
  );
};

Object.assign(window, {
  ContractStatusPill,
  ContractTabs,
  TabContractInfo,
  TabRateCard,
  TabContractDetails,
  TabAddons,
  ContractDetailsPage,
});
