/* global React */
/* Demand — full-screen RFQ table + full-page RFQ detail with rate cards, margin intelligence, audit trail */

window.DemandScreen = function DemandScreen({ onJump }) {
  const [selectedId, setSelectedId] = React.useState(() => {
    try { return localStorage.getItem('freight.rfq') || null; } catch { return null; }
  });

  React.useEffect(() => {
    try {
      if (selectedId) localStorage.setItem('freight.rfq', selectedId);
      else localStorage.removeItem('freight.rfq');
    } catch {}
  }, [selectedId]);

  if (selectedId) {
    return <RfqDetailView id={selectedId} onBack={() => setSelectedId(null)} onSelect={setSelectedId}/>;
  }
  return <DemandListView onOpen={setSelectedId}/>;
};

/* ============================================================
   LIST VIEW — full-screen table
   ============================================================ */
function DemandListView({ onOpen }) {
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');
  const rfqs = window.RFQS;

  const filtered = React.useMemo(() => {
    let r = rfqs;
    if (filter === 'review') r = r.filter(x => x.pending);
    else if (filter === 'awaiting') r = r.filter(x => x.status === 'sent');
    else if (filter === 'won') r = r.filter(x => x.status === 'won');
    else if (filter === 'lost') r = r.filter(x => x.status === 'lost');
    else if (filter === 'negotiating') r = r.filter(x => x.status === 'negotiating');
    if (q) {
      const t = q.toLowerCase();
      r = r.filter(x => (x.id + ' ' + x.customer + ' ' + x.origin + ' ' + x.destination).toLowerCase().includes(t));
    }
    return r;
  }, [filter, q]);

  const stageOf = (s) => {
    const map = {
      new: 0, awaiting_info: 1, rates_fetched: 2, drafted: 3, sent: 4, negotiating: 5, won: 6, lost: 6,
    };
    return map[s] ?? 0;
  };

  /* Derive TEU / weight from shipmentType / weight fields, with sensible defaults */
  const teuFor = (s) => {
    if (!s) return 2; // assume 1×40ft
    const m = s.match(/(\d+)\s*[×x]\s*(\d+)\s*ft/i);
    if (!m) return 2;
    const qty = parseInt(m[1], 10);
    const size = parseInt(m[2], 10);
    return qty * (size >= 40 ? 2 : 1);
  };
  const kgFor = (w) => {
    if (!w) return 3500;
    const m = String(w).match(/([\d,]+)/);
    return m ? parseInt(m[1].replace(/,/g, ''), 10) : 3500;
  };
  const statsOf = (list) => {
    let seaCount = 0, seaTeu = 0, airCount = 0, airKg = 0;
    for (const r of list) {
      if (r.mode === 'sea') { seaCount++; seaTeu += teuFor(r.shipmentType); }
      else if (r.mode === 'air') { airCount++; airKg += kgFor(r.weight); }
    }
    return { seaCount, seaTeu, airCount, airKg, total: list.length };
  };

  const groups = {
    all:         rfqs,
    review:      rfqs.filter(r => r.pending),
    awaiting:    rfqs.filter(r => r.status === 'sent'),
    negotiating: rfqs.filter(r => r.status === 'negotiating'),
    won:         rfqs.filter(r => r.status === 'won'),
    lost:        rfqs.filter(r => r.status === 'lost'),
  };
  const stats = Object.fromEntries(Object.entries(groups).map(([k, v]) => [k, statsOf(v)]));

  const filterDefs = [
    { id: 'all',         label: 'All RFQs',          tone: 'neutral' },
    { id: 'review',      label: 'Needs review',      tone: 'agent', agent: true },
    { id: 'awaiting',    label: 'Awaiting customer', tone: 'brand' },
    { id: 'negotiating', label: 'Negotiating',       tone: 'warning' },
    { id: 'won',         label: 'Won',               tone: 'success' },
    { id: 'lost',        label: 'Lost',              tone: 'danger' },
  ];

  return (
    <div style={{ padding: '20px 24px 32px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>Demand</div>
          <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 8 }}>
            <window.Icon name="inbox" size={12}/>
            <span><strong style={{ color: 'var(--fg-1)' }}>4 emails</strong> parsed today · {rfqs.length} active RFQs · <strong style={{ color: 'var(--fg-1)' }}>{rfqs.filter(r => r.pending).length}</strong> need review</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-sm btn-secondary"><window.Icon name="download" size={12}/> Export</button>
          <button className="btn btn-sm btn-primary"><window.Icon name="plus" size={12}/> New RFQ</button>
        </div>
      </div>

      {/* Filter metric cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, minmax(0, 1fr))', gap: 8 }}>
        {filterDefs.map(f => (
          <FilterMetricCard
            key={f.id}
            def={f}
            stats={stats[f.id]}
            active={filter === f.id}
            onClick={() => setFilter(f.id)}
          />
        ))}
      </div>

      {/* Search row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>
          Showing <strong style={{ color: 'var(--fg-1)' }}>{filterDefs.find(f => f.id === filter)?.label}</strong>
        </div>
        <div style={{ flex: 1 }}/>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'white', border: '1px solid var(--n-150)', borderRadius: 8, padding: '6px 10px', width: 260 }}>
          <window.Icon name="search" size={13} color="#98A2B3"/>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search ID, customer, lane…" style={{ border: 0, outline: 0, flex: 1, fontSize: 12.5, minWidth: 0, background: 'transparent' }}/>
        </div>
      </div>

      {/* Table */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="table" style={{ tableLayout: 'fixed' }}>
          <colgroup>
            <col style={{ width: 110 }}/>
            <col style={{ width: 220 }}/>
            <col style={{ width: 240 }}/>
            <col style={{ width: 110 }}/>
            <col/>
            <col style={{ width: 150 }}/>
            <col style={{ width: 110 }}/>
            <col style={{ width: 110 }}/>
            <col style={{ width: 40 }}/>
          </colgroup>
          <thead>
            <tr>
              <th>RFQ</th>
              <th>Customer</th>
              <th>Lane</th>
              <th>Mode · Type</th>
              <th>Stage</th>
              <th>Status</th>
              <th style={{ textAlign: 'right' }}>Quote</th>
              <th>Updated</th>
              <th/>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const stage = stageOf(r.status);
              const stageLabels = ['New', 'Clarify', 'Rates', 'Draft', 'Sent', 'Negotiate', r.status === 'won' ? 'Won' : 'Lost'];
              return (
                <tr key={r.id} className="selectable" onClick={() => onOpen(r.id)} style={{ height: 56 }}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span className="mono" style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-1)' }}>{r.id}</span>
                      {r.pending && <span className="agent-dot pulse" title="Agent active"/>}
                    </div>
                  </td>
                  <td>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' }}>{r.customer}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-4)' }}>{r.cargo || '—'}</div>
                  </td>
                  <td><window.Route origin={r.origin} dest={r.destination} mode={r.mode}/></td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--fg-2)' }}>
                      <window.ModeIcon mode={r.mode} size={13} color="#667085"/>
                      <span style={{ fontSize: 12 }}>{r.shipmentType || (r.mode === 'air' ? 'Air freight' : '40ft HC')}</span>
                    </div>
                  </td>
                  <td>
                    <MicroStage step={stage} total={6} labels={stageLabels} status={r.status}/>
                  </td>
                  <td><window.StatusBadge status={r.status}/></td>
                  <td style={{ textAlign: 'right' }} className="mono tnum">
                    {r.quotedPrice ? `$${r.quotedPrice.toLocaleString()}` : <span style={{ color: 'var(--fg-4)' }}>—</span>}
                  </td>
                  <td style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{r.lastActivity}</td>
                  <td><window.Icon name="chev-r" size={14} color="#98A2B3"/></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Footer count */}
      <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{filtered.length} of {rfqs.length} RFQs</div>
    </div>
  );
}

