// MaxAMove CRM — Customers, Crew & Reports views

// ─── CUSTOMERS ───
function CustomersView() {
  const [customers, setCustomers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState('');
  const [selected, setSelected] = React.useState(null);
  const [showAdd, setShowAdd] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [error, setError] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  async function refresh() {
    setLoading(true); setError('');
    try {
      const list = await window.listCustomers();
      setCustomers(list);
    } catch (e) {
      setError(e.message || 'Failed to load customers');
    } finally {
      setLoading(false);
    }
  }
  React.useEffect(() => { refresh(); }, []);

  async function handleCreate(form) {
    setSaving(true); setError('');
    try {
      await window.createCustomer(form);
      setShowAdd(false);
      await refresh();
    } catch (e) { setError(e.message); }
    finally { setSaving(false); }
  }

  async function handleUpdate(id, form) {
    setSaving(true); setError('');
    try {
      await window.updateCustomer(id, form);
      setEditing(null);
      await refresh();
    } catch (e) { setError(e.message); }
    finally { setSaving(false); }
  }

  const filtered = customers.filter(c =>
    (c.name || '').toLowerCase().includes(search.toLowerCase()) ||
    (c.email || '').toLowerCase().includes(search.toLowerCase()) ||
    (c.phone || '').includes(search)
  );
  const sel = customers.find(c => c.id === selected);

  const totalLifetimeValue = customers.reduce((s, c) => s + (c.totalSpent || 0), 0);

  return (
    <div style={{ display: 'flex', gap: 20, height: '100%' }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, gap: 10, flexWrap: 'wrap' }}>
          <div>
            <h1 style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 2 }}>Customers</h1>
            <p style={{ color: 'var(--muted)', fontSize: 14 }}>
              {loading ? 'Loading…' : `${customers.length} contacts · $${totalLifetimeValue.toLocaleString()} lifetime value`}
            </p>
          </div>
          <button onClick={() => setShowAdd(true)}
            style={{ padding: '9px 18px', borderRadius: 10, background: 'linear-gradient(135deg,#14C6BF,#3DCC7E)', color: '#fff', border: 'none', cursor: 'pointer', fontWeight: 700, fontFamily: 'inherit', fontSize: 13 }}>
            + New Customer
          </button>
        </div>

        {error && (
          <div style={{ background: '#fef2f2', border: '1px solid #fecaca', color: '#b91c1c', padding: '10px 14px', borderRadius: 9, fontSize: 13, marginBottom: 14, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>{error}</span>
            <button onClick={refresh} style={{ background: 'transparent', border: 'none', color: '#b91c1c', cursor: 'pointer', fontWeight: 700 }}>Retry</button>
          </div>
        )}

        <div style={{ marginBottom: 14, position: 'relative' }}>
          <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', display: 'inline-flex' }}><Icon name="search" size={16} color="var(--muted)"/></span>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search by name, email or phone…"
            style={{ width: '100%', padding: '10px 14px 10px 38px', borderRadius: 10, border: '1.5px solid var(--border)', background: 'var(--card)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' }} />
        </div>

        <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg)' }}>
                {['Customer', 'Contact', 'Jobs', 'Total Spent', 'Last Move', 'Tags', 'Rating'].map(h => (
                  <th key={h} style={{ padding: '11px 14px', textAlign: 'left', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((c, i) => (
                <tr key={c.id} onClick={() => setSelected(c.id === selected ? null : c.id)}
                  style={{ borderTop: '1px solid var(--border)', background: selected === c.id ? 'var(--accent-light)' : i % 2 === 0 ? 'transparent' : 'var(--bg)', cursor: 'pointer' }}>
                  <td style={{ padding: '12px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--accent)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 12, flexShrink: 0 }}>
                        {(c.name || '?').split(/\s+/).filter(Boolean).slice(0,2).map(n => n[0]).join('').toUpperCase()}
                      </div>
                      <div style={{ fontWeight: 700 }}>{c.name}</div>
                    </div>
                  </td>
                  <td style={{ padding: '12px 14px' }}>
                    <div style={{ fontSize: 12 }}>{c.email || '—'}</div>
                    <div style={{ fontSize: 11, color: 'var(--muted)' }}>{c.phone || '—'}</div>
                  </td>
                  <td style={{ padding: '12px 14px', fontWeight: 700, textAlign: 'center' }}>{c.jobs || 0}</td>
                  <td style={{ padding: '12px 14px', fontWeight: 800, color: 'var(--accent)' }}>${(c.totalSpent || 0).toLocaleString()}</td>
                  <td style={{ padding: '12px 14px', color: 'var(--muted)', fontSize: 12 }}>{fmtShortDate(c.lastMove)}</td>
                  <td style={{ padding: '12px 14px' }}>
                    {(c.tags || []).map(t => (
                      <span key={t} style={{ display: 'inline-block', background: t === 'vip' ? '#fef3c7' : t === 'commercial' ? '#eff6ff' : 'var(--bg)', color: t === 'vip' ? '#b45309' : t === 'commercial' ? '#2563eb' : 'var(--muted)', borderRadius: 4, padding: '2px 7px', fontSize: 10, fontWeight: 700, marginRight: 3, border: '1px solid ' + (t === 'vip' ? '#fde68a' : t === 'commercial' ? '#bfdbfe' : 'var(--border)') }}>{t}</span>
                    ))}
                  </td>
                  <td style={{ padding: '12px 14px' }}>
                    {c.rating ? <span style={{ color: '#f59e0b', fontWeight: 800, fontSize: 13 }}>{'★'.repeat(c.rating)}</span> : <span style={{ color: 'var(--muted)', fontSize: 12 }}>—</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {!loading && filtered.length === 0 && (
            <div style={{ textAlign: 'center', padding: '40px', color: 'var(--muted)' }}>
              {customers.length === 0 ? 'No customers yet. Click "+ New Customer" to add one.' : 'No customers match your search.'}
            </div>
          )}
          {loading && <div style={{ textAlign: 'center', padding: '40px', color: 'var(--muted)' }}>Loading customers…</div>}
        </div>
      </div>

      {/* Detail panel */}
      {sel && (
        <div style={{ width: 300, flexShrink: 0, background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', padding: 20, overflowY: 'auto', alignSelf: 'flex-start', position: 'sticky', top: 0 }}>
          <div style={{ textAlign: 'center', marginBottom: 16 }}>
            <div style={{ width: 60, height: 60, borderRadius: '50%', background: 'var(--accent)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 900, fontSize: 20, margin: '0 auto 10px' }}>
              {(sel.name || '?').split(/\s+/).filter(Boolean).slice(0,2).map(n => n[0]).join('').toUpperCase()}
            </div>
            <div style={{ fontWeight: 900, fontSize: 16, fontFamily: 'Poppins' }}>{sel.name}</div>
            {sel.source && <div style={{ color: 'var(--muted)', fontSize: 12, marginTop: 4 }}>via {sel.source}</div>}
            {(sel.tags || []).map(t => <span key={t} style={{ display: 'inline-block', background: 'var(--accent-light)', color: 'var(--accent-dark)', borderRadius: 4, padding: '2px 7px', fontSize: 10, fontWeight: 700, margin: '2px' }}>{t}</span>)}
          </div>
          {[['Email', sel.email], ['Phone', sel.phone], ['Address', sel.address], ['Total Jobs', sel.jobs || 0], ['Lifetime Value', '$' + (sel.totalSpent || 0).toLocaleString()], ['Last Move', fmtDate(sel.lastMove)]].map(([k, v]) => (
            <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid var(--border)', fontSize: 12 }}>
              <span style={{ color: 'var(--muted)', fontWeight: 600 }}>{k}</span>
              <span style={{ fontWeight: 700, textAlign: 'right', maxWidth: 160, wordBreak: 'break-all' }}>{v || '—'}</span>
            </div>
          ))}
          {sel.rating && <div style={{ marginTop: 12, textAlign: 'center', color: '#f59e0b', fontSize: 20 }}>{'★'.repeat(sel.rating)}</div>}
          {sel.notes && <div style={{ marginTop: 12, padding: 10, background: '#fffbeb', borderRadius: 8, fontSize: 12, color: '#78350f' }}>{sel.notes}</div>}
          <button onClick={() => setEditing({ ...sel })}
            style={{ display: 'block', width: '100%', marginTop: 16, padding: '10px', borderRadius: 9, background: 'var(--bg)', border: '1.5px solid var(--border)', color: 'var(--text)', cursor: 'pointer', fontWeight: 700, fontSize: 13, fontFamily: 'inherit' }}>
            Edit customer
          </button>
        </div>
      )}

      {/* Add / Edit modal */}
      {(showAdd || editing) && (
        <CustomerForm
          initial={editing || {}}
          mode={editing ? 'edit' : 'create'}
          saving={saving}
          onCancel={() => { setShowAdd(false); setEditing(null); }}
          onSave={form => editing ? handleUpdate(editing.id, form) : handleCreate(form)}
        />
      )}
    </div>
  );
}

function CustomerForm({ initial, mode, saving, onCancel, onSave }) {
  const [form, setForm] = React.useState({
    name: initial.name || '',
    email: initial.email || '',
    phone: initial.phone || '',
    address: initial.address || '',
    source: initial.source || '',
    notes: initial.notes || '',
    rating: initial.rating || '',
    tags: (initial.tags || []).join(', '),
  });
  const u = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = e => {
    e.preventDefault();
    if (!form.name.trim()) return alert('Name is required.');
    onSave({
      name: form.name.trim(),
      email: form.email.trim().toLowerCase() || null,
      phone: form.phone.trim() || null,
      address: form.address.trim() || null,
      source: form.source.trim() || null,
      notes: form.notes.trim() || null,
      rating: form.rating ? Number(form.rating) : null,
      tags: form.tags.split(',').map(t => t.trim()).filter(Boolean),
    });
  };
  const inputStyle = { width: '100%', boxSizing: 'border-box', padding: '10px 12px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'var(--bg)', color: 'var(--text)', fontSize: 14, fontFamily: 'inherit', outline: 'none' };
  return (
    <div onClick={onCancel} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <form onClick={e => e.stopPropagation()} onSubmit={submit}
        style={{ background: 'var(--card)', borderRadius: 16, padding: 24, width: 480, maxWidth: '100%', maxHeight: '90vh', overflowY: 'auto' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
          <h2 style={{ fontSize: 18, fontWeight: 900, fontFamily: 'Poppins' }}>{mode === 'edit' ? 'Edit customer' : 'New customer'}</h2>
          <button type="button" onClick={onCancel} style={{ background: 'none', border: 'none', fontSize: 22, cursor: 'pointer', color: 'var(--muted)' }}>×</button>
        </div>
        {[
          { k: 'name',    l: 'Full name *', t: 'text',  ph: 'Jane Smith' },
          { k: 'email',   l: 'Email',       t: 'email', ph: 'jane@email.com' },
          { k: 'phone',   l: 'Phone',       t: 'tel',   ph: '(555) 000-0000' },
          { k: 'address', l: 'Address',     t: 'text',  ph: '123 Main St, Austin, TX' },
          { k: 'source',  l: 'How did they find us?', t: 'text', ph: 'Google / Referral / Yelp / etc.' },
          { k: 'tags',    l: 'Tags (comma-separated)', t: 'text', ph: 'vip, repeat, commercial' },
          { k: 'rating',  l: 'Rating (1-5)', t: 'number', ph: '5' },
        ].map(f => (
          <div key={f.k} style={{ marginBottom: 12 }}>
            <label style={{ display: 'block', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.07em', color: 'var(--muted)', marginBottom: 5 }}>{f.l}</label>
            <input type={f.t} value={form[f.k]} onChange={e => u(f.k, e.target.value)} placeholder={f.ph} style={inputStyle} />
          </div>
        ))}
        <div style={{ marginBottom: 16 }}>
          <label style={{ display: 'block', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.07em', color: 'var(--muted)', marginBottom: 5 }}>Notes</label>
          <textarea value={form.notes} onChange={e => u('notes', e.target.value)} rows={3} style={{ ...inputStyle, resize: 'vertical', minHeight: 70 }} />
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button type="button" onClick={onCancel} style={{ flex: 1, padding: '11px', borderRadius: 9, border: '1.5px solid var(--border)', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, color: 'var(--text)' }}>Cancel</button>
          <button type="submit" disabled={saving} style={{ flex: 2, padding: '11px', borderRadius: 9, background: 'linear-gradient(135deg,#14C6BF,#3DCC7E)', border: 'none', color: '#fff', cursor: saving ? 'wait' : 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14, opacity: saving ? 0.7 : 1 }}>
            {saving ? 'Saving…' : (mode === 'edit' ? 'Save changes' : 'Create customer')}
          </button>
        </div>
      </form>
    </div>
  );
}

// ─── CREW & FLEET ───
function CrewView() {
  const statusMap = { available: { bg: '#f0fdf4', color: '#16a34a', label: 'Available' }, 'on-job': { bg: '#fff7ed', color: '#f97316', label: 'On Job' }, 'day-off': { bg: '#f3f4f6', color: '#6b7280', label: 'Day Off' }, maintenance: { bg: '#fef2f2', color: '#ef4444', label: 'Needs Service' } };

  return (
    <div>
      <h1 style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 4 }}>Crew & Fleet</h1>
      <p style={{ color: 'var(--muted)', fontSize: 14, marginBottom: 24 }}>Manage your team and trucks</p>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
        {/* Crew */}
        <div>
          <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
            <span style={{display:'inline-flex',alignItems:'center',gap:7}}><Icon name="crew" size={15} color="var(--accent)"/> Team Members</span>
            <span style={{ color: 'var(--muted)', fontWeight: 400, fontSize: 12 }}>{SEED_CREW.length} total</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {SEED_CREW.map(c => {
              const s = statusMap[c.status];
              return (
                <div key={c.id} style={{ background: 'var(--card)', borderRadius: 12, padding: '14px 16px', border: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                    <div style={{ width: 42, height: 42, borderRadius: '50%', background: 'var(--accent)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 900, fontSize: 14 }}>{c.avatar}</div>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{c.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--muted)' }}>{c.role} · {c.jobs} jobs</div>
                      <div style={{ color: '#f59e0b', fontSize: 11, marginTop: 1 }}>{'★'.repeat(Math.floor(c.rating))} {c.rating}</div>
                    </div>
                  </div>
                  <div>
                    <span style={{ background: s.bg, color: s.color, padding: '4px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700 }}>{s.label}</span>
                    <div style={{ fontSize: 10, color: 'var(--muted)', marginTop: 4, textAlign: 'right' }}>{c.phone}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Fleet */}
        <div>
          <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 14, display: 'flex', justifyContent: 'space-between' }}>
            <span style={{display:'inline-flex',alignItems:'center',gap:7}}><Icon name="truck" size={15} color="var(--accent)"/> Fleet</span>
            <span style={{ color: 'var(--muted)', fontWeight: 400, fontSize: 12 }}>{SEED_TRUCKS.length} trucks</span>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {SEED_TRUCKS.map(t => {
              const sKey = t.status === 'available' ? 'available' : t.status === 'deployed' ? 'on-job' : t.status === 'maintenance' ? 'maintenance' : 'day-off';
              const s = statusMap[sKey];
              const serviceAlert = daysUntil(t.nextService) !== null && daysUntil(t.nextService) <= 14;
              return (
                <div key={t.id} style={{ background: 'var(--card)', borderRadius: 12, padding: '14px 16px', border: `1px solid ${serviceAlert ? '#fbbf24' : 'var(--border)'}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div>
                      <div style={{ fontWeight: 700, fontSize: 14 }}>{t.name} <span style={{ fontWeight: 400, color: 'var(--muted)' }}>({t.size})</span></div>
                      <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>Plate: {t.plate} · {t.mileage.toLocaleString()} mi</div>
                      <div style={{ fontSize: 11, color: serviceAlert ? '#b45309' : 'var(--muted)', marginTop: 3, fontWeight: serviceAlert ? 700 : 400, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                        {serviceAlert && <Icon name="alert" size={11}/>}<span>Service: {fmtShortDate(t.nextService)}</span>
                      </div>
                    </div>
                    <span style={{ background: s.bg, color: s.color, padding: '4px 10px', borderRadius: 20, fontSize: 11, fontWeight: 700 }}>{s.label}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── REPORTS ───
function ReportsView({ leads, jobs }) {
  leads = leads || [];
  jobs = jobs || [];
  const totalRevenue = REVENUE_HISTORY.reduce((s, r) => s + r.revenue, 0);
  const avgJobValue = jobs.length > 0 ? Math.round(jobs.reduce((s, j) => s + (j.value || 0), 0) / jobs.length) : 0;
  const convRate = leads.length > 0 ? Math.round((leads.filter(l => l.stage === 'booked' || l.stage === 'completed').length / leads.length) * 100) : 0;
  const completedJobs = jobs.filter(j => j.status === 'completed');
  const completedRevenue = completedJobs.reduce((s, j) => s + (j.value || 0), 0);
  const maxRev = Math.max(...REVENUE_HISTORY.map(r => r.revenue));

  const StatBox = ({ label, value, sub, accent }) => (
    <div style={{ background: 'var(--card)', borderRadius: 14, padding: '18px 20px', border: '1px solid var(--border)', borderTop: `3px solid ${accent}` }}>
      <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--muted)', marginBottom: 6 }}>{label}</div>
      <div style={{ fontSize: 26, fontWeight: 900, fontFamily: 'Poppins', color: 'var(--text)' }}>{value}</div>
      {sub && <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 4 }}>{sub}</div>}
    </div>
  );

  return (
    <div>
      <h1 style={{ fontSize: 22, fontWeight: 900, fontFamily: 'Poppins', marginBottom: 4 }}>Reports & Analytics</h1>
      <p style={{ color: 'var(--muted)', fontSize: 14, marginBottom: 24 }}>Business performance overview</p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
        <StatBox label="6-Month Revenue" value={'$' + totalRevenue.toLocaleString()} sub="Nov 2025 – Apr 2026" accent="var(--accent)" />
        <StatBox label="Avg Job Value" value={'$' + avgJobValue.toLocaleString()} sub={`Across ${jobs.length} jobs`} accent="#0ea5e9" />
        <StatBox label="Conversion Rate" value={convRate + '%'} sub="Leads → Booked" accent="#22c55e" />
        <StatBox label="Completed Revenue" value={'$' + completedRevenue.toLocaleString()} sub={`${completedJobs.length} completed jobs`} accent="#f97316" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20, marginBottom: 20 }}>
        {/* Revenue bar chart */}
        <div style={{ background: 'var(--card)', borderRadius: 14, padding: 22, border: '1px solid var(--border)' }}>
          <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 20 }}>Monthly Revenue Trend</div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, height: 140 }}>
            {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: 11, color: isLast ? 'var(--accent)' : 'var(--muted)', fontWeight: 700 }}>${(r.revenue / 1000).toFixed(0)}k</div>
                  <div title={`${r.month}: $${r.revenue.toLocaleString()}`} style={{ width: '100%', height: h + '%', background: isLast ? 'var(--accent)' : 'var(--accent-light)', borderRadius: '6px 6px 0 0', minHeight: 6, position: 'relative', cursor: 'default' }}>
                    <div style={{ position: 'absolute', bottom: '100%', left: '50%', transform: 'translateX(-50%)', background: '#333', color: '#fff', padding: '3px 7px', borderRadius: 5, fontSize: 10, whiteSpace: 'nowrap', pointerEvents: 'none', opacity: 0 }} className="tooltip">${r.revenue.toLocaleString()}</div>
                  </div>
                  <div style={{ fontSize: 11, color: isLast ? 'var(--accent)' : 'var(--muted)', fontWeight: isLast ? 800 : 500 }}>{r.month}</div>
                  <div style={{ fontSize: 10, color: 'var(--muted)' }}>{r.jobs} jobs</div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Pipeline value */}
        <div style={{ background: 'var(--card)', borderRadius: 14, padding: 22, border: '1px solid var(--border)' }}>
          <div style={{ fontWeight: 800, fontSize: 14, fontFamily: 'Poppins', marginBottom: 16 }}>Pipeline Value</div>
          {PIPELINE_STAGES.map(s => {
            const stageLeads = leads.filter(l => l.stage === s.id);
            const val = stageLeads.reduce((sum, l) => sum + (l.value || 0), 0);
            const totalVal = leads.reduce((sum, l) => sum + (l.value || 0), 0);
            const pct = totalVal > 0 ? Math.round((val / totalVal) * 100) : 0;
            return (
              <div key={s.id} style={{ marginBottom: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: s.color }}>{s.label}</span>
                  <span style={{ fontSize: 13, fontWeight: 800 }}>${val.toLocaleString()}</span>
                </div>
                <div style={{ height: 7, background: 'var(--border)', borderRadius: 4 }}>
                  <div style={{ height: '100%', width: pct + '%', background: s.color, borderRadius: 4 }} />
                </div>
                <div style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>{stageLeads.length} leads · {pct}%</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Lead source table */}
      <div style={{ background: 'var(--card)', borderRadius: 14, border: '1px solid var(--border)', overflow: 'hidden' }}>
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border)', fontWeight: 800, fontSize: 14, fontFamily: 'Poppins' }}>Lead Source Performance</div>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: 'var(--bg)' }}>
              {['Source', 'Leads', 'Share', 'Performance'].map(h => (
                <th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--muted)' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {SOURCE_BREAKDOWN.map((s, i) => {
              const colors = ['var(--accent)', '#0ea5e9', '#f97316', '#22c55e', '#a855f7'];
              return (
                <tr key={s.source} style={{ borderTop: '1px solid var(--border)' }}>
                  <td style={{ padding: '12px 16px', fontWeight: 700 }}>{s.source}</td>
                  <td style={{ padding: '12px 16px' }}>{s.leads}</td>
                  <td style={{ padding: '12px 16px', fontWeight: 700, color: colors[i] }}>{s.pct}%</td>
                  <td style={{ padding: '12px 16px', width: 200 }}>
                    <div style={{ height: 6, background: 'var(--border)', borderRadius: 3 }}>
                      <div style={{ height: '100%', width: s.pct + '%', background: colors[i], borderRadius: 3 }} />
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { CustomersView, CrewView, ReportsView });
