/* global React */
/* Supply — rate matrix colored by Lane Health Score; drill-down with action recommendations */

window.SupplyScreen = function SupplyScreen() {
  const [mode, setMode] = React.useState('air');
  const [drawer, setDrawer] = React.useState(null);
  const [showRenegotiateModal, setShowRenegotiateModal] = React.useState(false);
  const [viewBy, setViewBy] = React.useState('health'); // health | rate
  const [showAttentionOnly, setShowAttentionOnly] = React.useState(false);

  const modeCfg = window.MATRIX_BY_MODE[mode] || window.MATRIX_BY_MODE.sea;
  const O = modeCfg.origins;
  const D = modeCfg.dests;
  const H = modeCfg.health;

  /* Health → color */
  const healthColor = (score) => {
    if (score == null) return null;
    if (score >= 75) return { bg: '#D1FADF', fg: '#027A48', label: 'Healthy' };
    if (score >= 60) return { bg: '#DCFCE7', fg: '#16A34A', label: 'Healthy' };
    if (score >= 45) return { bg: '#FEF0C7', fg: '#B54708', label: 'Moderate' };
    if (score >= 30) return { bg: '#FED7AA', fg: '#C2410C', label: 'Weak' };
    return { bg: '#FECACA', fg: '#B42318', label: 'Critical' };
  };
  const rateColor = (bench) => {
    if (bench == null) return null;
    if (bench < -0.6) return { bg: '#D1FADF', fg: '#027A48' };
    if (bench < -0.3) return { bg: '#DCFCE7', fg: '#027A48' };
    if (bench < 0)    return { bg: '#ECFDF3', fg: '#027A48' };
    if (bench < 0.3)  return { bg: '#FEF0C7', fg: '#B54708' };
    if (bench < 0.6)  return { bg: '#FED7AA', fg: '#C2410C' };
    return { bg: '#FECACA', fg: '#B42318' };
  };

  /* Critical lanes count */
  const criticalCount = H.flat().filter(c => c && c.composite < 35).length;
  const moderateCount = H.flat().filter(c => c && c.composite >= 35 && c.composite < 60).length;
  const healthyCount  = H.flat().filter(c => c && c.composite >= 60).length;

  const sel = drawer || { row: 0, col: 0 };

  return (
    <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.02em' }}>Supply</div>
          <div style={{ fontSize: 13, color: 'var(--fg-3)', marginTop: 4, display: 'flex', alignItems: 'center', gap: 8 }}>
            <window.Icon name="sparkles" size={12} color="#7C5CFF"/>
            <span>Agent computed health scores from <strong style={{ color: 'var(--fg-1)' }}>rate, carrier depth, capacity vs demand</strong> · refreshed 4m ago</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-sm btn-secondary"><window.Icon name="refresh" size={12}/> Refresh</button>
          <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}/> Fetch rates</button>
        </div>
      </div>

      {/* Filter strip */}
      <div className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em', marginRight: 4 }}>Mode</div>
        <div style={{ display: 'flex', gap: 4, padding: 2, background: 'var(--n-75)', borderRadius: 8 }}>
          {['air', 'sea', 'multimodal'].map(m => (
            <button key={m} onClick={() => { setMode(m); setDrawer(null); }}
              className="chip" style={{
                border: 0, background: mode === m ? 'white' : 'transparent',
                boxShadow: mode === m ? 'var(--shadow-xs)' : 'none',
                textTransform: 'capitalize',
              }}>
              <window.Icon name={m === 'air' ? 'plane' : m === 'sea' ? 'ship' : 'route'} size={12}/>
              {m}
            </button>
          ))}
        </div>

        <div className="divider-v"/>

        <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' }}>View by</div>
        <div style={{ display: 'flex', gap: 4, padding: 2, background: 'var(--n-75)', borderRadius: 8 }}>
          {[
            { id: 'health', label: 'Health Score', icon: 'gauge' },
            { id: 'rate', label: 'Rate vs Market', icon: 'trend-down' },
          ].map(v => (
            <button key={v.id} onClick={() => setViewBy(v.id)}
              className="chip" style={{
                border: 0, background: viewBy === v.id ? 'white' : 'transparent',
                boxShadow: viewBy === v.id ? 'var(--shadow-xs)' : 'none',
              }}>
              <window.Icon name={v.icon} size={12}/>
              {v.label}
            </button>
          ))}
        </div>

        <div className="divider-v"/>

        <button className={`chip ${showAttentionOnly ? 'active' : ''}`} onClick={() => setShowAttentionOnly(s => !s)}>
          <window.Icon name="alert" size={11}/> Needs attention <span className="chip-count">{criticalCount}</span>
        </button>

        <div style={{ flex: 1 }}/>

        {/* Legend */}
        {viewBy === 'health' ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11.5, color: 'var(--fg-3)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 10, borderRadius: 2, background: '#D1FADF' }}/> Healthy</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 10, borderRadius: 2, background: '#FEF0C7' }}/> Moderate</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 10, borderRadius: 2, background: '#FED7AA' }}/> Weak</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 10, borderRadius: 2, background: '#FECACA' }}/> Critical</span>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 11.5, color: 'var(--fg-3)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 10, borderRadius: 2, background: '#D1FADF' }}/> Below benchmark</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 10, borderRadius: 2, background: '#FEF0C7' }}/> At market</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 12, height: 10, borderRadius: 2, background: '#FECACA' }}/> Above market</span>
          </div>
        )}
      </div>

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        <div className="kpi">
          <div className="kpi-label">Healthy lanes</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <div className="kpi-value tnum" style={{ color: 'var(--success-700)', fontSize: 22 }}>{healthyCount}</div>
            <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>of {healthyCount + moderateCount + criticalCount}</div>
          </div>
          <HealthBar healthy={healthyCount} moderate={moderateCount} critical={criticalCount}/>
        </div>
        <div className="kpi">
          <div className="kpi-label">Critical · need action</div>
          <div className="kpi-value tnum" style={{ color: 'var(--danger-700)', fontSize: 22, display: 'flex', alignItems: 'center', gap: 6 }}>
            <span className="agent-dot pulse" style={{ background: 'var(--danger-500)', boxShadow: '0 0 0 0 rgba(240,68,56,.45)' }}/>
            {criticalCount}
          </div>
          <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Agent drafted outreach for top 3</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Avg rate vs benchmark</div>
          <div className="kpi-value tnum" style={{ color: 'var(--success-700)', fontSize: 22 }}>-4.2%</div>
          <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{healthyCount + moderateCount + criticalCount - 9} of {healthyCount + moderateCount + criticalCount} below market</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Rates Expiring in 2w</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
            <div className="kpi-value tnum" style={{ color: 'var(--warning-700)', fontSize: 22 }}>1,240</div>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--warning-700)' }}>TEU</div>
            <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>demand affected</div>
          </div>
          <ExpiringBar sea={840} air={400}/>
        </div>
      </div>

      {/* Matrix */}
      <div className="card" style={{ padding: 16, overflow: 'auto' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <div>
            <div style={{ fontSize: 13.5, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 }}>
              <window.Icon name={modeCfg.icon} size={14} color={mode === 'air' ? '#1659CB' : '#0F1E37'}/>
              Rate matrix · {modeCfg.rateLabel}
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>
              Cell shows best contracted/spot rate, top {mode === 'air' ? 'airline' : 'carrier'}, and Lane Score.
              {' '}
              Heat colored by {viewBy === 'health' ? 'composite Lane Score (rate 30% · supply 30% · demand 40%)' : 'rate vs market benchmark'}
            </div>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{O.length} origins × {D.length} destinations</div>
        </div>

        {/* X axis label */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginBottom: 6 }}>
          <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{modeCfg.originLabel}</span>
          <window.Icon name="arrow-r" size={11} color="#98A2B3"/>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: `24px 120px repeat(${O.length}, minmax(86px, 1fr))`, gap: 4, minWidth: 900 }}>
          {/* Top-left corner */}
          <div/>
          <div/>
          {/* Top: origins (POL) */}
          {O.map(o => {
            const port = window.PortByCode[o];
            return (
              <div key={o} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3, padding: '6px 0' }}>
                <window.Flag port={o} lg/>
                <span className="mono" style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--fg-1)' }}>{o}</span>
                <span style={{ fontSize: 9.5, color: 'var(--fg-3)', fontWeight: 500 }}>{port?.name}</span>
              </div>
            );
          })}

          {/* Rows: destinations (POD) */}
          {D.map((d, dRow) => {
            const port = window.PortByCode[d];
            return (
              <React.Fragment key={d}>
                {/* Y axis label (rotated) — only on first row */}
                {dRow === 0 && (
                  <div style={{ gridRow: `2 / span ${D.length}`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', fontSize: 10, fontWeight: 700, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em', whiteSpace: 'nowrap' }}>
                      {modeCfg.destLabel}
                    </span>
                  </div>
                )}
                {/* Row header */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 8px 0 4px' }}>
                  <window.Flag port={d} lg/>
                  <div style={{ minWidth: 0 }}>
                    <div className="mono" style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--fg-1)' }}>{d}</div>
                    <div style={{ fontSize: 9.5, color: 'var(--fg-3)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{port?.name}</div>
                  </div>
                </div>
                {/* Cells across origins */}
                {O.map((o, oCol) => {
                  const cell = H[oCol][dRow];
                  if (cell === null) {
                    return (
                      <div key={oCol} className="heat-cell empty" style={{ height: 72 }}>
                        <window.Icon name="plus" size={14} color="#98A2B3"/>
                      </div>
                    );
                  }
                  const col = viewBy === 'health' ? healthColor(cell.composite) : rateColor(cell.bench);
                  const isSel = drawer && sel.row === oCol && sel.col === dRow;
                  const dim = showAttentionOnly && cell.composite >= 35;
                  const critical = cell.composite < 35;
                  const scoreColor = cell.composite >= 60 ? '#027A48' : cell.composite >= 45 ? '#B54708' : cell.composite >= 30 ? '#C2410C' : '#B42318';
                  return (
                    <div key={oCol}
                      className={`heat-cell ${isSel ? 'selected' : ''}`}
                      style={{
                        background: col.bg, color: 'var(--fg-1)',
                        height: 72,
                        opacity: dim ? 0.25 : 1,
                        padding: '6px 4px',
                        flexDirection: 'column',
                        gap: 2,
                        position: 'relative',
                        boxShadow: `inset 3px 0 0 ${col.fg}`,
                      }}
                      onClick={() => setDrawer({ row: oCol, col: dRow })}
                      title={`${o} → ${d} · ${cell.topCarrier} · ${modeCfg.cellFmt(cell.rate)} ${modeCfg.unit} · Score ${cell.composite}/100`}
                    >
                      {critical && (
                        <span style={{ position: 'absolute', top: 4, right: 5, width: 7, height: 7, borderRadius: 50, background: '#D40B00', boxShadow: '0 0 0 1.5px white' }}/>
                      )}
                      {/* Hero: rate */}
                      <span className="mono" style={{ fontSize: 16, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.02em', display: 'inline-flex', alignItems: 'baseline', gap: 1 }}>
                        {modeCfg.cellFmt(cell.rate)}
                        {mode === 'air' && <span style={{ fontSize: 9, fontWeight: 600, opacity: 0.7 }}>/kg</span>}
                      </span>
                      {/* Carrier */}
                      <span style={{ fontSize: 10, fontWeight: 600, opacity: 0.85, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>
                        {cell.topCarrier}
                      </span>
                      {/* Score row */}
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 9.5, fontWeight: 700 }}>
                        <span style={{ width: 6, height: 6, borderRadius: 50, background: scoreColor }}/>
                        <span className="mono">Score {cell.composite}</span>
                      </span>
                    </div>
                  );
                })}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Critical attention panel */}
      {criticalCount > 0 && (
        <CriticalLanesPanel mode={mode} onOpen={(r, c) => setDrawer({ row: r, col: c })}/>
      )}

      {drawer && <LaneDrawer
        mode={mode}
        rowIdx={sel.row} colIdx={sel.col}
        onClose={() => setDrawer(null)}
        onRenegotiate={() => setShowRenegotiateModal(true)}
      />}

      {showRenegotiateModal && <RenegotiateModal
        origin={O[sel.row]} dest={D[sel.col]}
        topCarrier={H[sel.row][sel.col]?.topCarrier || (mode === 'air' ? 'Emirates SkyCargo' : 'Maersk')}
        onClose={() => setShowRenegotiateModal(false)}
      />}
    </div>
  );
};

/* ============== Bar showing healthy / moderate / critical proportions ============== */
function HealthBar({ healthy, moderate, critical }) {
  const total = healthy + moderate + critical;
  return (
    <div style={{ display: 'flex', height: 6, borderRadius: 999, overflow: 'hidden', background: 'var(--n-75)', marginTop: 4 }}>
      <div style={{ width: `${(healthy / total) * 100}%`, background: 'var(--success-500)' }}/>
      <div style={{ width: `${(moderate / total) * 100}%`, background: 'var(--warning-500)' }}/>
      <div style={{ width: `${(critical / total) * 100}%`, background: 'var(--danger-500)' }}/>
    </div>
  );
}

/* ============== Expiring rates: TEU split by mode ============== */
function ExpiringBar({ sea, air }) {
  const total = sea + air;
  return (
    <div style={{ marginTop: 6 }}>
      <div style={{ display: 'flex', height: 6, borderRadius: 999, overflow: 'hidden', background: 'var(--n-75)' }}>
        <div style={{ width: `${(sea / total) * 100}%`, background: '#1659CB' }}/>
        <div style={{ width: `${(air / total) * 100}%`, background: '#4ABFE5' }}/>
      </div>
      <div style={{ display: 'flex', gap: 10, marginTop: 5, fontSize: 10.5, color: 'var(--fg-3)' }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <span style={{ width: 6, height: 6, borderRadius: 2, background: '#1659CB' }}/>
          <span className="mono tnum" style={{ color: 'var(--fg-1)', fontWeight: 600 }}>{sea}</span> sea
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <span style={{ width: 6, height: 6, borderRadius: 2, background: '#4ABFE5' }}/>
          <span className="mono tnum" style={{ color: 'var(--fg-1)', fontWeight: 600 }}>{air}</span> air
        </span>
        <span style={{ marginLeft: 'auto', color: 'var(--fg-4)' }}>8 contracts</span>
      </div>
    </div>
  );
}

/* ============== Critical lanes panel (below matrix) ============== */
function CriticalLanesPanel({ mode = 'sea', onOpen }) {
  const cfg = window.MATRIX_BY_MODE[mode] || window.MATRIX_BY_MODE.sea;
  const O = cfg.origins;
  const D = cfg.dests;
  const H = cfg.health;
  const critical = [];
  for (let i = 0; i < O.length; i++) {
    for (let j = 0; j < D.length; j++) {
      const c = H[i][j];
      if (c && c.composite < 35) critical.push({ ...c, origin: O[i], dest: D[j], i, j });
    }
  }
  critical.sort((a, b) => a.composite - b.composite);

  return (
    <div className="card" style={{ padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <div style={{ width: 28, height: 28, borderRadius: 8, background: 'var(--danger-50)', color: 'var(--danger-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <window.Icon name="alert" size={14}/>
        </div>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>Lanes needing immediate attention</div>
          <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Health score below 35 · agent has drafted outreach for top 3</div>
        </div>
        <div style={{ flex: 1 }}/>
        <button className="btn btn-sm btn-agent-ghost"><window.Icon name="sparkles" size={11}/> Auto-resolve all</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: 10 }}>
        {critical.slice(0, 4).map((c, i) => (
          <div key={i} style={{
            border: '1px solid var(--danger-100)',
            borderLeft: '3px solid var(--danger-500)',
            background: 'white',
            borderRadius: 10, padding: '12px 14px',
            display: 'flex', flexDirection: 'column', gap: 8,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <window.Route origin={c.origin} dest={c.dest} mode={mode === 'multimodal' ? 'sea' : mode} compact/>
              <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: 'var(--danger-700)' }}>{c.composite}/100</span>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
              {c.flags.slice(0, 3).map((f, j) => (
                <span key={j} className={`badge b-${f.severity}`} style={{ fontSize: 10 }}>{f.label}</span>
              ))}
            </div>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', lineHeight: 1.5 }}>
              {c.carrierCount} {mode === 'air' ? 'airline' : 'carrier'}{c.carrierCount === 1 ? '' : 's'} · capacity <span className="mono">{c.capacity}</span> vs demand <span className="mono">{c.demand}</span> {cfg.capacityUnit}
            </div>
            <button className="btn btn-sm btn-primary" style={{ width: '100%' }} onClick={() => onOpen(c.i, c.j)}>
              View action plan <window.Icon name="arrow-r" size={11}/>
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ============== Lane drawer — health-centric ============== */
function LaneDrawer({ mode = 'sea', rowIdx, colIdx, onClose, onRenegotiate }) {
  const cfg = window.MATRIX_BY_MODE[mode] || window.MATRIX_BY_MODE.sea;
  const O = cfg.origins;
  const D = cfg.dests;
  const cell = cfg.health[rowIdx][colIdx];
  if (!cell) return null;
  const origin = O[rowIdx], dest = D[colIdx];

  // Available carriers (synthesized; capped by carrierCount)
  const allCarriersAir = [
    { name: 'Emirates SkyCargo',       transitDays: 2, baseRate: cell.rate,        source: 'Contracted', validity: 'Jun 30, 2026' },
    { name: 'Qatar Airways Cargo',     transitDays: 2, baseRate: cell.rate - 0.18, source: 'Contracted', validity: 'Jul 15, 2026' },
    { name: 'Cathay Cargo',            transitDays: 3, baseRate: cell.rate + 0.22, source: 'Spot API',   validity: 'May 31, 2026' },
    { name: 'Lufthansa Cargo',         transitDays: 2, baseRate: cell.rate + 0.35, source: 'Spot API',   validity: 'May 31, 2026' },
    { name: 'Singapore Airlines Cargo',transitDays: 3, baseRate: cell.rate - 0.05, source: 'Contracted', validity: 'Jun 30, 2026' },
    { name: 'Turkish Cargo',           transitDays: 3, baseRate: cell.rate - 0.28, source: 'Spot API',   validity: 'May 31, 2026' },
  ];
  const allCarriersSea = [
    { name: 'Maersk',       transitDays: 24, baseRate: cell.rate, source: 'Contracted', validity: 'Jun 30, 2026' },
    { name: 'MSC',          transitDays: 28, baseRate: cell.rate - 130, source: 'Contracted', validity: 'Jul 15, 2026' },
    { name: 'CMA CGM',      transitDays: 26, baseRate: cell.rate + 90, source: 'Spot API',   validity: 'May 31, 2026' },
    { name: 'Hapag-Lloyd',  transitDays: 25, baseRate: cell.rate + 270, source: 'Spot API',  validity: 'May 31, 2026' },
    { name: 'ONE',          transitDays: 27, baseRate: cell.rate - 70, source: 'Contracted', validity: 'Jun 30, 2026' },
    { name: 'Own Network',  transitDays: 30, baseRate: cell.rate - 340, source: 'Own network', validity: 'Open' },
  ];
  const allCarriers = mode === 'air' ? allCarriersAir : allCarriersSea;
  const carriers = allCarriers.slice(0, cell.carrierCount);
  const transitUnit = mode === 'air' ? 'd' : 'd';
  const rateFmt = cfg.cellFmt;
  const rateUnit = cfg.unit;

  // Suggested actions based on which sub-scores are weak
  const actions = [];
  if (cell.rateScore < 55) {
    actions.push({
      icon: 'sparkles', tone: 'agent',
      title: `Renegotiate rate with ${cell.topCarrier}`,
      reason: cell.rateScore < 35
        ? `You're paying ${Math.round((cell.bench) * 10)}% above market. Agent has draft ready.`
        : `Rate at market level. Volume justifies pushing for ${Math.round(2 + Math.random() * 2)}% concession.`,
      cta: 'Open draft email',
      onClick: onRenegotiate,
    });
  }
  if (cell.supplyScore < 55 || cell.carrierCount < 3) {
    actions.push({
      icon: 'users', tone: 'brand',
      title: 'Find additional carriers',
      reason: cell.carrierCount === 1
        ? 'Single-source lane — high disruption risk. Agent identified 4 candidates.'
        : `Only ${cell.carrierCount} active carriers. Agent identified ${4 - cell.carrierCount} additional options.`,
      cta: 'Browse candidates',
    });
  }
  if (cell.demandScore < 55) {
    actions.push({
      icon: 'trend-up', tone: 'warning',
      title: 'Predict upcoming demand',
      reason: cell.ratio < 1
        ? `Demand exceeds capacity by ${Math.round((1 - cell.ratio) * 100)}%. Forecast suggests it'll worsen 9% next month.`
        : `Capacity tight (${cell.ratio.toFixed(2)}× demand). Pre-book buffer recommended.`,
      cta: 'See forecast',
    });
  }
  if (actions.length === 0) {
    actions.push({
      icon: 'check-circle', tone: 'success',
      title: 'Lock contracted rate',
      reason: `Health is strong. Lock through end of Q3 to protect margin.`,
      cta: 'Draft renewal',
    });
  }
  // Pad up to keep at least 3 visible if room
  if (actions.length < 3) {
    actions.push({
      icon: 'history', tone: 'neutral',
      title: 'Review 12-month rate trend',
      reason: '−3.2% MoM, +19.9% YoY. Identify cyclical patterns.',
      cta: 'Open trend',
    });
  }

  const healthMeta = cell.composite >= 60 ? { label: 'Healthy', color: 'var(--success-700)', bg: 'var(--success-50)' }
                    : cell.composite >= 45 ? { label: 'Moderate', color: 'var(--warning-700)', bg: 'var(--warning-50)' }
                    : cell.composite >= 30 ? { label: 'Weak', color: '#C2410C', bg: '#FFF7ED' }
                    : { label: 'Critical', color: 'var(--danger-700)', bg: 'var(--danger-50)' };

  return (
    <div className="drawer-overlay" onClick={onClose}>
      <div className="drawer" onClick={e => e.stopPropagation()} style={{ width: 600 }}>
        {/* Header */}
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--n-100)', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <window.Route origin={origin} dest={dest} mode={mode === 'multimodal' ? 'sea' : mode}/>
              <span className="badge b-neutral">{cfg.equipmentBadge}</span>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>
              Best rate <strong className="mono" style={{ color: 'var(--fg-1)' }}>{rateFmt(Math.min(...carriers.map(c => c.baseRate)))}{rateUnit}</strong>
              {' · '}
              <strong style={{ color: 'var(--fg-1)' }}>{cell.carrierCount}</strong> {mode === 'air' ? 'airlines' : 'carriers'}
              {' · '}
              Capacity <strong className="mono" style={{ color: 'var(--fg-1)' }}>{cell.capacity}</strong> {cfg.capacityUnit}
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}><window.Icon name="x" size={16}/></button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflow: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 18 }}>

          {/* HEALTH SCORE CARD */}
          <div style={{
            background: `linear-gradient(180deg, ${healthMeta.bg}, white 80%)`,
            border: `1px solid ${healthMeta.color}33`,
            borderRadius: 12,
            padding: 16,
          }}>
            <div style={{ display: 'grid', gridTemplateColumns: '140px 1fr', gap: 18, alignItems: 'center' }}>
              {/* Gauge */}
              <CircularGauge score={cell.composite} color={healthMeta.color}/>
              {/* Label + flags */}
              <div>
                <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Lane health</div>
                <div style={{ fontSize: 22, fontWeight: 600, color: healthMeta.color, letterSpacing: '-0.01em' }}>{healthMeta.label}</div>
                <div style={{ fontSize: 12, color: 'var(--fg-2)', marginTop: 2, lineHeight: 1.45 }}>
                  {cell.composite < 35
                    ? 'Multiple risk factors. Agent recommends immediate action — outreach has been drafted.'
                    : cell.composite < 60
                    ? 'Acceptable but improvable. Action plan below targets the weakest dimensions.'
                    : 'Strong across rate, supply, and demand. Lock contract to protect.'
                  }
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 8 }}>
                  {cell.flags.map((f, j) => (
                    <span key={j} className={`badge b-${f.severity}`} style={{ fontSize: 10.5 }}>
                      <window.Icon name="alert" size={9}/>
                      {f.label}
                    </span>
                  ))}
                  {cell.flags.length === 0 && (
                    <span className="badge b-success" style={{ fontSize: 10.5 }}>
                      <window.Icon name="check" size={9}/>
                      No flags
                    </span>
                  )}
                </div>
              </div>
            </div>

            {/* Sub-score breakdown */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 14, paddingTop: 14, borderTop: '1px solid white' }}>
              <SubScoreCard
                title="Rate vs market"
                icon="trend-down"
                score={cell.rateScore}
                primary={cell.bench < 0 ? `${Math.abs(cell.bench * 10).toFixed(0)}% below market` : `${(cell.bench * 10).toFixed(0)}% above market`}
                secondary={`Benchmark ${rateFmt(cell.rate / (1 + cell.bench * 0.1))}${rateUnit}`}
                weight={30}
              />
              <SubScoreCard
                title="Supply depth"
                icon="users"
                score={cell.supplyScore}
                primary={`${cell.carrierCount} active ${mode === 'air' ? 'airline' : 'carrier'}${cell.carrierCount === 1 ? '' : 's'}`}
                secondary={`Capacity ${cell.capacity} ${cfg.capacityUnit}`}
                weight={30}
              />
              <SubScoreCard
                title="Demand match"
                icon="gauge"
                score={cell.demandScore}
                primary={`${cell.ratio.toFixed(2)}× headroom`}
                secondary={`${cell.demand} ${cfg.capacityUnit} demand`}
                weight={40}
              />
            </div>
          </div>

          {/* SUGGESTED ACTIONS */}
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Suggested actions</div>
              <span className="agent-chip"><window.Icon name="sparkles" size={10}/>{actions.length} prioritized by agent</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {actions.map((a, i) => <ActionCard key={i} {...a}/>)}
            </div>
          </div>

          {/* RATES TABLE */}
          <div>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Available rates ({cell.carrierCount})</div>
            <table className="table">
              <thead>
                <tr>
                  <th>{mode === 'air' ? 'Airline' : 'Carrier'}</th><th>Transit</th><th>Base{rateUnit}</th><th>Source</th><th>Validity</th>
                </tr>
              </thead>
              <tbody>
                {carriers.map((c, i) => (
                  <tr key={i}>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span style={{ width: 6, height: 6, borderRadius: 50, background: window.CARRIERS.find(x => x.name === c.name)?.color || '#98A2B3' }}/>
                        <span style={{ fontWeight: 600, color: 'var(--fg-1)' }}>{c.name}</span>
                      </div>
                    </td>
                    <td className="mono tnum">{c.transitDays}{transitUnit}</td>
                    <td className="mono tnum" style={{ fontWeight: 600 }}>{rateFmt(c.baseRate)}</td>
                    <td><span className={`badge ${c.source === 'Contracted' ? 'b-blue' : c.source === 'Own network' ? 'b-agent' : 'b-neutral'}`} style={{ fontSize: 10.5 }}>{c.source}</span></td>
                    <td style={{ color: 'var(--fg-3)', fontSize: 11.5 }}>{c.validity}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* LANE ECONOMICS */}
          <div>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>Lane economics · last 90 days</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {[
                ['Booked volume', `$${(cell.revenue90d / 1000).toFixed(0)}K`],
                ['RFQs', `${cell.rfqs90d}`],
                ['Booked', `${cell.booked90d}`],
              ].map(([k, v], i) => (
                <div key={i} style={{ padding: '10px 12px', background: 'var(--n-25)', borderRadius: 8, border: '1px solid var(--n-100)' }}>
                  <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{k}</div>
                  <div className="mono tnum" style={{ fontSize: 15, fontWeight: 600, marginTop: 2 }}>{v}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Health trend */}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 8 }}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>Health · 8 weeks</div>
              <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{cell.trend[cell.trend.length - 1] - cell.trend[0] > 0 ? '+' : ''}{cell.trend[cell.trend.length - 1] - cell.trend[0]} pts</div>
            </div>
            <TrendChart values={cell.trend}/>
          </div>

        </div>
      </div>
    </div>
  );
}

/* ============== Sub-score card ============== */
function SubScoreCard({ title, icon, score, primary, secondary, weight }) {
  const color = score >= 60 ? 'var(--success-700)' : score >= 40 ? 'var(--warning-700)' : 'var(--danger-700)';
  const bg = score >= 60 ? 'var(--success-500)' : score >= 40 ? 'var(--warning-500)' : 'var(--danger-500)';
  return (
    <div style={{ background: 'white', border: '1px solid var(--n-100)', borderRadius: 10, padding: '10px 12px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <window.Icon name={icon} size={11} color="#667085"/>
          <span style={{ fontSize: 10.5, color: 'var(--fg-3)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{title}</span>
        </div>
        <span style={{ fontSize: 9.5, color: 'var(--fg-4)' }}>w. {weight}%</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 5, marginTop: 5 }}>
        <span className="mono tnum" style={{ fontSize: 22, fontWeight: 700, color }}>{score}</span>
        <span style={{ fontSize: 10.5, color: 'var(--fg-4)' }}>/100</span>
      </div>
      <div style={{ height: 4, borderRadius: 999, background: 'var(--n-75)', overflow: 'hidden', marginTop: 6 }}>
        <div style={{ width: `${score}%`, height: '100%', background: bg, borderRadius: 999 }}/>
      </div>
      <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-1)', marginTop: 6 }}>{primary}</div>
      <div style={{ fontSize: 10.5, color: 'var(--fg-3)', marginTop: 1 }}>{secondary}</div>
    </div>
  );
}

/* ============== Action card ============== */
function ActionCard({ icon, tone, title, reason, cta, onClick }) {
  const palette = {
    agent:   { bg: 'var(--agent-50)',   border: 'var(--agent-200)',   color: 'var(--agent-700)',   btn: 'btn-agent' },
    brand:   { bg: 'var(--brand-50)',   border: 'var(--brand-200)',   color: 'var(--brand-700)',   btn: 'btn-primary' },
    warning: { bg: 'var(--warning-50)', border: 'var(--warning-200)', color: 'var(--warning-700)', btn: 'btn-secondary' },
    success: { bg: 'var(--success-50)', border: 'var(--success-100)', color: 'var(--success-700)', btn: 'btn-secondary' },
    neutral: { bg: 'var(--n-25)',       border: 'var(--n-100)',       color: 'var(--fg-2)',        btn: 'btn-secondary' },
  }[tone];
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '36px 1fr auto', alignItems: 'center', gap: 12,
      padding: '12px 14px',
      background: 'white',
      border: `1px solid ${palette.border}`,
      borderLeft: `3px solid ${palette.color}`,
      borderRadius: 10,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8,
        background: palette.bg, color: palette.color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <window.Icon name={icon} size={15}/>
      </div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--fg-1)' }}>{title}</div>
        <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2, lineHeight: 1.45 }}>{reason}</div>
      </div>
      <button className={`btn btn-sm ${palette.btn}`} onClick={onClick}>{cta}</button>
    </div>
  );
}

/* ============== Circular gauge ============== */
function CircularGauge({ score, color }) {
  const size = 120, stroke = 12;
  const r = (size - stroke) / 2;
  const cx = size / 2, cy = size / 2;
  // Arc 240° starting from 150° to 30° (bottom-open)
  const arcStart = 150 * Math.PI / 180;
  const arcEnd = (150 + 240) * Math.PI / 180;
  const arcLen = 240 * Math.PI / 180 * r;
  const filledLen = (score / 100) * (240 * Math.PI / 180 * r);

  const point = (angle) => [cx + r * Math.cos(angle), cy + r * Math.sin(angle)];
  const [sx, sy] = point(arcStart);
  const [ex, ey] = point(arcEnd);
  const arcPath = `M ${sx} ${sy} A ${r} ${r} 0 1 1 ${ex} ${ey}`;

  return (
    <svg width={size} height={size}>
      {/* Track */}
      <path d={arcPath} fill="none" stroke="var(--n-100)" strokeWidth={stroke} strokeLinecap="round"/>
      {/* Filled */}
      <path d={arcPath} fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round"
        strokeDasharray={`${filledLen} ${arcLen - filledLen + 100}`}/>
      {/* Center text */}
      <text x={cx} y={cy + 2} textAnchor="middle" fontSize="34" fontWeight="700" fontFamily="JetBrains Mono" fill="var(--fg-1)" dominantBaseline="middle">{score}</text>
      <text x={cx} y={cy + 22} textAnchor="middle" fontSize="10" fill="var(--fg-3)" fontFamily="Inter">of 100</text>
    </svg>
  );
}

/* ============== Mini trend chart ============== */
function TrendChart({ values }) {
  const w = 520, h = 64, padL = 8, padR = 8, padT = 8, padB = 8;
  const max = Math.max(...values, 100), min = Math.min(...values, 0);
  const range = max - min || 1;
  const x = (i) => padL + (i / (values.length - 1)) * (w - padL - padR);
  const y = (v) => padT + (1 - (v - min) / range) * (h - padT - padB);
  const pts = values.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(' ');
  const area = `${padL},${h - padB} ${pts} ${w - padR},${h - padB}`;
  const last = values[values.length - 1];
  const lastColor = last >= 60 ? '#12B76A' : last >= 40 ? '#F79009' : '#F04438';
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`}>
      <line x1={padL} y1={y(60)} x2={w - padR} y2={y(60)} stroke="#D1FADF" strokeWidth="1" strokeDasharray="3 3"/>
      <line x1={padL} y1={y(35)} x2={w - padR} y2={y(35)} stroke="#FECACA" strokeWidth="1" strokeDasharray="3 3"/>
      <polygon points={area} fill="#1659CB" opacity="0.08"/>
      <polyline points={pts} fill="none" stroke="#1659CB" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={x(values.length - 1)} cy={y(last)} r="4" fill={lastColor} stroke="white" strokeWidth="2"/>
    </svg>
  );
}

/* ============== Renegotiate modal ============== */
function RenegotiateModal({ origin, dest, topCarrier, onClose }) {
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ width: 640 }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--n-100)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="agent-chip"><span className="agent-dot"/>Drafted by agent</span>
              <div style={{ fontSize: 14, fontWeight: 600 }}>Renegotiate · {origin} → {dest}</div>
            </div>
            <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 4 }}>Email to <strong style={{ color: 'var(--fg-2)' }}>{topCarrier}</strong> · references $1.42M historical volume</div>
          </div>
          <button className="icon-btn" onClick={onClose}><window.Icon name="x" size={16}/></button>
        </div>
        <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr', rowGap: 8, alignItems: 'center', fontSize: 12 }}>
            <div style={{ color: 'var(--fg-3)' }}>To:</div>
            <div><span className="badge b-neutral">rates@{topCarrier.toLowerCase().replace(/\s+/g, '')}.com</span></div>
            <div style={{ color: 'var(--fg-3)' }}>Subject:</div>
            <div style={{ fontWeight: 600 }}>Rate review request — {origin} → {dest}, 40ft HC</div>
          </div>
          <div className="email-quote" style={{ background: 'var(--agent-50)', borderLeftColor: 'var(--agent-500)', color: 'var(--agent-700)', maxHeight: 240, overflow: 'auto' }}>
{`Hi Account Team,

We'd like to revisit our rates on the ${origin} → ${dest} corridor. Over the past 12 months we've moved 31 bookings ($842K booked volume, $1.42M annual run-rate) with ${topCarrier} on this lane.

Spot rates from competing carriers are tracking 6–9% above your contracted level — we'd like to extend the contract through Q3 at a 4% reduction in exchange for a volume commitment of 35 containers / quarter.

Can we discuss this week?

Best,
Freight AI Operations`}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-primary"><window.Icon name="send" size={13}/> Send to {topCarrier}</button>
            <button className="btn btn-secondary"><window.Icon name="edit" size={13}/> Edit draft</button>
            <div style={{ flex: 1 }}/>
            <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
          </div>
        </div>
      </div>
    </div>
  );
}


/* Expose helpers used by Demand Planning */
Object.assign(window, { SubScoreCard, ActionCard, CircularGauge });