/* ============================================================
   Filter metric card — replaces small chips with a richer overview
   ============================================================ */
function FilterMetricCard({ def, stats, active, onClick }) {
  const palette = {
    neutral: { accent: '#1659CB',  bg: 'white',                border: 'var(--n-150)',         pill: 'var(--n-50)',       pillFg: 'var(--fg-2)' },
    agent:   { accent: '#7C5CFF',  bg: 'var(--agent-50)',      border: 'var(--agent-100)',     pill: 'var(--agent-100)',  pillFg: 'var(--agent-700)' },
    brand:   { accent: '#1659CB',  bg: 'var(--brand-50)',      border: 'var(--brand-100)',     pill: 'white',             pillFg: 'var(--brand-700)' },
    warning: { accent: '#F0A105',  bg: 'var(--warning-50)',    border: 'var(--warning-100)',   pill: 'white',             pillFg: 'var(--warning-700)' },
    success: { accent: '#12B76A',  bg: 'var(--success-50)',    border: 'var(--success-100)',   pill: 'white',             pillFg: 'var(--success-700)' },
    danger:  { accent: '#D40B00',  bg: 'var(--danger-50)',     border: 'var(--danger-100)',    pill: 'white',             pillFg: 'var(--danger-700)' },
  }[def.tone] || {};

  const fmtT = (kg) => kg >= 1000 ? `${(kg / 1000).toFixed(1)}t` : `${kg}kg`;
  const hasSea = stats.seaCount > 0;
  const hasAir = stats.airCount > 0;
  const isEmpty = stats.total === 0;

  return (
    <button
      type="button"
      onClick={onClick}
      style={{
        textAlign: 'left',
        padding: '12px 12px 11px',
        borderRadius: 10,
        border: `1px solid ${active ? palette.accent : palette.border}`,
        background: active ? palette.bg : 'white',
        boxShadow: active ? `inset 3px 0 0 ${palette.accent}, var(--shadow-xs)` : 'var(--shadow-xs)',
        cursor: 'pointer',
        transition: 'all .12s',
        display: 'flex', flexDirection: 'column', gap: 6,
        minWidth: 0,
        outline: 'none',
        fontFamily: 'inherit',
      }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.borderColor = palette.accent; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.borderColor = palette.border; }}
    >
      {/* Label row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
        {def.agent && <span className="agent-dot pulse" style={{ flexShrink: 0 }}/>}
        <span style={{
          fontSize: 11, fontWeight: 600, color: 'var(--fg-3)',
          textTransform: 'uppercase', letterSpacing: '0.06em',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{def.label}</span>
      </div>

      {/* Big count */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 5 }}>
        <span className="mono tnum" style={{
          fontSize: 26, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1,
          color: active ? palette.accent : 'var(--fg-1)',
        }}>{stats.total}</span>
        <span style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>
          {stats.total === 1 ? 'RFQ' : 'RFQs'}
        </span>
      </div>

      {/* Mode breakdown */}
      {isEmpty ? (
        <div style={{ fontSize: 10.5, color: 'var(--fg-4)', height: 16, display: 'flex', alignItems: 'center' }}>—</div>
      ) : (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, alignItems: 'center', minHeight: 18 }}>
          {hasSea && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              padding: '2px 6px', borderRadius: 4,
              background: palette.pill,
              fontSize: 10.5, color: palette.pillFg, fontWeight: 600,
            }}>
              <window.Icon name="ship" size={9}/>
              <span className="mono tnum">{stats.seaCount}×</span>
              <span style={{ opacity: 0.7 }}>sea</span>
              <span className="mono tnum">{stats.seaTeu} TEU</span>
            </span>
          )}
          {hasAir && (
            <span style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              padding: '2px 6px', borderRadius: 4,
              background: palette.pill,
              fontSize: 10.5, color: palette.pillFg, fontWeight: 600,
            }}>
              <window.Icon name="plane" size={9}/>
              <span className="mono tnum">{stats.airCount}×</span>
              <span style={{ opacity: 0.7 }}>air</span>
              <span className="mono tnum">{fmtT(stats.airKg)}</span>
            </span>
          )}
        </div>
      )}

      {/* Volume stripe — visual proportion of sea vs air by count */}
      {!isEmpty && (hasSea || hasAir) && (
        <div style={{ display: 'flex', height: 3, borderRadius: 999, overflow: 'hidden', background: 'var(--n-75)' }}>
          {hasSea && <div style={{ width: `${(stats.seaCount / stats.total) * 100}%`, background: '#1659CB' }}/>}
          {hasAir && <div style={{ width: `${(stats.airCount / stats.total) * 100}%`, background: '#4ABFE5' }}/>}
        </div>
      )}
    </button>
  );
}

