// Read-only Prime Radiant M&A book. All decision fields are authoritative
// exports; this page formats them but never derives ENTER/PASS/HOLD/EXIT.

function MaValue({ label, value, color }) {
  return (
    <div style={{ padding: '16px 18px', background: CX.panel, border: `1px solid ${CX.line}` }}>
      <Mono style={{ display: 'block', fontSize: 9, color: CX.faint, letterSpacing: '.15em', textTransform: 'uppercase', marginBottom: 8 }}>{label}</Mono>
      <Mono style={{ fontSize: 21, color: color || CX.textHi }}>{value ?? '—'}</Mono>
    </div>
  );
}

function MaBadge({ children, tone = 'plain' }) {
  const tones = {
    green: [CX.accent, CX.accentDim], red: [CX.red, CX.redDim],
    amber: [CX.amber, CX.amberDim], blue: [CX.blue, CX.blueDim],
    plain: [CX.dim, CX.line],
  };
  const [color, bg] = tones[tone] || tones.plain;
  return <Mono style={{ fontSize: 9, color, background: bg, padding: '4px 7px', letterSpacing: '.08em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{children}</Mono>;
}

const maPct = (v, digits = 1) => v == null ? '—' : `${(Number(v) * 100).toFixed(digits)}%`;
const maMoney = (v, c) => v == null ? '—' : `${Number(v).toLocaleString(undefined, { maximumFractionDigits: 2 })}${c ? ` ${c}` : ''}`;
const maDate = (v, withTime = false) => {
  if (!v) return '—';
  const d = new Date(v);
  if (isNaN(d.getTime())) return '—';
  return new Intl.DateTimeFormat(undefined, withTime
    ? { dateStyle: 'medium', timeStyle: 'short' }
    : { year: 'numeric', month: 'short', day: '2-digit' }).format(d);
};

function MaHistory({ dealId }) {
  const rows = (window.MA?.history_by_deal || {})[dealId] || [];
  if (!rows.length) return <Mono style={{ fontSize: 10, color: CX.faint }}>No published history in the 180-day window.</Mono>;
  const steps = [];
  rows.forEach(r => {
    const label = r.latest_action && r.latest_action !== 'none'
      ? r.latest_action : (r.recommendation !== 'none' ? r.recommendation : r.participation_status);
    if (!steps.length || steps[steps.length - 1].label !== label) steps.push({ label, as_of: r.as_of });
  });
  return (
    <div style={{ display: 'flex', gap: 7, alignItems: 'center', flexWrap: 'wrap' }}>
      {steps.map((s, i) => <React.Fragment key={`${s.as_of}-${i}`}>
        {i > 0 && <Mono style={{ color: CX.faint }}>→</Mono>}
        <span title={maDate(s.as_of, true)}><MaBadge tone={s.label === 'pass' ? 'red' : s.label === 'exit' ? 'amber' : 'green'}>{s.label}</MaBadge></span>
      </React.Fragment>)}
    </div>
  );
}

function MaDealTable({ title, subtitle, deals, tone }) {
  return (
    <section style={{ marginTop: 28 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 11, gap: 12 }}>
        <div><h2 style={{ fontSize: 18, margin: 0, fontWeight: 500 }}>{title}</h2><Mono style={{ fontSize: 10, color: CX.faint }}>{subtitle}</Mono></div>
        <MaBadge tone={tone}>{deals.length}</MaBadge>
      </div>
      <div style={{ border: `1px solid ${CX.line}`, background: CX.panel, overflowX: 'auto' }}>
        {deals.length > 0 && <div style={{ minWidth: 980, display: 'grid', gridTemplateColumns: '2.1fr .8fr .8fr .75fr .75fr .65fr .65fr .65fr', gap: 14, padding: '8px 16px', borderBottom: `1px solid ${CX.line}` }}>{['DEAL / BIDDER','OFFER','MARKET','GROSS','ANNUAL.','P MODEL','P IMPL.','EDGE'].map(x => <Mono key={x} style={{ fontSize: 8, color: CX.faint, letterSpacing: '.1em' }}>{x}</Mono>)}</div>}
        {deals.length === 0 ? <Mono style={{ display: 'block', padding: 20, color: CX.faint, fontSize: 11 }}>No deals in this section.</Mono> : deals.map((d, idx) => {
          const reasons = Array.isArray(d.reason_text) ? d.reason_text : [];
          const codes = Array.isArray(d.reason_codes) ? d.reason_codes : [];
          const deadlinePast = d.resolution_deadline && new Date(d.resolution_deadline) < new Date() && d.lifecycle === 'active';
          const markOld = d.market_price_at && (Date.now() - new Date(d.market_price_at).getTime()) > 48 * 3600e3;
          return (
            <details key={d.deal_id} style={{ borderTop: idx ? `1px solid ${CX.line}` : 'none' }}>
              <summary style={{ listStyle: 'none', cursor: 'pointer', minWidth: 980, display: 'grid', gridTemplateColumns: '2.1fr .8fr .8fr .75fr .75fr .65fr .65fr .65fr', gap: 14, alignItems: 'center', padding: '14px 16px' }}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ color: CX.textHi }}>{d.target_name}</span>{d.ticker && <Mono style={{ fontSize: 9, color: CX.faint }}>{d.ticker}</Mono>}</div>
                  <Mono style={{ display: 'block', fontSize: 10, color: CX.dim, marginTop: 4 }}>{d.bidder_name || 'Bidder not supplied'}</Mono>
                  {(deadlinePast || markOld) && <Mono style={{ display: 'block', color: CX.amber, fontSize: 9, marginTop: 5 }}>{deadlinePast ? 'PAST DEADLINE' : ''}{deadlinePast && markOld ? ' · ' : ''}{markOld ? 'STALE MARK' : ''}</Mono>}
                </div>
                <Mono style={{ fontSize: 11 }}>{maMoney(d.offer_price, d.currency)}</Mono>
                <Mono style={{ fontSize: 11 }}>{maMoney(d.market_price, d.currency)}</Mono>
                <Mono style={{ fontSize: 11, color: CX.accent }}>{maPct(d.gross_spread)}</Mono>
                <Mono style={{ fontSize: 11 }}>{maPct(d.annualized_spread)}</Mono>
                <Mono style={{ fontSize: 11 }}>{maPct(d.p_model)}</Mono>
                <Mono style={{ fontSize: 11 }}>{maPct(d.p_implied)}</Mono>
                <Mono style={{ fontSize: 11, color: d.edge != null && d.edge > 0 ? CX.accent : CX.red }}>{maPct(d.edge)}</Mono>
              </summary>
              <div style={{ padding: '4px 16px 18px', borderTop: `1px solid ${CX.line}`, background: CX.bg }}>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 16, padding: '15px 0' }}>
                  <div><Mono style={{ fontSize: 9, color: CX.faint }}>STATE</Mono><div style={{ marginTop: 6 }}><MaBadge tone={tone}>{d.participation_status}</MaBadge></div></div>
                  <div><Mono style={{ fontSize: 9, color: CX.faint }}>RECOMMENDATION / ACTION</Mono><div style={{ marginTop: 6, display: 'flex', gap: 5 }}><MaBadge>{d.recommendation}</MaBadge><MaBadge>{d.latest_action}</MaBadge></div></div>
                  <div><Mono style={{ fontSize: 9, color: CX.faint }}>FORECAST AGE</Mono><Mono style={{ display: 'block', marginTop: 7, fontSize: 11 }}>{d.forecast_age_days == null ? '—' : `${d.forecast_age_days}d`}</Mono></div>
                  <div><Mono style={{ fontSize: 9, color: CX.faint }}>DEADLINE</Mono><Mono style={{ display: 'block', marginTop: 7, color: deadlinePast ? CX.amber : CX.text, fontSize: 11 }}>{maDate(d.resolution_deadline)}</Mono></div>
                  <div><Mono style={{ fontSize: 9, color: CX.faint }}>POSITION SIZE</Mono><Mono style={{ display: 'block', marginTop: 7, fontSize: 11 }}>{d.position?.size_fraction == null ? '—' : maPct(d.position.size_fraction)}</Mono></div>
                  <div><Mono style={{ fontSize: 9, color: CX.faint }}>ENTRY PRICE</Mono><Mono style={{ display: 'block', marginTop: 7, fontSize: 11 }}>{maMoney(d.position?.entry_price, d.currency)}</Mono></div>
                </div>
                <div style={{ padding: '12px 0', borderTop: `1px solid ${CX.line}` }}>
                  <Mono style={{ fontSize: 9, color: CX.faint }}>DECISION REASONS</Mono>
                  {codes.length || reasons.length ? <div style={{ marginTop: 8, display: 'flex', flexDirection: 'column', gap: 5 }}>{(codes.length ? codes : reasons).map((code, i) => <div key={i}><MaBadge tone={tone}>{code}</MaBadge>{reasons[i] && <span style={{ marginLeft: 9, color: CX.dim, fontSize: 12 }}>{reasons[i]}</span>}</div>)}</div> : <Mono style={{ display: 'block', marginTop: 7, color: CX.faint, fontSize: 10 }}>No rejection or pending reason applies.</Mono>}
                </div>
                <div style={{ paddingTop: 12, borderTop: `1px solid ${CX.line}` }}><Mono style={{ display: 'block', fontSize: 9, color: CX.faint, marginBottom: 8 }}>PUBLISHED STATE CHANGES</Mono><MaHistory dealId={d.deal_id} /></div>
              </div>
            </details>
          );
        })}
      </div>
    </section>
  );
}

