// ============================================================================
// Composite dashboard card — KPI tile + a slice of the orders table.
// Two visual densities: 'cropped' (default — KPI + small table) and 'full'
// (more rows, fuller window chrome). Both use real BorderLens tokens.
// ============================================================================

function MiniSparkline({ values, color = 'var(--bl-brand)' }) {
  const w = 120, h = 28;
  const max = Math.max(...values), min = Math.min(...values);
  const points = values.map((v, i) => {
    const x = (i / (values.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * h;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  return (
    <svg width={w} height={h} style={{ display: 'block' }}>
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/>
      <circle cx={w} cy={h - ((values[values.length-1]-min)/(max-min||1))*h} r="2.5" fill={color}/>
    </svg>
  );
}

function DashboardCard({ density = 'cropped', tickedTotal }) {
  const isFull = density === 'full';
  const totalDisplay = `£${(tickedTotal ?? 127405).toLocaleString('en-GB')}`;

  const rows = [
    { id: '#13472', dest: 'US·CT', value: '£1,318', est: '£94',  inv: '£94',   variance: '−£1',  vClass: 'pos', margin: '74.2%' },
    { id: '#13468', dest: 'AU',    value: '£1,047', est: '£244', inv: '£202',  variance: '−£42', vClass: 'pos', margin: '65.8%' },
    { id: '#13463', dest: 'US·CA', value: '£687',   est: '£57',  inv: '£57',   variance: '+£0',  vClass: 'risk', margin: '70.3%' },
    { id: '#13451', dest: 'US·NJ', value: '£742',   est: '£62',  inv: '£62',   variance: '+£0',  vClass: 'risk', margin: '69.7%' },
    { id: '#13444', dest: 'US·PA', value: '£2,418', est: '£169', inv: '£190',  variance: '+£21', vClass: 'risk', margin: '72.4%' },
    { id: '#13433', dest: 'US·NY', value: '£3,148', est: '£420', inv: '£618',  variance: '+£198',vClass: 'risk', margin: '70.1%' },
    { id: '#13422', dest: 'US·GA', value: '£2,461', est: '£166', inv: '£341',  variance: '+£175',vClass: 'risk', margin: '73.0%' },
    { id: '#13418', dest: 'KR',    value: '£812',   est: '£182', inv: '£187',  variance: '+£5',  vClass: 'risk', margin: '63.4%' },
  ];
  const visibleRows = isFull ? rows : rows.slice(0, 4);

  const varColor = (c) => c === 'pos' ? '#0D9E8C' : '#f87171';

  return (
    <div style={{
      width: isFull ? 720 : 560,
      background: '#fff',
      borderRadius: 14,
      boxShadow:
        '0 60px 120px -30px rgba(2, 12, 27, 0.65), ' +
        '0 30px 60px -20px rgba(2, 12, 27, 0.45), ' +
        '0 0 0 1px rgba(15, 23, 42, 0.10), ' +
        '0 0 0 6px rgba(255, 255, 255, 0.04)',
      overflow: 'hidden',
      fontFamily: 'var(--bl-font)',
      color: '#0f172a',
      position: 'relative',
    }}>
      {/* Window chrome */}
      <div style={{
        padding: '11px 16px',
        display: 'flex', alignItems: 'center', gap: 10,
        borderBottom: '1px solid #e6ebf2',
        background: 'linear-gradient(#fcfcfd, #f6f8fb)',
      }}>
        <div style={{ display: 'flex', gap: 6 }}>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#e85b5b' }}/>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#f0b748' }}/>
          <span style={{ width: 10, height: 10, borderRadius: '50%', background: '#5cc463' }}/>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginLeft: 10 }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--bl-brand)', boxShadow: '0 0 0 3px rgba(13,158,140,0.18)' }}/>
          <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.14em', color: '#0f172a' }}>BORDERLENS</span>
          <span style={{ fontSize: 10.5, color: '#94a3b8', marginLeft: 4 }}>/ Order Explorer</span>
        </div>
        <div style={{ marginLeft: 'auto', fontSize: 10, color: '#94a3b8', fontFamily: 'var(--bl-font-mono)' }}>
          843 orders · last 90d
        </div>
      </div>

      {/* KPI strip */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 0,
        borderBottom: '1px solid #e6ebf2',
      }}>
        <div style={{ padding: '20px 22px', borderRight: '1px solid #e6ebf2', position: 'relative' }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.12em', display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--bl-brand)' }}/>
            Duty & Tax Invoiced
          </div>
          <div style={{
            fontSize: 42, fontWeight: 600, color: 'var(--bl-brand)',
            letterSpacing: '-0.025em', lineHeight: 1.05, marginTop: 8,
            fontVariantNumeric: 'tabular-nums',
          }}>{totalDisplay}</div>
          <div style={{ fontSize: 11, color: '#64748b', marginTop: 6 }}>
            <span style={{ color: '#0f172a', fontWeight: 500 }}>843 orders</span> · matched to carrier evidence
          </div>
        </div>
        <div style={{ padding: '20px 22px', borderRight: '1px solid #e6ebf2' }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: '#d97706', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
            Estimate Limited
          </div>
          <div style={{ fontSize: 24, fontWeight: 600, color: '#d97706', marginTop: 8, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>£4,840</div>
          <div style={{ fontSize: 10.5, color: '#64748b', marginTop: 6 }}>9 shipments · partial estimates</div>
        </div>
        <div style={{ padding: '20px 22px' }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: '#64748b', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
            Classification Risk
          </div>
          <div style={{ fontSize: 24, fontWeight: 600, color: '#0f172a', marginTop: 8, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em' }}>
            £9,720 <span style={{ fontSize: 11, color: '#94a3b8', fontWeight: 400 }}>/ yr est.</span>
          </div>
          <div style={{ fontSize: 10.5, color: '#64748b', marginTop: 6 }}>34 products · missing HS codes</div>
        </div>
      </div>

      {/* Table slice */}
      <div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11.5, fontFamily: 'var(--bl-font)' }}>
          <thead>
            <tr style={{ background: '#fafbfd' }}>
              {['Order','Dest','Customs Value','Est. D&T','Carrier Inv.','Variance','Margin'].map((h, i) => (
                <th key={i} style={{
                  padding: '9px 14px',
                  textAlign: i >= 2 ? 'right' : 'left',
                  fontSize: 9, fontWeight: 600, color: '#94a3b8',
                  textTransform: 'uppercase', letterSpacing: '0.1em',
                  borderBottom: '1px solid #e6ebf2',
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {visibleRows.map((r, i) => (
              <tr key={i} style={{ borderTop: i === 0 ? 'none' : '1px solid #f0f3f8' }}>
                <td style={{ padding: '10px 14px', fontFamily: 'var(--bl-font-mono)', fontSize: 11, color: 'var(--bl-brand)', fontWeight: 500 }}>{r.id}</td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    fontSize: 10, fontFamily: 'var(--bl-font-mono)', fontWeight: 500,
                    padding: '2px 6px', borderRadius: 3, background: '#f1f4f8', color: '#475569',
                  }}>{r.dest}</span>
                </td>
                <td style={{ padding: '10px 14px', textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: '#0f172a' }}>{r.value}</td>
                <td style={{ padding: '10px 14px', textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: 'var(--bl-brand)', textDecoration: 'underline', textUnderlineOffset: 2, textDecorationColor: 'rgba(13,158,140,0.4)' }}>{r.est}</td>
                <td style={{ padding: '10px 14px', textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: '#475569' }}>{r.inv}</td>
                <td style={{ padding: '10px 14px', textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: varColor(r.vClass), fontWeight: 500 }}>{r.variance}</td>
                <td style={{ padding: '10px 14px', textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: '#0f172a' }}>{r.margin}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Footer status bar */}
      <div style={{
        padding: '10px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        borderTop: '1px solid #e6ebf2', background: '#fafbfd',
        fontSize: 10.5, color: '#64748b',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--bl-brand)' }}/>
            Reconciled · 843 orders matched
          </span>
          <span style={{ color: '#cbd5e1' }}>·</span>
          <span>Data coverage <span style={{ color: '#0f172a', fontWeight: 500 }}>100%</span></span>
        </div>
        <div style={{ fontFamily: 'var(--bl-font-mono)', fontSize: 9.5, color: '#94a3b8' }}>v3.4 · GBP</div>
      </div>
    </div>
  );
}

window.DashboardCard = DashboardCard;
window.MiniSparkline = MiniSparkline;