function MicroStage({ step, total = 6, labels, status }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{ display: 'flex', gap: 2 }}>
        {Array.from({ length: total }).map((_, i) => {
          const done = i < step;
          const current = i === step;
          const lost = status === 'lost' && i === total - 1;
          return (
            <div key={i} style={{
              width: 14, height: 4, borderRadius: 2,
              background: lost ? 'var(--danger-500)' : done ? 'var(--brand-600)' : current ? 'var(--brand-500)' : 'var(--n-100)',
            }}/>
          );
        })}
      </div>
      <span style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500 }}>{labels[step]}</span>
    </div>
  );
}

/* ============================================================
   DETAIL VIEW — full-page two-column
   ============================================================ */
function RfqDetailView({ id, onBack, onSelect }) {
  const r = window.RFQS.find(x => x.id === id) || window.RFQS[0];
  // For non-2041 RFQs, fall through to a simpler detail (mostly placeholder).
  if (r.id === 'RFQ-2041') return <Rfq2041 r={r} onBack={onBack}/>;
  if (r.id === 'RFQ-2039') return <Rfq2039 r={r} onBack={onBack}/>;
  return <RfqGeneric r={r} onBack={onBack}/>;
}

/* ============== RFQ-2041 — Full agentic rate selection ============== */
function Rfq2041({ r, onBack }) {
  const rates = window.RATE_BREAKDOWN_2041;
  const [chosen, setChosen] = React.useState(0);
  const [markup, setMarkup] = React.useState(8.0);
  const chosenRate = rates[chosen];
  const subtotal = chosenRate.lineItems.reduce((s, x) => s + x.amount, 0);
  const margin = Math.round(subtotal * (markup / 100));
  const total = subtotal + margin;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 380px', minHeight: '100%' }}>
      {/* Main column */}
      <div style={{ padding: '18px 26px 32px', display: 'flex', flexDirection: 'column', gap: 14, minWidth: 0 }}>

        {/* Header / breadcrumb */}
        <div>
          <button onClick={onBack} className="btn btn-sm btn-ghost" style={{ marginLeft: -10 }}>
            <window.Icon name="chev-l" size={13}/> All RFQs
          </button>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginTop: 4 }}>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                <span className="mono" style={{ fontSize: 12, color: 'var(--fg-3)' }}>{r.id}</span>
                <window.StatusBadge status="rates_fetched"/>
                <span className="agent-chip"><span className="agent-dot pulse"/>3 rates ready · awaiting decision</span>
              </div>
              <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>{r.customer}</div>
              <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 5, display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
                <window.Route origin={r.origin} dest={r.destination} mode={r.mode}/>
                <ShipmentBit icon="package" label={r.shipmentType}/>
                <ShipmentBit icon="gauge" label={`${r.weight} · ${r.volume}`}/>
                <ShipmentBit icon="doc" label={`Incoterms ${r.incoterms}`}/>
                <ShipmentBit icon="clock" label={`Ready: ${r.readyDate}`}/>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn btn-sm btn-secondary"><window.Icon name="paperclip" size={12}/> 3 files</button>
              <button className="btn btn-sm btn-ghost"><window.Icon name="x" size={14}/></button>
            </div>
          </div>
        </div>

        {/* Decision banner */}
        <div style={{
          background: 'linear-gradient(180deg, var(--agent-50), #FBFAFF)',
          border: '1px solid var(--agent-100)',
          borderRadius: 10,
          padding: '10px 14px',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 8, background: 'var(--agent-500)', color: 'white',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <window.Icon name="sparkles" size={14}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--agent-700)' }}>Agent recommends <strong>Maersk</strong> · contracted · 24-day transit · 12.4% margin</div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-2)', marginTop: 2, lineHeight: 1.4 }}>
              Best margin and 4 days faster than MSC. Acme's last 3 shipments tolerated ≤25-day transit; rate locks through Jun 30.
            </div>
          </div>
          <button className="btn btn-sm btn-secondary" onClick={() => setChosen(0)}>Accept</button>
        </div>

        {/* Section heading */}
        <SectionHeader title="Rate options" subtitle="3 rates · fetched 11:43 from contracted carriers + spot APIs" right={
          <button className="btn btn-sm btn-secondary"><window.Icon name="refresh" size={12}/> Refresh</button>
        }/>

        {/* Rate cards */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {rates.map((rate, i) => (
            <RateCard key={i} rate={rate} idx={i} chosen={chosen === i} onChoose={() => setChosen(i)} expandedDefault={i === 0} markup={markup}/>
          ))}
        </div>

        {/* Margin intelligence */}
        <SectionHeader title="Margin intelligence" subtitle="Calibrated against this customer's history, lane benchmark, and competitive context"/>
        <MarginIntelligenceCard
          markup={markup} setMarkup={setMarkup}
          subtotal={subtotal} margin={margin} total={total}
          chosenRate={chosenRate}
        />

        {/* Quote preview */}
        <SectionHeader title="Quote preview" subtitle={`To: ${r.email.from}`}/>
        <QuotePreviewCard r={r} rate={chosenRate} markup={markup} total={total}/>

      </div>

      {/* Right column: audit trail */}
      <AuditTrail r={r} markup={markup} chosen={chosenRate}/>
    </div>
  );
}

function ShipmentBit({ icon, label }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
      <window.Icon name={icon} size={12} color="#98A2B3"/>
      <span>{label}</span>
    </span>
  );
}

function SectionHeader({ title, subtitle, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 4 }}>
      <div>
        <div style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: '-0.005em' }}>{title}</div>
        {subtitle && <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 1 }}>{subtitle}</div>}
      </div>
      {right}
    </div>
  );
}

