// Home page: hero, cashflow chart, live ticker, leaderboards, industry mix
const { useState: useStateH, useEffect: useEffectH, useRef: useRefH, useMemo: useMemoH } = React;

// BarChart: discrete bars (one per period bucket). Used by the Capital flow card.
// Uses sqrt scale on the y-axis so a single mega-day doesn't flatten everything else.
function BarChart({ data, width = 1200, height = 220, color }) {
  if (!data || data.length === 0) {
    return <div style={{ height, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-4)', fontSize: 13 }}>No filings in this window</div>;
  }
  const w = width, h = height;
  const pad = { l: 56, r: 16, t: 16, b: 30 };
  const iw = w - pad.l - pad.r;
  const ih = h - pad.t - pad.b;

  const max = Math.max(...data.map((d) => d.v), 1);
  // sqrt scale tames outliers without going log-zero-unfriendly
  const scale = (v) => (v <= 0 ? 0 : Math.sqrt(v) / Math.sqrt(max));

  const slot = iw / data.length;
  const barW = Math.max(2, Math.floor(slot * 0.7));
  const c = color || 'var(--accent)';

  // Y ticks at 0, 25%, 50%, 75%, 100% of the SQRT-scaled range, but labels show the actual $ value.
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map((t) => {
    const v = (t * Math.sqrt(max)) ** 2;
    return { y: pad.t + ih - t * ih, label: window.fmtMoney(v) };
  });

  // X-axis: first, middle, last labels (date format depends on bucket width)
  const xLabels = data.length <= 1 ? [0] : [0, Math.floor(data.length / 2), data.length - 1];

  return (
    <svg className="timeline-svg" width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ overflow: 'visible' }}>
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={pad.l} x2={pad.l + iw} y1={t.y} y2={t.y} stroke="var(--line)" strokeDasharray={i === 0 ? null : '2 3'} />
          <text x={pad.l - 8} y={t.y + 3} fontSize="10" fontFamily="var(--font-mono)" fill="var(--ink-4)" textAnchor="end">{t.label}</text>
        </g>
      ))}
      {data.map((d, i) => {
        const barH = scale(d.v) * ih;
        const x = pad.l + i * slot + (slot - barW) / 2;
        const y = pad.t + ih - barH;
        return (
          <rect key={i} x={x} y={y} width={barW} height={barH} fill={c} fillOpacity={d.v > 0 ? 0.85 : 0}>
            <title>{window.fmtDateShort(d.d)}: {window.fmtMoney(d.v)} across {d.f || 0} filings</title>
          </rect>
        );
      })}
      {xLabels.map((idx, i) => (
        <text key={i} x={pad.l + idx * slot + slot / 2} y={pad.t + ih + 18}
              fontSize="10" fontFamily="var(--font-mono)" fill="var(--ink-4)"
              textAnchor={i === 0 ? 'start' : i === xLabels.length - 1 ? 'end' : 'middle'}>
          {window.fmtDateShort(data[idx].d)}
        </text>
      ))}
    </svg>
  );
}

function Sparkline({ data, width = 600, height = 200, color }) {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data.map(d => d.v), 1);
  const min = 0;
  const w = width, h = height;
  const pad = { l: 48, r: 12, t: 12, b: 28 };
  const iw = w - pad.l - pad.r;
  const ih = h - pad.t - pad.b;
  const xStep = iw / Math.max(data.length - 1, 1);
  const ax = (i) => pad.l + i * xStep;
  const ay = (v) => pad.t + ih - ((v - min) / (max - min)) * ih;

  const linePath = data.map((d, i) => `${i === 0 ? 'M' : 'L'} ${ax(i).toFixed(1)} ${ay(d.v).toFixed(1)}`).join(' ');
  const areaPath = `M ${pad.l} ${pad.t + ih} ` + data.map((d, i) => `L ${ax(i).toFixed(1)} ${ay(d.v).toFixed(1)}`).join(' ') + ` L ${pad.l + iw} ${pad.t + ih} Z`;

  // Y-axis ticks (0, 25%, 50%, 75%, 100%)
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(t => ({
    y: pad.t + ih - t * ih,
    label: window.fmtMoney(min + (max - min) * t),
  }));

  // X-axis: show first, middle, last
  const xLabels = [0, Math.floor(data.length / 2), data.length - 1];

  const c = color || 'var(--accent)';

  return (
    <svg className="timeline-svg" width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ overflow: 'visible' }}>
      <defs>
        <linearGradient id="sparkGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={c} stopOpacity="0.25"/>
          <stop offset="100%" stopColor={c} stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* Y grid */}
      {yTicks.map((t, i) => (
        <g key={i}>
          <line x1={pad.l} x2={pad.l + iw} y1={t.y} y2={t.y} stroke="var(--line)" strokeDasharray={i === 0 ? null : '2 3'} />
          <text x={pad.l - 8} y={t.y + 3} fontSize="10" fontFamily="var(--font-mono)" fill="var(--ink-4)" textAnchor="end">{t.label}</text>
        </g>
      ))}
      {/* X labels */}
      {xLabels.map((idx, i) => (
        <text key={i} x={ax(idx)} y={pad.t + ih + 18} fontSize="10" fontFamily="var(--font-mono)" fill="var(--ink-4)"
              textAnchor={i === 0 ? 'start' : i === xLabels.length - 1 ? 'end' : 'middle'}>
          {window.fmtDateShort(data[idx].d)}
        </text>
      ))}
      {/* Area */}
      <path d={areaPath} fill="url(#sparkGrad)" />
      {/* Line */}
      <path d={linePath} fill="none" stroke={c} strokeWidth="1.5" />
      {/* Last point dot */}
      <circle cx={ax(data.length - 1)} cy={ay(data[data.length - 1].v)} r="3" fill={c} />
      <circle cx={ax(data.length - 1)} cy={ay(data[data.length - 1].v)} r="6" fill={c} fillOpacity="0.2" />
    </svg>
  );
}

