/* QuoteFlow Prototype · Installer admin, wired to window.QFStore.
   Dashboard metrics, kanban (working stage moves), contacts, lead drawer. */
function AdminApp({ onGoCustomer, onGoPortal, jump }) {
  const { Card, MetricCard, Button, IconButton, StatusBadge, Avatar, Tag, Select } = window.QuoteFlowDesignSystem_41788d;
  const store = useStore();
  const [active, setActive] = React.useState('dashboard');
  const [selId, setSelId] = React.useState(null);
  // Lifted screen-local UI state so it survives store-driven re-renders
  // (inline screen components get new identities on each notify()).
  const [range, setRange] = React.useState(0);   // Dashboard date-range (days; 0 = all)
  const [q, setQ] = React.useState('');           // Contacts search
  const [sel, setSel] = React.useState({});             // Contacts bulk selection {id:true}
  const [editing, setEditing] = React.useState(false);  // Lead drawer edit mode
  React.useEffect(() => { if (jump && jump.id) setSelId(jump.id); }, [jump && jump.n]);
  React.useEffect(() => { setEditing(false); }, [selId]);

  const nav = [
    { id: 'dashboard', label: 'Dashboard', icon: 'layout-dashboard' },
    { id: 'pipeline', label: 'Sales Pipeline', icon: 'git-branch' },
    { id: 'proposals', label: 'Proposals', icon: 'file-text' },
    { id: 'contacts', label: 'Contacts', icon: 'users' },
    { id: 'aftercare', label: 'After Care', icon: 'heart-handshake' },
    { id: 'tools', label: 'Quote Tools', icon: 'sliders-horizontal' },
    { id: 'settings', label: 'Settings', icon: 'settings' },
  ];

  const leads = store.getLeads();
  const lead = selId ? store.getLead(selId) : null;
  const profile = store.getProfile();

  // ---------------- Sidebar ----------------
  const Sidebar = () => (
    <aside style={{ width: 240, flex: 'none', background: 'var(--surface-sidebar)', color: '#fff', display: 'flex', flexDirection: 'column', padding: 16, gap: 4, height: '100%', boxSizing: 'border-box' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px 16px' }}>
        <img src="../assets/logo-mark.svg" alt="" style={{ width: 26, height: 26 }} />
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: '#fff' }}>QuoteFlow</span>
      </div>
      {nav.map(n => {
        const on = active === n.id;
        return (
          <button key={n.id} onClick={() => setActive(n.id)}
            style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '0 14px', height: 42, border: 'none', cursor: 'pointer', textAlign: 'left', borderRadius: 'var(--radius-md)', fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: on ? 600 : 400, color: on ? '#fff' : 'rgba(247,244,236,0.62)', background: on ? 'rgba(255,255,255,0.10)' : 'transparent' }}>
            <Icon name={n.icon} size={19} color={on ? 'var(--mint)' : 'rgba(247,244,236,0.55)'} />{n.label}
          </button>
        );
      })}
      <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <button onClick={onGoCustomer} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '0 14px', height: 40, border: '1px solid rgba(255,255,255,0.16)', cursor: 'pointer', borderRadius: 'var(--radius-md)', background: 'transparent', color: 'var(--cream)', fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 600 }}>
          <Icon name="external-link" size={16} color="var(--mint)" /> Open customer quote tool
        </button>
        <button onClick={() => setActive('profile')} title="View your profile"
          style={{ display: 'flex', alignItems: 'center', gap: 11, padding: 10, border: 'none', cursor: 'pointer', textAlign: 'left', width: '100%',
            background: active === 'profile' ? 'rgba(255,255,255,0.14)' : 'rgba(255,255,255,0.06)', borderRadius: 'var(--radius-md)' }}>
          <Avatar name={profile.name} size={34} />
          <div style={{ lineHeight: 1.3, overflow: 'hidden', flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#fff' }}>{profile.name}</div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'rgba(247,244,236,0.5)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{profile.company.toUpperCase()}</div>
          </div>
          <Icon name="chevrons-up-down" size={16} color="rgba(247,244,236,0.5)" />
        </button>
      </div>
    </aside>
  );

  // ---------------- Dashboard ----------------
  const Dashboard = () => {
    const m = store.getMetrics(range || undefined);
    const recent = leads.slice(0, 6);
    const ranges = [['All time', 0], ['7 days', 7], ['30 days', 30], ['90 days', 90]];
    const exportCSV = () => window.downloadText('quoteflow-leads.csv', store.leadsCSV());
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
          <div>
            <h1 style={{ fontSize: 30 }}>Welcome back, Greenline</h1>
            <p style={{ marginTop: 6, fontSize: 15, color: 'var(--text-muted)' }}>Every quote your tools generate lands here live. You currently have <b style={{ color: 'var(--text-strong)' }}>{m.open} open leads</b>.</p>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <div style={{ display: 'inline-flex', gap: 3, padding: 3, background: 'var(--surface-sunken)', borderRadius: 'var(--radius-full)' }}>
              {ranges.map(([label, days]) => (
                <button key={days} onClick={() => setRange(days)}
                  style={{ height: 32, padding: '0 13px', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-full)', whiteSpace: 'nowrap', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 12.5, background: range === days ? 'var(--ink-900)' : 'transparent', color: range === days ? '#fff' : 'var(--text-muted)' }}>{label}</button>
              ))}
            </div>
            <Button variant="secondary" size="sm" iconLeft={<Icon name="download" size={15} />} onClick={exportCSV}>Export CSV</Button>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: 16 }}>
          <MetricCard label={range ? 'Leads (' + range + 'd)' : 'Total leads'} value={m.total} icon={<Icon name="users" size={20} />} />
          <MetricCard dark label="Won quote value" value={gbp(m.wonValue)} />
          <MetricCard label="New leads" value={m.newLeads} icon={<Icon name="user-plus" size={20} />} />
          <MetricCard label="Proposals sent" value={m.proposalsSent} icon={<Icon name="file-text" size={20} />} />
          <MetricCard label="Conversion" value={m.conversion + '%'} icon={<Icon name="trending-up" size={20} />} />
          <MetricCard label="Deposits collected" value={gbp(m.deposits)} icon={<Icon name="wallet" size={20} />} />
          <MetricCard label="Recurring revenue / yr" value={gbp(m.recurring)} icon={<Icon name="repeat" size={20} />} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 320px', gap: 20, alignItems: 'start' }}>
          <LeadsChart store={store} days={range || 30} />
          <ToolStats store={store} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 340px', gap: 20, alignItems: 'start' }}>
          <Card padding={0}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '18px 24px', borderBottom: '1px solid var(--border-default)' }}>
              <h2 style={{ fontSize: 20 }}>Recent leads</h2>
              <Button variant="ghost" size="sm" iconRight={<Icon name="arrow-right" size={15} />} onClick={() => setActive('pipeline')}>Open pipeline</Button>
            </div>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-sans)' }}>
              <thead><tr style={{ textAlign: 'left' }}>{['Customer', 'Quote tool', 'Value', 'Status', 'Created'].map(h => <th key={h} style={{ padding: '11px 24px', fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-faint)', borderBottom: '1px solid var(--border-default)' }}>{h}</th>)}</tr></thead>
              <tbody>
                {recent.map((l, i) => (
                  <tr key={l.id} onClick={() => setSelId(l.id)} style={{ borderBottom: i < recent.length - 1 ? '1px solid var(--slate-100)' : 'none', cursor: 'pointer' }}>
                    <td style={{ padding: '13px 24px' }}><div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Avatar name={l.name} size={32} /><span style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{l.name}</span></div></td>
                    <td style={{ padding: '13px 24px', fontSize: 14, color: 'var(--text-body)' }}>{l.system}</td>
                    <td style={{ padding: '13px 24px', fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{gbp(l.value)}</td>
                    <td style={{ padding: '13px 24px' }}><StatusBadge status={l.stage} /></td>
                    <td style={{ padding: '13px 24px', fontSize: 13, color: 'var(--text-muted)' }}>{store.fmtDate(l.createdAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>

          <ActivityFeed store={store} onOpen={setSelId} />
        </div>
      </div>
    );
  };

  // ---------------- Contacts ----------------
  const Contacts = () => {
    const rows = leads.filter(l => q === '' || (l.name + l.email + l.loc).toLowerCase().includes(q.toLowerCase()));
    const selIds = Object.keys(sel).filter(k => sel[k]);
    const selCount = selIds.length;
    const allChecked = rows.length > 0 && rows.every(l => sel[l.id]);
    const toggleAll = () => { const next = {}; if (!allChecked) rows.forEach(l => { next[l.id] = true; }); setSel(next); };
    const toggleOne = (id) => setSel(s => Object.assign({}, s, { [id]: !s[id] }));
    const clearSel = () => setSel({});
    const Check = ({ on }) => (
      <span style={{ width: 18, height: 18, flex: 'none', borderRadius: 5, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: on ? 'var(--primary)' : 'var(--surface-card)', border: on ? '1.5px solid var(--primary)' : '1.5px solid var(--border-strong)' }}>{on && <Icon name="check" size={12} color="#fff" stroke={3} />}</span>
    );
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
          <div><h1 style={{ fontSize: 30 }}>Contacts</h1><p style={{ marginTop: 6, fontSize: 15, color: 'var(--text-muted)' }}>Everyone who's come through your quote tools. Select rows for bulk actions.</p></div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ position: 'relative', width: 280 }}>
              <span style={{ position: 'absolute', left: 16, top: 13, color: 'var(--text-faint)' }}><Icon name="search" size={16} /></span>
              <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search name, email or area…" style={{ width: '100%', height: 44, boxSizing: 'border-box', padding: '0 18px 0 42px', fontFamily: 'var(--font-sans)', fontSize: 14, color: 'var(--text-strong)', background: 'var(--surface-card)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-full)', outline: 'none' }} />
            </div>
            <Button variant="secondary" iconLeft={<Icon name="download" size={15} />} onClick={() => window.downloadText('quoteflow-contacts.csv', store.leadsCSV())}>Export CSV</Button>
          </div>
        </div>

        {/* bulk action bar */}
        {selCount > 0 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 18px', background: 'var(--indigo-900)', borderRadius: 'var(--radius-md)', color: 'var(--cream)', flexWrap: 'wrap' }}>
            <span style={{ fontSize: 13.5, fontWeight: 600 }}>{selCount} selected</span>
            <span style={{ width: 1, height: 20, background: 'rgba(255,255,255,0.2)' }} />
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, color: 'var(--text-on-dark-muted)' }}>
              <Icon name="git-branch" size={15} color="var(--mint)" /> Move to
              <select onChange={e => { if (e.target.value) { store.bulkStage(selIds, e.target.value); clearSel(); } }} defaultValue=""
                style={{ appearance: 'none', WebkitAppearance: 'none', padding: '6px 26px 6px 10px', fontFamily: 'var(--font-sans)', fontSize: 12.5, fontWeight: 600, color: 'var(--indigo-900)', background: 'var(--cream) url("data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2712%27 height=%2712%27 viewBox=%270 0 24 24%27 fill=%27none%27 stroke=%27%2322163C%27 stroke-width=%273%27 stroke-linecap=%27round%27%3E%3Cpolyline points=%276 9 12 15 18 9%27/%3E%3C/svg%3E") no-repeat right 8px center', border: 'none', borderRadius: 'var(--radius-full)', cursor: 'pointer', outline: 'none' }}>
                <option value="" disabled>Stage…</option>
                {store.STAGES.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, color: 'var(--text-on-dark-muted)' }}>
              <Icon name="user-round" size={15} color="var(--mint)" /> Assign
              <select onChange={e => { if (e.target.value) { store.bulkAssign(selIds, e.target.value); clearSel(); } }} defaultValue=""
                style={{ appearance: 'none', WebkitAppearance: 'none', padding: '6px 26px 6px 10px', fontFamily: 'var(--font-sans)', fontSize: 12.5, fontWeight: 600, color: 'var(--indigo-900)', background: 'var(--cream) url("data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 width=%2712%27 height=%2712%27 viewBox=%270 0 24 24%27 fill=%27none%27 stroke=%27%2322163C%27 stroke-width=%273%27 stroke-linecap=%27round%27%3E%3Cpolyline points=%276 9 12 15 18 9%27/%3E%3C/svg%3E") no-repeat right 8px center', border: 'none', borderRadius: 'var(--radius-full)', cursor: 'pointer', outline: 'none' }}>
                <option value="" disabled>Owner…</option>
                {store.OWNERS.map(o => <option key={o} value={o}>{o}</option>)}
              </select>
            </span>
            <span style={{ flex: 1 }} />
            <button onClick={() => { if (confirm('Delete ' + selCount + ' contact' + (selCount > 1 ? 's' : '') + '? This cannot be undone.')) { store.deleteLeads(selIds); clearSel(); } }}
              style={{ display: 'inline-flex', alignItems: 'center', gap: 6, height: 32, padding: '0 14px', border: 'none', cursor: 'pointer', borderRadius: 'var(--radius-full)', background: 'var(--error)', color: '#fff', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 12.5 }}>
              <Icon name="trash-2" size={14} color="#fff" /> Delete
            </button>
            <button onClick={clearSel} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, height: 32, padding: '0 12px', border: '1px solid rgba(255,255,255,0.25)', cursor: 'pointer', borderRadius: 'var(--radius-full)', background: 'transparent', color: 'var(--cream)', fontFamily: 'var(--font-sans)', fontWeight: 600, fontSize: 12.5 }}>Clear</button>
          </div>
        )}

        <Card padding={0}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontFamily: 'var(--font-sans)' }}>
            <thead><tr style={{ textAlign: 'left' }}>
              <th style={{ padding: '11px 16px 11px 24px', borderBottom: '1px solid var(--border-default)', width: 20 }}><span onClick={toggleAll} style={{ cursor: 'pointer', display: 'inline-flex' }}><Check on={allChecked} /></span></th>
              {['Contact', 'Interest', 'Area', 'Value', 'Status', ''].map((h, i) => <th key={i} style={{ padding: '11px 24px', fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-faint)', borderBottom: '1px solid var(--border-default)' }}>{h}</th>)}
            </tr></thead>
            <tbody>
              {rows.map((l, i) => (
                <tr key={l.id} style={{ borderBottom: i < rows.length - 1 ? '1px solid var(--slate-100)' : 'none', background: sel[l.id] ? 'var(--primary-soft)' : 'transparent' }}>
                  <td style={{ padding: '13px 16px 13px 24px' }} onClick={() => toggleOne(l.id)}><span style={{ cursor: 'pointer', display: 'inline-flex' }}><Check on={!!sel[l.id]} /></span></td>
                  <td style={{ padding: '13px 24px', cursor: 'pointer' }} onClick={() => setSelId(l.id)}><div style={{ display: 'flex', alignItems: 'center', gap: 11 }}><Avatar name={l.name} size={36} /><div style={{ lineHeight: 1.3 }}><div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{l.name}</div><div style={{ fontSize: 12.5, color: 'var(--text-muted)' }}>{l.email}</div></div></div></td>
                  <td style={{ padding: '13px 24px', fontSize: 14, color: 'var(--text-body)', cursor: 'pointer' }} onClick={() => setSelId(l.id)}>{l.system}</td>
                  <td style={{ padding: '13px 24px', fontSize: 13.5, color: 'var(--text-muted)' }}>{l.loc}</td>
                  <td style={{ padding: '13px 24px', fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{gbp(l.value)}</td>
                  <td style={{ padding: '13px 24px' }}><StatusBadge status={l.stage} /></td>
                  <td style={{ padding: '13px 24px', textAlign: 'right', color: 'var(--text-faint)', cursor: 'pointer' }} onClick={() => setSelId(l.id)}><Icon name="chevron-right" size={18} /></td>
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan={7} style={{ padding: 32, textAlign: 'center', fontSize: 14, color: 'var(--text-faint)' }}>No contacts match.</td></tr>}
            </tbody>
          </table>
        </Card>
      </div>
    );
  };

  // ---------------- Lead drawer ----------------
  const Drawer = () => {
    if (!lead) return null;
    const acts = lead.activity.slice().reverse();
    return (
      <div onClick={() => setSelId(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(22,14,42,0.4)', zIndex: 60 }}>
        <div onClick={e => e.stopPropagation()} style={{ position: 'absolute', top: 0, right: 0, width: 440, maxWidth: '94vw', height: '100%', background: 'var(--surface-card)', boxShadow: 'var(--shadow-xl)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '20px 24px', borderBottom: '1px solid var(--border-default)' }}>
            <Avatar name={lead.name} size={44} />
            <div style={{ flex: 1 }}><div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, color: 'var(--text-strong)' }}>{lead.name}</div><div style={{ fontSize: 13, color: 'var(--text-muted)' }}>{lead.loc} · {lead.system}</div></div>
            <IconButton variant="ghost" ariaLabel={editing ? 'Stop editing' : 'Edit contact'} onClick={() => setEditing(e => !e)} style={editing ? { background: 'var(--primary-soft)', color: 'var(--primary)' } : {}}><Icon name="pencil" size={18} /></IconButton>
            <IconButton variant="ghost" ariaLabel="Close" onClick={() => setSelId(null)}><Icon name="x" size={20} /></IconButton>
          </div>
          <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 20, overflowY: 'auto' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <StatusBadge status={lead.stage} />
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26, color: 'var(--text-strong)' }}>{gbp(lead.value)}</span>
            </div>

            {/* working stage control */}
            <div style={{ background: 'var(--surface-sunken)', borderRadius: 'var(--radius-md)', padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-faint)', marginBottom: 6 }}>Stage</div>
                <Select value={lead.stage} onChange={e => store.setStage(lead.id, e.target.value)} options={store.STAGES} />
              </div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-faint)', marginBottom: 6 }}>Assigned to</div>
                <Select value={lead.owner} onChange={e => store.assign(lead.id, e.target.value)} options={store.OWNERS} />
              </div>
            </div>

            {editing ? <LeadEditBlock store={store} lead={lead} onDone={() => setEditing(false)} /> : (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {[['Quote tool', lead.system], ['Email', lead.email || '—'], ['Phone', lead.phone || '—'], ['Postcode', lead.postcode || '—'], ['Source', lead.source], ['Created', store.fmtDate(lead.createdAt) + ' 2026']].map(r => (
                <div key={r[0]}><div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{r[0]}</div><div style={{ marginTop: 3, fontSize: 13.5, color: 'var(--text-strong)', fontWeight: 500, wordBreak: 'break-word' }}>{r[1]}</div></div>
              ))}
            </div>
            )}

            {lead.config && lead.config.panels && (
              <div style={{ border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: 14 }}>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-faint)', marginBottom: 8 }}>Configured system</div>
                <div style={{ fontSize: 13.5, color: 'var(--text-body)', lineHeight: 1.6 }}>{lead.config.panels} panels{lead.config.battery ? ' · 9.5kWh battery' : ''}{lead.config.ev ? ' · EV charger' : ''}{lead.config.bird ? ' · bird protection' : ''}</div>
              </div>
            )}

            {/* proposal + deposit status */}
            {lead.proposal && (
              <div style={{ border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', overflow: 'hidden' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 14px', background: 'var(--surface-sunken)' }}>
                  <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>Proposal</span>
                  <StatusBadge status={lead.proposal.payment ? 'Accepted' : lead.proposal.status === 'accepted' ? 'Accepted' : 'Proposal sent'} />
                </div>
                <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}><span style={{ color: 'var(--text-muted)' }}>Total</span><span style={{ fontWeight: 700, color: 'var(--text-strong)' }}>{gbp(lead.proposal.total)}</span></div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}><span style={{ color: 'var(--text-muted)' }}>Deposit (15%)</span><span style={{ fontWeight: 600, color: 'var(--text-strong)' }}>{gbp(lead.proposal.deposit)}</span></div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}>
                    <span style={{ color: 'var(--text-muted)' }}>Deposit status</span>
                    {lead.proposal.payment
                      ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontWeight: 600, color: 'var(--accent-deep)' }}><Icon name="check-circle" size={14} color="var(--accent-deep)" /> Paid ····{lead.proposal.payment.last4}</span>
                      : <span style={{ color: 'var(--text-faint)' }}>Awaiting payment</span>}
                  </div>
                </div>
              </div>
            )}

            {/* survey + install milestones */}
            <ProjectBlock store={store} lead={lead} />

            {/* email / SMS notification log */}
            <MessagesBlock store={store} lead={lead} />

            <div>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-faint)', marginBottom: 10 }}>Activity</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                {acts.map((a, i) => (
                  <div key={i} style={{ display: 'flex', gap: 11 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: i === 0 ? 'var(--primary)' : 'var(--slate-300)', marginTop: 5, flex: 'none' }} /><div><div style={{ fontSize: 13.5, color: 'var(--text-strong)' }}>{a.label}</div><div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{store.fmtTime(a.ts)}</div></div></div>
                ))}
              </div>
            </div>
          </div>
          <div style={{ marginTop: 'auto', display: 'flex', gap: 10, padding: 20, borderTop: '1px solid var(--border-default)' }}>
            <IconButton variant="outline" ariaLabel="Delete contact" onClick={() => { if (confirm('Delete ' + lead.name + '? This cannot be undone.')) { var id = lead.id; setSelId(null); store.deleteLead(id); } }} style={{ color: 'var(--error)', borderColor: 'var(--error)' }}><Icon name="trash-2" size={18} /></IconButton>
            <Button variant="secondary" style={{ flex: 1 }} iconLeft={<Icon name="phone" size={16} />} onClick={() => store.addActivity(lead.id, 'Logged a call')}>Log call</Button>
            {lead.proposal
              ? <Button variant="primary" style={{ flex: 1 }} iconLeft={<Icon name="external-link" size={16} />} onClick={onGoPortal}>Open in portal</Button>
              : <Button variant="primary" style={{ flex: 1 }} iconLeft={<Icon name="send" size={16} />} onClick={() => store.sendProposal(lead.id)}>Send proposal</Button>}
          </div>
        </div>
      </div>
    );
  };

  const Screen = { dashboard: Dashboard, pipeline: function () { return <PipelineBoard store={store} onOpen={setSelId} />; }, contacts: Contacts,
    proposals: function () { return <AdminProposals store={store} onOpen={setSelId} />; },
    aftercare: function () { return <AdminAfterCare store={store} onOpen={setSelId} />; },
    tools: function () { return <AdminQuoteTools store={store} onPreview={onGoCustomer} />; },
    settings: function () { return <AdminSettings store={store} />; },
    profile: function () { return <AdminProfile store={store} onBack={() => setActive('dashboard')} />; } }[active];
  return (
    <div style={{ display: 'flex', height: '100%', overflow: 'hidden' }}>
      <Sidebar />
      <main style={{ flex: 1, overflowY: 'auto', padding: '30px 34px' }}>
        <div style={{ maxWidth: 1180, margin: '0 auto' }}><Screen /></div>
      </main>
      <Drawer />
    </div>
  );
}
window.AdminApp = AdminApp;