/* ============== Rate card ============== */
function RateCard({ rate, idx, chosen, onChoose, expandedDefault, markup }) {
  const [expanded, setExpanded] = React.useState(!!expandedDefault);
  const subtotal = rate.lineItems.reduce((s, x) => s + x.amount, 0);
  const customerPrice = Math.round(subtotal * (1 + markup / 100));
  const marginAmt = customerPrice - subtotal;
  const baseColor = window.CARRIERS.find(c => c.name === rate.carrier)?.color || '#1659CB';

  /* Group line items by category */
  const groups = {};
  rate.lineItems.forEach(li => {
    if (!groups[li.group]) groups[li.group] = [];
    groups[li.group].push(li);
  });
  const groupEntries = Object.entries(groups);

  return (
    <div className="card" style={{
      borderColor: chosen ? 'var(--brand-600)' : 'var(--n-100)',
      boxShadow: chosen ? '0 0 0 3px var(--brand-50), var(--shadow-sm)' : 'var(--shadow-xs)',
      overflow: 'hidden',
      transition: 'border-color .12s, box-shadow .12s',
    }}>
      {/* Header */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: '24px 1fr auto',
        gap: 12, alignItems: 'center',
        padding: '11px 14px',
        cursor: 'pointer',
        background: chosen ? 'linear-gradient(180deg, var(--brand-50) 0%, white 100%)' : 'white',
      }} onClick={onChoose}>
        {/* Radio */}
        <div style={{
          width: 18, height: 18, borderRadius: '50%',
          border: `2px solid ${chosen ? 'var(--brand-600)' : 'var(--n-200)'}`,
          background: chosen ? 'var(--brand-600)' : 'white',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          {chosen && <window.Icon name="check" size={10} color="white"/>}
        </div>
        {/* Carrier + meta */}
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
            <span style={{ width: 8, height: 8, borderRadius: 2, background: baseColor }}/>
            <span style={{ fontSize: 14, fontWeight: 600 }}>{rate.carrier}</span>
            {rate.badges?.map((b, j) => (
              <span key={j} className={`badge ${
                b === 'Recommended' ? 'b-agent' :
                b === 'Best price' ? 'b-success' :
                b === 'Fastest' ? 'b-blue' :
                b === 'Contracted' ? 'b-blue' :
                b === 'Own network' ? 'b-agent' :
                'b-neutral'
              }`} style={{ fontSize: 10 }}>
                {b === 'Recommended' && <window.Icon name="sparkles" size={9}/>}
                {b}
              </span>
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 3, fontSize: 11, color: 'var(--fg-3)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}><window.Icon name="clock" size={10}/>{rate.transitDays}d</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}><window.Icon name="ship" size={10}/>{rate.service || rate.vessel}</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}><window.Icon name="doc" size={10}/>Valid {rate.validity}</span>
            {rate.freeDays && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}><window.Icon name="history" size={10}/>{rate.freeDays}d free</span>}
          </div>
        </div>
        {/* Price stack */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ textAlign: 'right' }}>
            <div className="mono tnum" style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--fg-1)', lineHeight: 1.1 }}>
              ${customerPrice.toLocaleString()}
            </div>
            <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 1 }}>
              <span className="mono">${subtotal.toLocaleString()}</span> + <span style={{ color: 'var(--success-700)', fontWeight: 600 }}>{markup.toFixed(1)}%</span> = <span className="mono" style={{ color: 'var(--success-700)' }}>${marginAmt.toLocaleString()}</span>
            </div>
          </div>
          <button
            className="icon-btn"
            onClick={(e) => { e.stopPropagation(); setExpanded(!expanded); }}
            title={expanded ? 'Hide breakdown' : 'View breakdown'}
            style={{ width: 28, height: 28 }}
          >
            <window.Icon name={expanded ? 'chev-u' : 'chev-d'} size={14}/>
          </button>
        </div>
      </div>

      {/* Breakdown */}
      {expanded && (
        <div style={{ borderTop: '1px solid var(--n-100)', background: 'var(--n-25)' }}>
          {/* 2-col layout */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, padding: '12px 14px' }}>
            {groupEntries.map(([group, items], gi) => (
              <div key={gi} style={{
                padding: '4px 12px',
                borderRight: gi % 2 === 0 ? '1px dashed var(--n-150)' : 'none',
                paddingRight: gi % 2 === 0 ? 16 : 12,
                paddingLeft: gi % 2 === 1 ? 16 : 0,
              }}>
                <div style={{
                  fontSize: 10, fontWeight: 700, color: 'var(--fg-4)',
                  textTransform: 'uppercase', letterSpacing: '0.06em',
                  marginBottom: 5,
                }}>{group}</div>
                {items.map((li, j) => (
                  <div key={j} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
                    padding: '3px 0',
                    fontSize: 11.5,
                  }}>
                    <span style={{ color: 'var(--fg-2)', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {li.label}
                      {li.code && <span className="mono" style={{ color: 'var(--fg-4)', marginLeft: 4, fontSize: 9.5 }}>{li.code}</span>}
                    </span>
                    <span className="mono tnum" style={{ fontWeight: 600, color: 'var(--fg-1)', flexShrink: 0, marginLeft: 8 }}>
                      ${li.amount.toLocaleString()}
                    </span>
                  </div>
                ))}
              </div>
            ))}
          </div>

          {/* Totals strip */}
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr auto auto auto',
            alignItems: 'center', gap: 14,
            padding: '10px 14px',
            borderTop: '1px solid var(--n-150)',
            background: 'white',
          }}>
            <div style={{ fontSize: 10.5, color: 'var(--fg-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
              Customer price · live
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10, color: 'var(--fg-4)' }}>Carrier cost</div>
              <div className="mono tnum" style={{ fontSize: 13, fontWeight: 600 }}>${subtotal.toLocaleString()}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10, color: 'var(--fg-4)' }}>Margin · {markup.toFixed(1)}%</div>
              <div className="mono tnum" style={{ fontSize: 13, fontWeight: 600, color: 'var(--success-700)' }}>+${marginAmt.toLocaleString()}</div>
            </div>
            <div style={{ textAlign: 'right', paddingLeft: 8, borderLeft: '1px solid var(--n-150)' }}>
              <div style={{ fontSize: 10, color: 'var(--fg-4)' }}>Quoted</div>
              <div className="mono tnum" style={{ fontSize: 16, fontWeight: 700, color: 'var(--brand-700)', letterSpacing: '-0.01em' }}>${customerPrice.toLocaleString()}</div>
            </div>
          </div>

          {/* Notes */}
          {rate.notes && (
            <div style={{
              padding: '8px 14px 10px',
              fontSize: 11, color: 'var(--fg-3)', display: 'flex', gap: 6, lineHeight: 1.5,
              borderTop: '1px dashed var(--n-150)',
              background: 'var(--n-25)',
            }}>
              <window.Icon name="info" size={11} color="#98A2B3"/>
              <span>{rate.notes}</span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ============== Margin intelligence ============== */
function MarginIntelligenceCard({ markup, setMarkup, subtotal, margin, total, chosenRate }) {
  /* Customer history */
  const history = {
    rfqs12m: 47,
    won: 14,
    avgMarkup: 7.8,
    lastAccepted: [8.1, 7.5, 8.0, 7.9, 8.2],
    volumeBooked: 1420000,
  };
  /* Curve points — win probability vs markup */
  const curve = [
    { m: 4.0, p: 0.92 },
    { m: 5.0, p: 0.86 },
    { m: 6.0, p: 0.78 },
    { m: 7.0, p: 0.71 },
    { m: 7.5, p: 0.66 },
    { m: 8.0, p: 0.62 },
    { m: 8.5, p: 0.51 },
    { m: 9.0, p: 0.42 },
    { m: 10.0, p: 0.27 },
    { m: 11.0, p: 0.16 },
    { m: 12.0, p: 0.09 },
  ];
  const evCurve = curve.map(c => ({ m: c.m, ev: c.p * (subtotal * c.m / 100) }));
  const winProb = (mark) => {
    // linear interpolation
    if (mark <= curve[0].m) return curve[0].p;
    if (mark >= curve[curve.length - 1].m) return curve[curve.length - 1].p;
    for (let i = 0; i < curve.length - 1; i++) {
      if (mark >= curve[i].m && mark <= curve[i + 1].m) {
        const t = (mark - curve[i].m) / (curve[i + 1].m - curve[i].m);
        return curve[i].p + t * (curve[i + 1].p - curve[i].p);
      }
    }
    return 0;
  };
  const p = winProb(markup);
  const ev = p * margin;

  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.05fr 1fr' }}>
        {/* Left: editable markup + curve */}
        <div style={{ padding: 18, borderRight: '1px solid var(--n-100)', display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Markup</div>
              <span className="agent-chip"><window.Icon name="sparkles" size={10}/>Agent suggests 8.0%</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, marginTop: 8 }}>
              <input
                type="number" step="0.1" min="0" max="20"
                value={markup}
                onChange={e => setMarkup(parseFloat(e.target.value) || 0)}
                style={{
                  fontFamily: 'var(--mono)', fontSize: 30, fontWeight: 600,
                  width: 120, padding: '4px 10px', border: '1px solid var(--n-150)', borderRadius: 8,
                  outline: 0, color: 'var(--agent-700)',
                }}
              />
              <span style={{ fontSize: 22, fontWeight: 500, color: 'var(--fg-3)', marginBottom: 6 }}>%</span>
              <div style={{ flex: 1 }}/>
              <div style={{ textAlign: 'right', marginBottom: 4 }}>
                <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Margin earned</div>
                <div className="mono tnum" style={{ fontSize: 18, fontWeight: 600, color: 'var(--success-700)' }}>${margin.toLocaleString()}</div>
              </div>
            </div>
            <input type="range" className="markup" min="3" max="14" step="0.1"
              value={markup}
              style={{ '--p': `${((markup - 3) / 11) * 100}%`, marginTop: 12 }}
              onChange={e => setMarkup(parseFloat(e.target.value))}
            />
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4, fontSize: 10.5, color: 'var(--fg-4)' }}>
              <span>3%</span>
              <span style={{ color: 'var(--success-700)', fontWeight: 600 }}>↑ 8.0% optimal</span>
              <span>14%</span>
            </div>
          </div>

          {/* Win probability curve */}
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>
              Win probability vs markup
            </div>
            <WinProbCurve curve={curve} current={markup}/>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 11.5 }}>
              <span style={{ color: 'var(--fg-3)' }}>At {markup.toFixed(1)}%: <strong style={{ color: 'var(--fg-1)' }}>{Math.round(p * 100)}%</strong> win prob</span>
              <span style={{ color: 'var(--fg-3)' }}>Expected value: <strong style={{ color: 'var(--agent-700)' }}>${Math.round(ev).toLocaleString()}</strong></span>
            </div>
          </div>
        </div>

        {/* Right: customer / lane / competitive insights */}
        <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
            Calibration signals
          </div>

          {/* Customer */}
          <InsightRow icon="users" color="var(--brand-600)" bg="var(--brand-50)"
            title="Customer · Acme Logistics"
            body={<>
              Last <strong>3 markups</strong> accepted at <span className="mono">8.1%, 7.5%, 8.0%</span> (avg <strong>7.87%</strong>).
              {' '}YTD: <strong>{history.won}/{history.rfqs12m}</strong> RFQs converted, <strong>${(history.volumeBooked / 1e6).toFixed(2)}M</strong> booked.
            </>}
          />

          {/* Lane benchmark */}
          <InsightRow icon="gauge" color="var(--success-700)" bg="var(--success-50)"
            title="Lane · SIN → RTM"
            body={<>
              Freightos Baltic Index: <strong className="mono">$4,180</strong> all-in.
              {' '}Your quote at {markup}% = <strong className="mono">${total.toLocaleString()}</strong>{' '}
              (<strong style={{ color: total < 4180 ? 'var(--success-700)' : 'var(--warning-700)' }}>
                {total < 4180 ? `${Math.round((1 - total / 4180) * 100)}% below` : `+${Math.round((total / 4180 - 1) * 100)}% above`} index
              </strong>).
            </>}
          />

          {/* Competitive */}
          <InsightRow icon="flag" color="var(--warning-700)" bg="var(--warning-50)"
            title="Competitive · Kuehne+Nagel last week"
            body={<>
              Acme noted K+N quoted <strong className="mono">$4,520</strong> on parallel lane.
              {' '}You're <strong style={{ color: 'var(--success-700)' }}>${(4520 - total).toLocaleString()} cheaper</strong> at current markup.
            </>}
          />

          {/* Agent reco */}
          <div style={{
            background: 'var(--agent-50)', border: '1px solid var(--agent-100)',
            borderRadius: 10, padding: '12px 14px', display: 'flex', gap: 10,
          }}>
            <window.Icon name="sparkles" size={14} color="#7C5CFF"/>
            <div style={{ fontSize: 12, color: 'var(--agent-700)', lineHeight: 1.55 }}>
              <strong>8.0% is the local EV maximum.</strong> At 7.5% you gain only +4pp win prob but lose $19/container.
              At 8.5% prob drops 11pp — expected margin falls 18%.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function InsightRow({ icon, color, bg, title, body }) {
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <div style={{
        width: 26, height: 26, borderRadius: 7,
        background: bg, color, flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <window.Icon name={icon} size={13}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-1)', marginBottom: 2 }}>{title}</div>
        <div style={{ fontSize: 11.5, color: 'var(--fg-2)', lineHeight: 1.55 }}>{body}</div>
      </div>
    </div>
  );
}