function HomePage({ navigate }) {
  const [recent, setRecent] = useStateH(null);
  const [topSponsors, setTopSponsors] = useStateH(null);
  const [topDeals, setTopDeals] = useStateH(null);
  const [byCount, setByCount] = useStateH(null);
  const [range, setRange] = useStateH('90d');
  const [searchQ, setSearchQ] = useStateH('');
  const [cashflowData, setCashflowData] = useStateH(null);

  useEffectH(() => {
    // Recent filings ticker. We pull a generous slice and let the ticker
    // fall back to the most-recent-N if the strict 48h window is empty
    // (Sun/Mon mornings — SEC publishes Mon-Fri).
    window.api('/api/deals?real_estate=1&limit=50&sort=latest_filing_date').then(r => setRecent(r.results));
    window.api('/api/sponsors?limit=8&sort=total_raised').then(r => setTopSponsors(r.results));
    window.api('/api/deals?real_estate=1&limit=5&sort=total_raised').then(r => setTopDeals(r.results));
    window.api('/api/sponsors?limit=5&sort=deals_count').then(r => setByCount(r.results));
  }, []);

  // Cashflow chart now driven by a server-side aggregated endpoint that
  // buckets by day/week/month based on the requested window. No 200-row cap.
  useEffectH(() => {
    setCashflowData(null);
    const days = range === '30d' ? 30 : range === '90d' ? 90 : range === '180d' ? 180 : 365;
    window.api(`/api/stats/cashflow?days=${days}`).then(r => setCashflowData(r));
  }, [range]);

  const cashflow = useMemoH(() => {
    if (!cashflowData) return null;
    return cashflowData.buckets.map(b => ({ d: b.date, v: b.raised, f: b.filings }));
  }, [cashflowData]);

  // Ticker: prefer the strict 48h window. If empty (weekend lull), fall back
  // to the most recent N entries with a "stale" badge so the panel never sits empty.
  const ticker = useMemoH(() => {
    if (!recent) return { rows: [], stale: false };
    const cutoff = new Date(); cutoff.setDate(cutoff.getDate() - 2);
    const fresh = recent.filter(r => new Date(r.latest_filing_date) >= cutoff);
    if (fresh.length >= 3) return { rows: fresh.slice(0, 14), stale: false };
    return { rows: recent.slice(0, 8), stale: true };
  }, [recent]);
  const last24h = ticker.rows;

  const totalRaised24h = useMemoH(() => {
    // Use the server's aggregated 24h slice from the cashflow data when
    // available (most accurate). Falls back to 0 while loading.
    if (!cashflowData?.buckets?.length) return 0;
    const today = new Date().toISOString().slice(0, 10);
    const yest  = new Date(Date.now() - 86_400_000).toISOString().slice(0, 10);
    return cashflowData.buckets
      .filter(b => b.date === today || b.date === yest)
      .reduce((s, b) => s + b.raised, 0);
  }, [cashflowData]);

  const onSearchSubmit = (e) => {
    e.preventDefault();
    if (searchQ.trim()) navigate({ name: 'search', q: searchQ.trim() });
  };

  return (
    <>
      {/* Hero */}
      <div className="hero">
        <div className="hero-left">
          <div className="hero-eyebrow">
            <span className="live-dot"></span>
            <span>Live · 2008 → today</span>
          </div>
          <h1 className="hero-title">
            Every private real-estate raise,<br/>
            attributed to the <em>real</em> sponsor.
          </h1>
          <p className="hero-sub">
            18 years of private real-estate raise activity, rolled up into 52,028 distinct deals and 6,056 sponsors —
            with the SPV chains, amendment history, and evidence trails the public record hides.
          </p>

          <form className="hero-search" onSubmit={onSearchSubmit}>
            <span className="hero-search-icon"><I.search /></span>
            <input
              type="text"
              placeholder="Search by deal, sponsor, address, or phone…"
              value={searchQ}
              onChange={(e) => setSearchQ(e.target.value)}
            />
            <span className="hero-shortcut">↵</span>
          </form>

          <div className="hero-stats">
            <div>
              <div className="stat-label">Capital indexed</div>
              <div className="stat-value">$501B</div>
              <div className="stat-sub">all time</div>
            </div>
            <div>
              <div className="stat-label">Deals</div>
              <div className="stat-value">52,028</div>
              <div className="stat-sub">2008 → today</div>
            </div>
            <div>
              <div className="stat-label">Sponsors</div>
              <div className="stat-value">6,056</div>
              <div className="stat-sub">deduplicated GPs</div>
            </div>
            <div>
              <div className="stat-label">2025+</div>
              <div className="stat-value">$35B</div>
              <div className="stat-sub">5,126 deals</div>
            </div>
          </div>
        </div>

        {/* Live ticker */}
        <div className="hero-right">
          <div className="ticker-header">
            <h3 style={{ margin: 0, fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)' }}>
              Latest filings
            </h3>
            {ticker.stale ? (
              <span className="live-pill" style={{ background: 'transparent', color: 'var(--ink-4)' }}>
                <span className="live-dot" style={{ background: 'var(--ink-5, #94a3b8)' }}></span>
                Most recent
              </span>
            ) : (
              <span className="live-pill">
                <span className="live-dot"></span>
                Last 48h
              </span>
            )}
          </div>
          <div className="ticker-list">
            {!recent && Array.from({ length: 8 }).map((_, i) => (
              <div className="ticker-row" key={i}>
                <div className="skel" style={{ height: 10, width: 50 }}></div>
                <div><div className="skel" style={{ height: 12, width: '70%' }}></div>
                  <div className="skel" style={{ height: 9, width: '40%', marginTop: 4 }}></div></div>
                <div className="skel" style={{ height: 12, width: 50 }}></div>
              </div>
            ))}
            {last24h.map((r, i) => (
              <div className={`ticker-row ${i < 2 ? 'fresh' : ''}`} key={r.deal_id}
                   onClick={() => navigate({ name: 'deal', id: r.deal_id })}>
                <span className="ticker-time">{window.relTime(r.latest_filing_date).toUpperCase()}</span>
                <div style={{ minWidth: 0 }}>
                  <div className="ticker-name">{r.deal_name}</div>
                  <div className="ticker-sponsor">
                    {window.industryShort(r.industry_group_type)}{r.amendment_no > 0 ? ` · Amendment ${r.amendment_no}` : ' · New filing'}
                  </div>
                </div>
                <div className={`ticker-amount ${!r.total_raised ? 'zero' : ''}`}>
                  {r.total_raised ? window.fmtMoney(r.total_raised) : '—'}
                  {r.target_is_indefinite ? (
                    <div style={{ fontSize: 9, color: 'var(--ink-4)', fontWeight: 400, fontStyle: 'italic', marginTop: 1 }}>of Indefinite</div>
                  ) : r.target_offering_amount ? (
                    <div style={{ fontSize: 9, color: 'var(--ink-4)', fontWeight: 400, marginTop: 1 }}>
                      of {window.fmtMoney(r.target_offering_amount)}
                    </div>
                  ) : null}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Cashflow chart */}
      <div className="card cashflow-card">
        <div className="cashflow-header">
          <div className="cashflow-title">
            <h3>Capital flow</h3>
            <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>
              {cashflowData?.bucket === 'month' ? 'Monthly reported raises across all RE filings'
                : cashflowData?.bucket === 'week' ? 'Weekly reported raises across all RE filings'
                : 'Daily reported raises across all RE filings'}
            </span>
          </div>
          <div className="range-tabs">
            {['30d','90d','180d','1y'].map(r => (
              <button key={r} className={range === r ? 'active' : ''} onClick={() => setRange(r)}>{r.toUpperCase()}</button>
            ))}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 40, padding: '14px 22px 4px' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="stat-label">Period total</div>
            <div className="stat-value" style={{ fontSize: 24, marginTop: 0 }}>
              {cashflowData ? window.fmtMoney(cashflowData.totals.raised) : '—'}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="stat-label">Last 24h</div>
            <div className="stat-value" style={{ fontSize: 24, marginTop: 0, color: 'var(--pos)' }}>
              {cashflowData ? (totalRaised24h ? window.fmtMoney(totalRaised24h) : '—') : '—'}
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="stat-label">Filings ({range})</div>
            <div className="stat-value" style={{ fontSize: 24, marginTop: 0 }}>
              {cashflowData ? cashflowData.totals.filings.toLocaleString() : '—'}
            </div>
          </div>
        </div>
        <div className="cashflow-chart">
          {cashflow ? <BarChart data={cashflow} width={1200} height={220} /> :
            <div className="skel" style={{ height: 200, width: '100%' }}></div>}
        </div>
      </div>

      {/* Two col: leaderboard + industry mix */}
      <div className="row-2col">
        <div className="card">
          <div className="card-header">
            <h3>Top sponsors by capital raised</h3>
            <a href="#/sponsors" className="btn ghost" onClick={(e) => { e.preventDefault(); navigate({ name: 'sponsors' }); }}>
              View all <I.arrow />
            </a>
          </div>
          <div>
            {!topSponsors && Array.from({ length: 8 }).map((_, i) => (
              <div className="leaderboard-row" key={i}>
                <div className="skel" style={{ height: 10, width: 18 }}></div>
                <div><div className="skel" style={{ height: 12, width: '60%' }}></div></div>
                <div className="skel" style={{ height: 12, width: 60 }}></div>
                <div className="skel" style={{ height: 12, width: 30 }}></div>
              </div>
            ))}
            {topSponsors && topSponsors.map((s, i) => (
              <div className="leaderboard-row" key={s.sponsor_id} onClick={() => navigate({ name: 'sponsor', id: s.sponsor_id })}>
                <span className="lb-rank">{String(i + 1).padStart(2, '0')}</span>
                <div style={{ minWidth: 0 }}>
                  <div className="lb-name">{s.canonical_name}</div>
                  <div className="lb-meta">
                    {s.deals_count} attributed {s.deals_count === 1 ? 'SPV' : 'SPVs'}{s.primary_city ? ` · ${s.primary_city}, ${s.primary_state_or_country || ''}`.replace(/, $/, '') : ''}
                  </div>
                </div>
                <div className="lb-amount">{window.fmtMoney(s.total_raised)}</div>
                <div className="lb-deals">{window.industryShort(s.industry_group_type)}</div>
              </div>
            ))}
          </div>
        </div>

        <IndustryMix navigate={navigate} />
      </div>

      {/* Volume vs capital — top sponsors split */}
      <div className="row-2col">
        <div className="card">
          <div className="card-header">
            <h3>Top deals by lifetime raise</h3>
            <a href="#/deals" className="btn ghost" onClick={(e) => { e.preventDefault(); navigate({ name: 'deals' }); }}>
              View all <I.arrow />
            </a>
          </div>
          <div>
            {!topDeals && Array.from({ length: 5 }).map((_, i) => (
              <div className="leaderboard-row" key={i}>
                <div className="skel" style={{ height: 10, width: 18 }}></div>
                <div><div className="skel" style={{ height: 12, width: '70%' }}></div></div>
                <div className="skel" style={{ height: 12, width: 60 }}></div>
                <div className="skel" style={{ height: 12, width: 30 }}></div>
              </div>
            ))}
            {topDeals && topDeals.map((d, i) => (
              <div className="leaderboard-row" key={d.deal_id} onClick={() => navigate({ name: 'deal', id: d.deal_id })}>
                <span className="lb-rank">{String(i + 1).padStart(2, '0')}</span>
                <div style={{ minWidth: 0 }}>
                  <div className="lb-name">{d.deal_name}</div>
                  <div className="lb-meta">
                    {d.filings_count} filings · {window.industryShort(d.industry_group_type)}
                  </div>
                </div>
                <div className="lb-amount">{window.fmtMoney(d.total_raised)}</div>
                <div className="lb-deals">{new Date(d.first_filing_date).getFullYear()}–{new Date(d.latest_filing_date).getFullYear().toString().slice(2)}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-header">
            <h3>Most active sponsors by deal count</h3>
            <span style={{ fontSize: 11, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>VOLUME</span>
          </div>
          <div>
            {!byCount && Array.from({ length: 5 }).map((_, i) => (
              <div className="leaderboard-row" key={i}>
                <div className="skel" style={{ height: 10, width: 18 }}></div>
                <div><div className="skel" style={{ height: 12, width: '60%' }}></div></div>
                <div className="skel" style={{ height: 12, width: 60 }}></div>
                <div className="skel" style={{ height: 12, width: 30 }}></div>
              </div>
            ))}
            {byCount && byCount.map((s, i) => (
              <div className="leaderboard-row" key={s.sponsor_id} onClick={() => navigate({ name: 'sponsor', id: s.sponsor_id })}>
                <span className="lb-rank">{String(i + 1).padStart(2, '0')}</span>
                <div style={{ minWidth: 0 }}>
                  <div className="lb-name">{s.canonical_name}</div>
                  <div className="lb-meta">
                    {window.industryShort(s.industry_group_type)}{s.primary_city ? ` · ${s.primary_city}, ${s.primary_state_or_country || ''}`.replace(/, $/, '') : ''}
                  </div>
                </div>
                <div className="lb-amount">{window.fmtMoney(s.total_raised)}</div>
                <div className="lb-deals">{s.deals_count} deals</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
}

function IndustryMix({ navigate }) {
  // Industry distribution across all indexed RE deals
  const segments = [
    { key: 'COMMERCIAL',  label: 'Commercial',         deals: 28840, raised: 198.6, pct: 55.4, sponsors: 3340 },
    { key: 'RESIDENTIAL', label: 'Residential',        deals: 18620, raised:  93.4, pct: 35.8, sponsors: 2080 },
    { key: 'OTHER',       label: 'Other Real Estate',  deals:  4568, raised: 209.4, pct:  8.8, sponsors:  636 },
  ];
  const totalRaised = segments.reduce((a, b) => a + b.raised, 0);
  const maxDeals = Math.max(...segments.map(s => s.deals));

  return (
    <div className="card">
      <div className="card-header">
        <h3>Industry mix</h3>
        <span style={{ fontSize: 11, color: 'var(--ink-4)', fontFamily: 'var(--font-mono)' }}>
          BY DEALS · BY CAPITAL
        </span>
      </div>
      <div style={{ padding: '8px 22px 0' }}>
        {/* Stacked bar — by capital */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-4)' }}>
            Share of $501B raised
          </span>
        </div>
        <div style={{ display: 'flex', height: 32, borderRadius: 4, overflow: 'hidden', border: '1px solid var(--rule)' }}>
          {segments.map((s, i) => {
            const pct = (s.raised / totalRaised) * 100;
            const colors = ['var(--accent)', 'color-mix(in oklab, var(--accent) 60%, var(--bg-sunk))', 'color-mix(in oklab, var(--accent) 30%, var(--bg-sunk))'];
            return (
              <div key={s.key}
                   onClick={() => navigate({ name: 'deals', industry: s.key })}
                   style={{
                     width: `${pct}%`, background: colors[i], cursor: 'pointer',
                     display: 'flex', alignItems: 'center', justifyContent: 'center',
                     fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 600,
                     color: i === 0 ? '#fff' : 'var(--ink)',
                     letterSpacing: '0.04em',
                   }}
                   title={`${s.label}: $${s.raised}B (${pct.toFixed(1)}%)`}>
                {pct > 8 ? `${pct.toFixed(0)}%` : ''}
              </div>
            );
          })}
        </div>

        {/* Per-segment rows */}
        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 14, paddingBottom: 16 }}>
          {segments.map((s, i) => {
            const dealPct = (s.deals / maxDeals) * 100;
            const colors = ['var(--accent)', 'color-mix(in oklab, var(--accent) 60%, var(--bg-sunk))', 'color-mix(in oklab, var(--accent) 30%, var(--bg-sunk))'];
            return (
              <div key={s.key} className="industry-row"
                   onClick={() => navigate({ name: 'deals', industry: s.key })}
                   style={{ cursor: 'pointer' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 8, height: 8, borderRadius: 2, background: colors[i] }}></span>
                    <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{s.label}</span>
                  </div>
                  <div style={{ display: 'flex', gap: 18, fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-2)' }}>
                    <span>{window.fmtInt(s.deals)} deals</span>
                    <span style={{ color: 'var(--ink)', fontWeight: 600 }}>${s.raised}B</span>
                  </div>
                </div>
                <div style={{ height: 4, background: 'var(--bg-sunk)', borderRadius: 2, overflow: 'hidden' }}>
                  <div style={{ width: `${dealPct}%`, height: '100%', background: colors[i] }}></div>
                </div>
                <div style={{ marginTop: 4, fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  {window.fmtInt(s.sponsors)} sponsors · avg ${(s.raised * 1000 / s.deals).toFixed(1)}M / deal
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.HomePage = HomePage;
window.Sparkline = Sparkline;
