// MaxAMove CRM — Dashboard View
// (Verse-of-the-day data + render lives in components/verse.jsx and is shared
// with the on-job screen and the worker portal so every surface shows the same
// verse on the same day.)

function Dashboard({ leads, jobs, onNavigate }) {
  leads = leads || [];
  jobs = jobs || [];

  // ── "Today" widget data — what needs attention right now? ────────────────────
  // Pulls live from Supabase estimates + the props (leads + jobs) and surfaces
  // items that need action: tentative holds waiting, sent estimates going stale,
  // jobs in the next 48hrs, signed estimates without a scheduled job. Each row
  // is one-tap to jump to that record.
  const [todayItems, setTodayItems] = React.useState([]);
  // ── Estimate accuracy widget ─────────────────────────────────────
  // Pulls completed estimates with all three snapshots (system / your quote / actual)
  // and shows how close each was. The first time you see "system avg +2.3 hrs" while
  // "your quote avg +0.4 hrs", you'll know which knob to turn.
  const [accuracy, setAccuracy] = React.useState({ count: 0, stats: null, recent: [] });
  React.useEffect(() => {
    if (!window.sb) return;
    (async () => {
      try {
        const { data: ests } = await window.sb.from('estimates')
          .select('id, number, pricing, customers(name), updated_at')
          .order('updated_at', { ascending: false }).limit(80);
        const rows = (ests || [])
          .map(e => {
            const p = e.pricing || {};
            const sys = +p.systemEstimateHours;
            const quote = +p.hours;
            const actual = +p.actualBillableHours;
            if (!isFinite(sys) || !isFinite(quote) || !isFinite(actual) || actual <= 0) return null;
            return {
              id: e.id, number: e.number,
              customer: (e.customers && e.customers.name) || 'Customer',
              when: p.actualCompletedAt || e.updated_at,
              sys, quote, actual,
              sysErr: +(actual - sys).toFixed(2),
              quoteErr: +(actual - quote).toFixed(2),
            };
          })
          .filter(Boolean);
        if (rows.length === 0) { setAccuracy({ count: 0, stats: null, recent: [] }); return; }
        const avg = arr => arr.reduce((s, n) => s + n, 0) / arr.length;
        const stats = {
          avgSysErr: +avg(rows.map(r => r.sysErr)).toFixed(2),
          avgQuoteErr: +avg(rows.map(r => r.quoteErr)).toFixed(2),
          avgSysAbs: +avg(rows.map(r => Math.abs(r.sysErr))).toFixed(2),
          avgQuoteAbs: +avg(rows.map(r => Math.abs(r.quoteErr))).toFixed(2),
          sysWithin1: Math.round(rows.filter(r => Math.abs(r.sysErr) <= 1).length / rows.length * 100),
          quoteWithin1: Math.round(rows.filter(r => Math.abs(r.quoteErr) <= 1).length / rows.length * 100),
        };
        setAccuracy({ count: rows.length, stats, recent: rows.slice(0, 5) });
      } catch (err) { console.warn('[accuracy widget]', err); }
    })();
  }, []);

  React.useEffect(() => {
    (async () => {
      const items = [];
      try {
        const tentativeLeads = leads.filter(l => l.stage === 'tentative');
        tentativeLeads.forEach(l => items.push({
          icon: 'clock', kind: 'tentative-lead',
          text: `${l.name}'s tentative hold — waiting on details`,
          sub: l.phone || l.email || '',
          go: () => onNavigate && onNavigate('leads'),
        }));
      } catch {}
      // Jobs starting in next 48 hours (or already in-progress)
      try {
        const now = Date.now();
        const soonCutoff = now + 48 * 3600 * 1000;
        const soon = jobs.filter(j => {
          if (j.status === 'completed' || j.status === 'cancelled') return false;
          const t = j.date ? new Date(j.date + 'T08:00').getTime() : null;
          return t && t >= now - 12*3600*1000 && t <= soonCutoff;
        });
        soon.forEach(j => items.push({
          icon: 'calendar', kind: 'upcoming-job',
          text: `Job for ${j.customerName || 'customer'} — ${j.date || 'soon'}`,
          sub: j.fromAddress ? `From ${j.fromAddress}` : '',
          go: () => onNavigate && onNavigate('jobs'),
        }));
      } catch {}
      // Stale sent estimates (sent 4+ days ago, no signature yet) + signed estimates without jobs
      try {
        if (window.sb) {
          const { data: ests } = await window.sb.from('estimates')
            .select('id, number, status, sent_at, signed_at, customers(name), pricing')
            .in('status', ['sent', 'signed'])
            .order('updated_at', { ascending: false }).limit(50);
          const fourDaysAgo = Date.now() - 4*86400*1000;
          (ests || []).forEach(e => {
            const customer = e.customers?.name || 'Customer';
            if (e.status === 'sent' && e.sent_at && new Date(e.sent_at).getTime() < fourDaysAgo) {
              items.push({
                icon: 'send', kind: 'stale-estimate',
                text: `${customer}'s estimate (#${e.number}) sent 4+ days ago — no response`,
                sub: 'Consider following up',
                go: () => onNavigate && onNavigate('estimates'),
              });
            }
          });
          // Signed estimates without a job scheduled yet
          const signedIds = (ests || []).filter(e => e.status === 'signed' && (e.pricing?.reservationType !== 'tentative')).map(e => e.id);
          if (signedIds.length) {
            const { data: matchedJobs } = await window.sb.from('jobs')
              .select('estimate_id').in('estimate_id', signedIds);
            const haveJobs = new Set((matchedJobs || []).map(j => j.estimate_id));
            (ests || []).filter(e => signedIds.includes(e.id) && !haveJobs.has(e.id)).forEach(e => {
              items.push({
                icon: 'check-circle', kind: 'unscheduled-job',
                text: `${e.customers?.name || 'Customer'} signed (#${e.number}) — schedule the job`,
                sub: 'No job created yet',
                go: () => onNavigate && onNavigate('estimates'),
              });
            });
          }
        }
      } catch (err) { console.warn('[today widget]', err); }
      setTodayItems(items);
    })();
  }, [leads, jobs, onNavigate]);


  const thisMonth = REVENUE_HISTORY[REVENUE_HISTORY.length - 1];
  const lastMonth = REVENUE_HISTORY[REVENUE_HISTORY.length - 2];
  const openLeads = leads.filter(l => l.stage === 'new' || l.stage === 'quoted').length;
  const bookedJobs = leads.filter(l => l.stage === 'booked').length;
  const unpaidTotal = jobs.filter(j => j.status !== 'completed').reduce((s, j) => s + (j.value || 0), 0);
  const upcomingJobs = jobs.filter(j => j.status !== 'completed').sort((a, b) => (a.date || '').localeCompare(b.date || '')).slice(0, 5);
  const recentLeads = leads.filter(l => l.stage === 'new').slice(0, 4);
  const conversionRate = leads.length > 0
    ? Math.round((leads.filter(l => l.stage === 'booked' || l.stage === 'completed').length / leads.length) * 100)
    : 0;
  const revChange = Math.round(((thisMonth.revenue - lastMonth.revenue) / lastMonth.revenue) * 100);

  const KPICard = ({ label, value, sub, subColor, icon, accent }) => (
    <div style={{ background: 'var(--card)', borderRadius: 16, padding: '20px 22px', border: '1px solid var(--border)', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, width: 4, height: '100%', background: accent, borderRadius: '16px 0 0 16px' }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted)', marginBottom: 8 }}>{label}</div>
          <div style={{ fontSize: 28, fontWeight: 900, fontFamily: 'Poppins', color: 'var(--text)', lineHeight: 1 }}>{value}</div>
          {sub && <div style={{ fontSize: 12, marginTop: 6, color: subColor || 'var(--muted)' }}>{sub}</div>}
        </div>
        <div style={{ opacity: 0.22, display: 'flex' }}><Icon name={icon} size={32} color={accent}/></div>
      </div>
    </div>
  );

  const maxRev = Math.max(...REVENUE_HISTORY.map(r => r.revenue));

  // ── Greeting ──────────────────────────────────────────────────────────
  // Greeting follows the clock so the page reads naturally whenever Gavin opens it.
  const _now = new Date();
  const _hr = _now.getHours();
  const greetingPhrase = _hr < 12 ? 'Good morning' : _hr < 17 ? 'Good afternoon' : 'Good evening';

  return (
    <div>
      <div style={{ marginBottom: 18 }}>
        <h1 style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 4 }}>{greetingPhrase}</h1>
        <p style={{ color: 'var(--muted)', fontSize: 14 }}>Here's what's happening with MaxAMove today — {_now.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</p>
      </div>

      <VerseOfTheDay style={{ marginBottom: 24 }} />

      {/* TODAY widget — what needs your attention right now (added per progressive-disclosure pass) */}
      <div style={{ marginBottom: 24, background: 'var(--card)', borderRadius: 16, padding: 22, border: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="bolt" size={18} color="var(--accent)"/>
            <h2 style={{ fontSize: 16, fontWeight: 800, fontFamily: 'Poppins' }}>Today</h2>
            <span style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600 }}>What needs your attention</span>
          </div>
          <span style={{ fontSize: 11, fontWeight: 700, color: todayItems.length > 0 ? 'var(--accent)' : 'var(--muted)' }}>{todayItems.length} {todayItems.length === 1 ? 'item' : 'items'}</span>
        </div>
        {todayItems.length === 0 ? (
          <div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>
            <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'center' }}><Icon name="sparkles" size={26} color="var(--accent)"/></div>
            All clear — nothing demanding your attention right now.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {todayItems.slice(0, 8).map((it, i) => (
              <button key={i} onClick={it.go}
                style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 10, background: 'var(--bg)', border: '1px solid transparent', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', transition: 'background .12s, border-color .12s' }}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--accent-light)'; e.currentTarget.style.borderColor = 'var(--accent)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'var(--bg)'; e.currentTarget.style.borderColor = 'transparent'; }}>
                <Icon name={it.icon} size={18} color="var(--accent)"/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text)' }}>{it.text}</div>
                  {it.sub && <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>{it.sub}</div>}
                </div>
                <span style={{ fontSize: 14, color: 'var(--muted)' }}>→</span>
              </button>
            ))}
            {todayItems.length > 8 && (
              <div style={{ padding: '8px 12px', fontSize: 11, color: 'var(--muted)', textAlign: 'center' }}>
                + {todayItems.length - 8} more
              </div>
            )}
          </div>
        )}
      </div>

      {/* KPI Row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        <KPICard label="Revenue This Month" value={`$${thisMonth.revenue.toLocaleString()}`} sub={`${revChange > 0 ? '▲' : '▼'} ${Math.abs(revChange)}% vs last month`} subColor={revChange > 0 ? '#16a34a' : '#ef4444'} icon="dollar-bill" accent="var(--accent)" />
        <KPICard label="Open Leads" value={openLeads} sub={`${leads.filter(l => l.stage === 'new').length} new, ${leads.filter(l => l.stage === 'quoted').length} quoted`} icon="leads-target" accent="#0ea5e9" />
        <KPICard label="Jobs This Month" value={thisMonth.jobs} sub={`${bookedJobs} upcoming confirmed`} icon="truck" accent="#f97316" />
        <KPICard label="Conversion Rate" value={`${conversionRate}%`} sub="Lead → Booked" icon="trending-up" accent="#22c55e" />
      </div>

      {/* ESTIMATE ACCURACY widget — system vs your quote vs actual */}
      {accuracy.count > 0 && accuracy.stats && (() => {
        const errColor = (e) => Math.abs(e) <= 0.5 ? '#16a34a' : Math.abs(e) <= 1 ? '#f59e0b' : '#ef4444';
        const sign = (n) => (n > 0 ? '+' : '') + n;
        const winner = Math.abs(accuracy.stats.avgQuoteAbs) < Math.abs(accuracy.stats.avgSysAbs) ? 'quote' : 'system';
        return (
          <div style={{ marginBottom: 24, background: 'var(--card)', borderRadius: 16, padding: 22, border: '1px solid var(--border)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="chart-bar" size={18} color="var(--accent)"/>
                <h2 style={{ fontSize: 16, fontWeight: 800, fontFamily: 'Poppins' }}>Estimate accuracy</h2>
                <span style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600 }}>System vs your quote vs actual</span>
              </div>
              <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--muted)' }}>{accuracy.count} completed {accuracy.count === 1 ? 'job' : 'jobs'}</span>
            </div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 16 }}>
              Positive = under-estimated (job ran long). Negative = over-estimated (finished early).
            </div>

            {/* Headline stat blocks */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 18 }}>
              <div style={{ padding: 14, background: 'var(--bg)', borderRadius: 12, border: winner === 'system' ? '2px solid var(--accent)' : '1px solid var(--border)', position: 'relative' }}>
                {winner === 'system' && <div style={{ position: 'absolute', top: -8, right: 10, fontSize: 9, fontWeight: 800, padding: '2px 7px', borderRadius: 5, background: 'var(--accent)', color: '#fff', letterSpacing: '.06em' }}>CLOSER</div>}
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--muted)', marginBottom: 6 }}>System estimate</div>
                <div style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', color: errColor(accuracy.stats.avgSysErr), lineHeight: 1 }}>
                  {sign(accuracy.stats.avgSysErr)} hr<span style={{ fontSize: 13, fontWeight: 700, color: 'var(--muted)' }}> avg</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>
                  Off by <b>{accuracy.stats.avgSysAbs} hr</b> on average · <b>{accuracy.stats.sysWithin1}%</b> within 1 hr
                </div>
              </div>
              <div style={{ padding: 14, background: 'var(--bg)', borderRadius: 12, border: winner === 'quote' ? '2px solid var(--accent)' : '1px solid var(--border)', position: 'relative' }}>
                {winner === 'quote' && <div style={{ position: 'absolute', top: -8, right: 10, fontSize: 9, fontWeight: 800, padding: '2px 7px', borderRadius: 5, background: 'var(--accent)', color: '#fff', letterSpacing: '.06em' }}>CLOSER</div>}
                <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--muted)', marginBottom: 6 }}>Your quote</div>
                <div style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', color: errColor(accuracy.stats.avgQuoteErr), lineHeight: 1 }}>
                  {sign(accuracy.stats.avgQuoteErr)} hr<span style={{ fontSize: 13, fontWeight: 700, color: 'var(--muted)' }}> avg</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>
                  Off by <b>{accuracy.stats.avgQuoteAbs} hr</b> on average · <b>{accuracy.stats.quoteWithin1}%</b> within 1 hr
                </div>
              </div>
            </div>

            {/* Recent comparisons table */}
            <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--muted)', marginBottom: 8 }}>Recent jobs</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1.4fr .8fr .8fr .8fr 1fr', gap: 8, fontSize: 11, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '.06em', padding: '6px 4px' }}>
              <div>Customer</div>
              <div style={{ textAlign: 'right' }}>System</div>
              <div style={{ textAlign: 'right' }}>Quote</div>
              <div style={{ textAlign: 'right' }}>Actual</div>
              <div style={{ textAlign: 'right' }}>Δ vs quote</div>
            </div>
            {accuracy.recent.map(r => (
              <div key={r.id} style={{ display: 'grid', gridTemplateColumns: '1.4fr .8fr .8fr .8fr 1fr', gap: 8, padding: '10px 4px', borderTop: '1px solid var(--border)', fontSize: 13, alignItems: 'center' }}>
                <div>
                  <div style={{ fontWeight: 700, color: 'var(--text)' }}>{r.customer}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted)' }}>#{r.number}</div>
                </div>
                <div style={{ textAlign: 'right', color: 'var(--muted)', fontVariantNumeric: 'tabular-nums' }}>{r.sys} hr</div>
                <div style={{ textAlign: 'right', color: 'var(--muted)', fontVariantNumeric: 'tabular-nums' }}>{r.quote} hr</div>
                <div style={{ textAlign: 'right', fontWeight: 800, color: 'var(--text)', fontVariantNumeric: 'tabular-nums' }}>{r.actual} hr</div>
                <div style={{ textAlign: 'right', fontWeight: 800, color: errColor(r.quoteErr), fontVariantNumeric: 'tabular-nums' }}>{sign(r.quoteErr)} hr</div>
              </div>
            ))}
          </div>
        );
      })()}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
        {/* Revenue Chart */}
        <div style={{ background: 'var(--card)', borderRadius: 16, padding: 22, border: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
            <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins' }}>Revenue — Last 6 Months</div>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>Monthly</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 100 }}>
            {REVENUE_HISTORY.map((r, i) => {
              const isLast = i === REVENUE_HISTORY.length - 1;
              const h = Math.round((r.revenue / maxRev) * 100);
              return (
                <div key={r.month} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                  <div style={{ fontSize: 10, color: isLast ? 'var(--accent)' : 'var(--muted)', fontWeight: 700 }}>${(r.revenue / 1000).toFixed(0)}k</div>
                  <div style={{ width: '100%', height: h + '%', background: isLast ? 'var(--accent)' : 'var(--accent-light)', borderRadius: '6px 6px 0 0', transition: 'height 0.3s', minHeight: 4 }} />
                  <div style={{ fontSize: 10, color: isLast ? 'var(--accent)' : 'var(--muted)', fontWeight: isLast ? 800 : 400 }}>{r.month}</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Lead Sources */}
        <div style={{ background: 'var(--card)', borderRadius: 16, padding: 22, border: '1px solid var(--border)' }}>
          <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 16 }}>Lead Sources</div>
          {SOURCE_BREAKDOWN.map((s, i) => {
            const colors = ['var(--accent)', '#0ea5e9', '#f97316', '#22c55e', '#a855f7'];
            return (
              <div key={s.source} style={{ marginBottom: 10 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{s.source}</span>
                  <span style={{ fontSize: 13, fontWeight: 700, color: colors[i] }}>{s.pct}%</span>
                </div>
                <div style={{ height: 6, background: 'var(--border)', borderRadius: 3 }}>
                  <div style={{ height: '100%', width: s.pct + '%', background: colors[i], borderRadius: 3, transition: 'width 0.4s' }} />
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        {/* Upcoming Jobs */}
        <div style={{ background: 'var(--card)', borderRadius: 16, padding: 22, border: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins' }}>Upcoming Jobs</div>
            <button onClick={() => onNavigate('jobs')} style={{ fontSize: 12, color: 'var(--accent)', background: 'none', border: 'none', cursor: 'pointer', fontWeight: 700 }}>View all →</button>
          </div>
          {upcomingJobs.length === 0 && <div style={{ color: 'var(--muted)', fontSize: 14 }}>No upcoming jobs</div>}
          {upcomingJobs.map(job => {
            const days = daysUntil(job.date);
            return (
              <div key={job.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
                <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                  <div style={{ width: 36, height: 36, borderRadius: 9, background: 'var(--accent-light)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="truck" size={18} color="var(--accent)"/></div>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 13 }}>{job.customer}</div>
                    <div style={{ fontSize: 11, color: 'var(--muted)' }}>{job.from} → {job.to}</div>
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontWeight: 800, fontSize: 13, color: days <= 2 ? '#ef4444' : days <= 7 ? '#f97316' : 'var(--text)' }}>
                    {days === 0 ? 'Today' : days === 1 ? 'Tomorrow' : `In ${days}d`}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--muted)' }}>${job.value.toLocaleString()}</div>
                </div>
              </div>
            );
          })}
        </div>

        {/* New Leads */}
        <div style={{ background: 'var(--card)', borderRadius: 16, padding: 22, border: '1px solid var(--border)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins' }}>New Leads</div>
            <button onClick={() => onNavigate('leads')} style={{ fontSize: 12, color: 'var(--accent)', background: 'none', border: 'none', cursor: 'pointer', fontWeight: 700 }}>View pipeline →</button>
          </div>
          {recentLeads.length === 0 && <div style={{ color: 'var(--muted)', fontSize: 14 }}>No new leads</div>}
          {recentLeads.map(lead => (
            <div key={lead.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 800, fontSize: 13 }}>
                  {lead.name.split(' ').map(n => n[0]).join('')}
                </div>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 13 }}>{lead.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--muted)' }}>{lead.fromCity} → {lead.toCity} · {lead.size}</div>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontWeight: 800, fontSize: 13, color: 'var(--accent)' }}>${lead.value.toLocaleString()}</div>
                <div style={{ fontSize: 11, color: 'var(--muted)' }}>{lead.source}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