function WinProbCurve({ curve, current }) {
  const w = 360, h = 64, padL = 4, padR = 4, padT = 8, padB = 4;
  const xMin = curve[0].m, xMax = curve[curve.length - 1].m;
  const x = (m) => padL + ((m - xMin) / (xMax - xMin)) * (w - padL - padR);
  const y = (p) => padT + (1 - p) * (h - padT - padB);
  const pts = curve.map(c => `${x(c.m).toFixed(1)},${y(c.p).toFixed(1)}`).join(' ');
  const area = `${padL},${h} ${pts} ${w - padR},${h}`;
  const cx = x(current);
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`}>
      <polygon points={area} fill="#7C5CFF" opacity="0.10"/>
      <polyline points={pts} fill="none" stroke="#7C5CFF" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      {/* Marker */}
      <line x1={cx} y1={padT - 4} x2={cx} y2={h - padB} stroke="#1659CB" strokeWidth="1.5" strokeDasharray="3 3"/>
      <circle cx={cx} cy={y(((p) => {
        // find prob at current m
        if (current <= curve[0].m) return curve[0].p;
        if (current >= curve[curve.length - 1].m) return curve[curve.length - 1].p;
        for (let i = 0; i < curve.length - 1; i++) {
          if (current >= curve[i].m && current <= curve[i + 1].m) {
            const t = (current - curve[i].m) / (curve[i + 1].m - curve[i].m);
            return curve[i].p + t * (curve[i + 1].p - curve[i].p);
          }
        }
        return 0;
      })())} r="4" fill="#1659CB" stroke="white" strokeWidth="2"/>
    </svg>
  );
}

/* ============== Quote preview ============== */
function QuotePreviewCard({ r, rate, markup, total }) {
  return (
    <div className="card" style={{ overflow: 'hidden' }}>
      <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--n-100)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <span className="agent-chip"><window.Icon name="sparkles" size={10}/>Drafted by agent</span>
        <span style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>To: <strong style={{ color: 'var(--fg-2)' }}>{r.email.from}</strong></span>
        <div style={{ flex: 1 }}/>
        <button className="btn btn-sm btn-ghost"><window.Icon name="edit" size={12}/> Edit</button>
      </div>
      <div style={{ padding: '14px 18px', fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.7 }}>
        <div style={{ fontWeight: 600, color: 'var(--fg-1)', marginBottom: 10 }}>Re: Quote needed — SG to NL — May shipment</div>
Hi Sarah,
<br/><br/>
Thanks for the additional info — locked in for May 18 ready date with All Risk cover. Our quote for 1× 40ft HC, SIN → RTM, FOB:
<br/><br/>
<div style={{ padding: '10px 14px', background: 'var(--n-25)', borderRadius: 8, fontFamily: 'var(--mono)', fontSize: 12.5, color: 'var(--fg-1)', margin: '4px 0 14px' }}>
{`  Carrier:       ${rate.carrier}
  Service:       ${rate.service || rate.vessel || '—'}
  Transit:       ${rate.transitDays} days port-to-port
  All-in rate:   $${total.toLocaleString()} USD
  Markup:        ${markup.toFixed(1)}%
  Valid until:   ${rate.validity}
  Free days:     ${rate.freeDays || 7} at destination`}
</div>
Insurance and customs clearance included as noted on attached SOA. Bill of Lading and pre-alert handled by our agent in Rotterdam.
<br/><br/>
Best,<br/>
Priya · Freight AI Operations
      </div>
      <div style={{ padding: '12px 16px', borderTop: '1px solid var(--n-100)', display: 'flex', gap: 8, background: 'var(--n-25)' }}>
        <button className="btn btn-primary"><window.Icon name="send" size={13}/> Send quote</button>
        <button className="btn btn-secondary"><window.Icon name="edit" size={13}/> Edit & review</button>
        <div style={{ flex: 1 }}/>
        <button className="btn btn-ghost btn-sm">Save draft</button>
      </div>
    </div>
  );
}

/* ============== Audit trail (right column) ============== */
function AuditTrail({ r, markup, chosen }) {
  /* Live event log — newest first */
  const events = [
    {
      kind: 'pending', icon: 'clock',
      title: 'Awaiting your decision',
      ts: 'now',
      body: <>Rate selection · margin set at <strong>{markup.toFixed(1)}%</strong></>,
    },
    {
      kind: 'agent', icon: 'sparkles',
      title: 'Margin intelligence refreshed',
      ts: '11:48',
      body: <>Pulled 12-month customer history, lane benchmark from Freightos, and 1 competitive signal. Recommended <strong>8.0%</strong>.</>,
    },
    {
      kind: 'agent', icon: 'sparkles',
      title: 'Rates fetched from 3 sources',
      ts: '11:46',
      body: <>Contracted: Maersk, MSC, ONE · Spot API: Hapag-Lloyd, CMA · Own network multi-leg explored.</>,
    },
    {
      kind: 'inbound', icon: 'mail',
      title: 'Customer replied — clarification complete',
      ts: '11:45',
      from: 'sarah.chen@acmelogistics.com',
      body: <em>"Ready date is May 18 confirmed. Let's go All Risk on the insurance, please. Thanks!"</em>,
    },
    {
      kind: 'agent', icon: 'mail-out',
      title: 'Clarification email sent',
      ts: '11:43',
      body: <>Asked for required ready date + insurance preference (All Risk vs Marine + War).</>,
    },
    {
      kind: 'agent', icon: 'sparkles',
      title: 'Parsed RFQ from inbound email',
      ts: '11:42',
      body: <>Extracted <strong>9 fields</strong> · 2 missing (ready date, insurance). Confidence avg 96%.</>,
    },
    {
      kind: 'inbound', icon: 'inbox',
      title: 'New RFQ from Acme Logistics',
      ts: '11:42',
      from: 'sarah.chen@acmelogistics.com',
      body: <em>"Quote needed — SG to NL — May shipment. 18,400 kg industrial filtration units, 24 CBM…"</em>,
    },
  ];

  const tone = (k) => {
    if (k === 'agent') return { color: 'var(--agent-700)', bg: 'var(--agent-50)', border: 'var(--agent-200)', dot: 'var(--agent-500)' };
    if (k === 'inbound') return { color: 'var(--brand-700)', bg: 'var(--brand-50)', border: 'var(--brand-200)', dot: 'var(--brand-600)' };
    if (k === 'pending') return { color: 'var(--warning-700)', bg: 'var(--warning-50)', border: 'var(--warning-200)', dot: 'var(--warning-500)' };
    return { color: 'var(--fg-2)', bg: 'var(--n-50)', border: 'var(--n-150)', dot: 'var(--n-300)' };
  };

  return (
    <aside style={{
      borderLeft: '1px solid var(--n-100)',
      background: 'var(--bg-surface)',
      display: 'flex', flexDirection: 'column', minHeight: 0,
      position: 'sticky', top: 0, alignSelf: 'flex-start', height: 'calc(100vh - 56px)',
    }}>
      <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--n-100)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <window.Icon name="history" size={14} color="#667085"/>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Audit trail</div>
          <span className="agent-dot pulse" style={{ marginLeft: 'auto' }}/>
        </div>
        <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 4 }}>
          7 events · 6 by agent · 2 emails
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '8px 14px 14px' }}>
        {/* Timeline */}
        <div style={{ position: 'relative', paddingLeft: 22 }}>
          <div style={{
            position: 'absolute', top: 10, bottom: 10, left: 9,
            width: 2, background: 'var(--n-100)',
          }}/>
          {events.map((e, i) => {
            const t = tone(e.kind);
            return (
              <div key={i} style={{ position: 'relative', paddingBottom: 14 }}>
                {/* Dot */}
                <div style={{
                  position: 'absolute', left: -22, top: 4,
                  width: 20, height: 20, borderRadius: 6,
                  background: t.bg, color: t.color,
                  border: `1.5px solid ${t.border}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <window.Icon name={e.icon} size={11}/>
                </div>
                {/* Body */}
                <div style={{
                  background: e.kind === 'pending' ? t.bg : 'white',
                  border: `1px solid ${e.kind === 'pending' ? t.border : 'var(--n-100)'}`,
                  borderRadius: 8, padding: '8px 10px',
                }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-1)', lineHeight: 1.35 }}>{e.title}</div>
                    <div style={{ fontSize: 10, color: 'var(--fg-4)', flexShrink: 0 }}>{e.ts}</div>
                  </div>
                  {e.from && (
                    <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 3 }}>
                      from <span style={{ color: 'var(--fg-2)' }}>{e.from}</span>
                    </div>
                  )}
                  <div style={{ fontSize: 11.5, color: 'var(--fg-2)', marginTop: 5, lineHeight: 1.5 }}>{e.body}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ padding: '10px 18px', borderTop: '1px solid var(--n-100)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <window.Icon name="chat" size={13} color="#7C5CFF"/>
        <span style={{ fontSize: 11.5, color: 'var(--fg-3)', flex: 1 }}>Ask the agent about this RFQ…</span>
        <span className="kbd">⌘J</span>
      </div>
    </aside>
  );
}