function PageMA() {
  const data = window.MA || {};
  const deals = data.deals || [];
  const sync = data.latest_sync || {};
  const stale = !sync.as_of || (Date.now() - new Date(sync.as_of).getTime()) > (data.stale_after_hours || 36) * 3600e3;
  const participating = deals.filter(d => d.lifecycle === 'active' && d.participation_status === 'participating');
  const passed = deals.filter(d => d.lifecycle === 'active' && d.participation_status === 'not_participating');
  const pending = deals.filter(d => d.lifecycle === 'active' && d.participation_status === 'pending');
  const closed = deals.filter(d => d.lifecycle !== 'active' || d.participation_status === 'closed');
  return (
    <div style={{ height: '100%', overflowY: 'auto', padding: '32px 32px 64px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16, marginBottom: 24 }}>
        <div><Mono style={{ fontSize: 10, color: CX.accent, letterSpacing: '.16em' }}>PRIME RADIANT · READ ONLY</Mono><h1 style={{ fontSize: 40, fontWeight: 400, margin: '7px 0 5px' }}>M&A paper strategy</h1><span style={{ color: CX.dim, fontSize: 13 }}>Authoritative decisions and paper positions from the latest complete published snapshot.</span></div>
        <div style={{ textAlign: 'right' }}><MaBadge tone={stale ? 'amber' : 'green'}>{stale ? 'stale data' : 'current'}</MaBadge><Mono style={{ display: 'block', fontSize: 10, color: CX.faint, marginTop: 8 }}>{sync.as_of ? `snapshot ${maDate(sync.as_of, true)}` : 'No published snapshot'}</Mono></div>
      </div>
      {stale && <div style={{ padding: '12px 14px', marginBottom: 18, border: `1px solid ${CX.amber}`, background: CX.amberDim }}><Mono style={{ color: CX.amber, fontSize: 10, letterSpacing: '.08em' }}>STALE SNAPSHOT · The last successful Prime Radiant snapshot is missing or older than {data.stale_after_hours || 36} hours. The previous published state remains visible.</Mono></div>}
      {!data.available && <div style={{ padding: 20, border: `1px solid ${CX.line}`, background: CX.panel, color: CX.dim }}>No Prime Radiant snapshot has been published yet.</div>}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8 }}>
        <MaValue label="Participating" value={participating.length} color={CX.accent} /><MaValue label="Passed" value={passed.length} color={CX.red} /><MaValue label="Pending" value={pending.length} color={CX.amber} /><MaValue label="Open positions" value={data.book?.open_positions ?? 0} /><MaValue label="Gross exposure" value={maPct(data.book?.gross_exposure)} /><MaValue label="Paper P&L" value={maPct((Number(data.book?.realized_pnl_fraction || 0) + Number(data.book?.unrealized_pnl_fraction || 0)), 2)} />
      </div>
      <MaDealTable title="Participating" subtitle="Active paper positions" deals={participating} tone="green" />
      <MaDealTable title="Passed" subtitle="Valid active deals currently rejected by Prime Radiant rules" deals={passed} tone="red" />
      <MaDealTable title="Pending" subtitle="Not assessable because required forecast or price data is missing" deals={pending} tone="amber" />
      <MaDealTable title="Recently closed" subtitle="Exited, resolved, or voided deals retained in the complete snapshot" deals={closed} tone="blue" />
    </div>
  );
}

window.PageMA = PageMA;