/* ============== RFQ-2039 — Negotiation/counter ============== */
function Rfq2039({ r, onBack }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 380px', minHeight: '100%' }}>
      <div style={{ padding: '20px 28px 40px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <button onClick={onBack} className="btn btn-sm btn-ghost" style={{ marginLeft: -10, alignSelf: 'flex-start' }}>
          <window.Icon name="chev-l" size={13}/> All RFQs
        </button>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <span className="mono" style={{ fontSize: 12, color: 'var(--fg-3)' }}>{r.id}</span>
            <window.StatusBadge status={r.status}/>
          </div>
          <div style={{ fontSize: 24, fontWeight: 600 }}>{r.customer}</div>
          <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 6, display: 'flex', alignItems: 'center', gap: 14 }}>
            <window.Route origin={r.origin} dest={r.destination} mode={r.mode}/>
            <span>· {r.shipmentType} · {r.cargo}</span>
          </div>
        </div>

        {/* Decision banner */}
        <div style={{
          background: 'linear-gradient(180deg, var(--warning-50), white)',
          border: '1px solid var(--warning-200)',
          borderRadius: 12, padding: '14px 18px',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <window.Icon name="alert" size={20} color="#F79009"/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--warning-700)' }}>Customer countered $4,920 → $4,640 (markup drops 8.0% → 6.2%)</div>
            <div style={{ fontSize: 12, color: 'var(--fg-2)', marginTop: 3 }}>Agent recommends countering at $4,755 (7.0% markup) · 71% acceptance probability.</div>
          </div>
        </div>

        {/* Three options card */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
          {[
            { title: 'Accept counter', sub: '$4,640 · 6.2% markup', prob: '100%', margin: '$272', cta: 'Accept', kind: 'secondary' },
            { title: 'Counter at 7.0%', sub: '$4,755 · 7.0% markup', prob: '71%', margin: '$311', cta: 'Send counter', kind: 'agent', recommended: true },
            { title: 'Hold at 8.0%', sub: '$4,920 · 8.0% markup', prob: '24%', margin: '$364', cta: 'Reject counter', kind: 'danger' },
          ].map((opt, i) => (
            <div key={i} className="card" style={{
              padding: 14,
              borderColor: opt.recommended ? 'var(--agent-300)' : 'var(--n-100)',
              boxShadow: opt.recommended ? '0 0 0 3px var(--agent-50)' : 'var(--shadow-xs)',
              position: 'relative',
            }}>
              {opt.recommended && (
                <div style={{ position: 'absolute', top: -8, left: 12 }}>
                  <span className="agent-chip"><window.Icon name="sparkles" size={10}/>Agent pick</span>
                </div>
              )}
              <div style={{ fontSize: 13, fontWeight: 600, marginTop: 4 }}>{opt.title}</div>
              <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>{opt.sub}</div>
              <div style={{ display: 'flex', gap: 14, marginTop: 10 }}>
                <div>
                  <div style={{ fontSize: 10, color: 'var(--fg-3)' }}>Win prob</div>
                  <div className="mono tnum" style={{ fontSize: 15, fontWeight: 600 }}>{opt.prob}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, color: 'var(--fg-3)' }}>Margin</div>
                  <div className="mono tnum" style={{ fontSize: 15, fontWeight: 600, color: 'var(--success-700)' }}>{opt.margin}</div>
                </div>
              </div>
              <button className={`btn btn-sm ${opt.kind === 'agent' ? 'btn-agent' : opt.kind === 'danger' ? 'btn-danger' : 'btn-secondary'}`} style={{ width: '100%', marginTop: 12 }}>{opt.cta}</button>
            </div>
          ))}
        </div>

        <div className="card" style={{ padding: 18 }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Customer's counter message</div>
          <div className="email-quote">
{`Hi Priya,

Thanks for the quote. We're seeing $4,640 from a competitor on this same lane and timing.
Can you match? Otherwise we'll need to look elsewhere.

— Rajesh, Bharat Industries`}
          </div>
        </div>
      </div>

      <AuditTrailMini events={[
        { kind: 'pending', icon: 'clock', title: 'Awaiting counter decision', ts: 'now', body: 'Agent recommends counter at 7.0%' },
        { kind: 'inbound', icon: 'mail', title: 'Counter offer received', ts: '6m ago', from: 'rajesh.k@bharatind.com', body: 'Asking $4,640 — references competitor quote' },
        { kind: 'agent', icon: 'mail-out', title: 'Quote sent · $4,920 (8.0%)', ts: '1d ago', body: 'Maersk via contracted rate · 28-day transit' },
        { kind: 'agent', icon: 'sparkles', title: 'Rates fetched', ts: '1d ago', body: '4 rates · NSA→JEB lane' },
        { kind: 'inbound', icon: 'inbox', title: 'RFQ from Bharat Industries', ts: '1d ago', from: 'rajesh.k@bharatind.com', body: '1× 40ft HC · CKD auto parts · CIF' },
      ]}/>
    </div>
  );
}

function AuditTrailMini({ events }) {
  const tone = (k) => {
    if (k === 'agent') return { color: 'var(--agent-700)', bg: 'var(--agent-50)', border: 'var(--agent-200)' };
    if (k === 'inbound') return { color: 'var(--brand-700)', bg: 'var(--brand-50)', border: 'var(--brand-200)' };
    if (k === 'pending') return { color: 'var(--warning-700)', bg: 'var(--warning-50)', border: 'var(--warning-200)' };
    return { color: 'var(--fg-2)', bg: 'var(--n-50)', border: 'var(--n-150)' };
  };
  return (
    <aside style={{ borderLeft: '1px solid var(--n-100)', background: 'var(--bg-surface)', padding: '14px 14px 20px 14px', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 4px 12px' }}>
        <window.Icon name="history" size={14} color="#667085"/>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Audit trail</div>
      </div>
      <div style={{ position: 'relative', paddingLeft: 22 }}>
        <div style={{ position: 'absolute', top: 10, bottom: 10, left: 9, width: 2, background: 'var(--n-100)' }}/>
        {events.map((e, i) => {
          const t = tone(e.kind);
          return (
            <div key={i} style={{ position: 'relative', paddingBottom: 14 }}>
              <div style={{ position: 'absolute', left: -22, top: 4, width: 20, height: 20, borderRadius: 6, background: t.bg, color: t.color, border: `1.5px solid ${t.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <window.Icon name={e.icon} size={11}/>
              </div>
              <div style={{ background: e.kind === 'pending' ? t.bg : 'white', border: `1px solid ${e.kind === 'pending' ? t.border : 'var(--n-100)'}`, borderRadius: 8, padding: '8px 10px' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8 }}>
                  <div style={{ fontSize: 12, fontWeight: 600 }}>{e.title}</div>
                  <div style={{ fontSize: 10, color: 'var(--fg-4)' }}>{e.ts}</div>
                </div>
                {e.from && <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 3 }}>from <span style={{ color: 'var(--fg-2)' }}>{e.from}</span></div>}
                <div style={{ fontSize: 11.5, color: 'var(--fg-2)', marginTop: 5, lineHeight: 1.5 }}>{e.body}</div>
              </div>
            </div>
          );
        })}
      </div>
    </aside>
  );
}

/* ============== RFQ generic detail (other RFQs) ============== */
function RfqGeneric({ r, onBack }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 380px', minHeight: '100%' }}>
      <div style={{ padding: '20px 28px 40px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        <button onClick={onBack} className="btn btn-sm btn-ghost" style={{ marginLeft: -10, alignSelf: 'flex-start' }}>
          <window.Icon name="chev-l" size={13}/> All RFQs
        </button>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <span className="mono" style={{ fontSize: 12, color: 'var(--fg-3)' }}>{r.id}</span>
            <window.StatusBadge status={r.status}/>
          </div>
          <div style={{ fontSize: 24, fontWeight: 600 }}>{r.customer}</div>
          <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 6 }}>
            <window.Route origin={r.origin} dest={r.destination} mode={r.mode}/>
          </div>
        </div>
        <div className="card" style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <window.Icon name="info" size={14} color="#667085"/>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Full detail view</div>
          </div>
          <div style={{ fontSize: 12.5, color: 'var(--fg-3)', lineHeight: 1.6 }}>
            Open <strong>RFQ-2041</strong> (Acme Logistics) to see the full rate-selection flow with breakdowns, margin intelligence, and audit trail.
            Or <strong>RFQ-2039</strong> (Bharat Industries) for the counter-offer flow.
          </div>
        </div>
      </div>
      <AuditTrailMini events={[
        { kind: 'agent', icon: 'sparkles', title: 'RFQ ingested', ts: r.lastActivity, body: 'Parsed from inbound email · awaiting next step.' },
      ]}/>
    </div>
  );
}
