// Admin panel — back office for Lupipak.
// Sections: Dashboard · Leads · Products · Sectors · Settings
// Protected by username/password login; uses RBAC (admin / sales / viewer).

function useAuth() {
  const [user, setUser] = React.useState(undefined); // undefined = loading, null = logged out
  const refresh = React.useCallback(async () => {
    const me = await api.tryGet('/api/auth/me');
    setUser(me?.user || null);
  }, []);
  React.useEffect(() => { refresh(); }, [refresh]);
  return { user, setUser, refresh };
}

const can = (user, perm) => {
  if (!user) return false;
  if (user.access === 'admin') return true;
  if (user.access === 'sales' && (perm === 'read' || perm === 'leads:write')) return true;
  if (user.access === 'viewer' && perm === 'read') return true;
  return false;
};

function AdminAuthGate({ onExit, children }) {
  const auth = useAuth();
  if (auth.user === undefined) return <PageLoading />;
  if (auth.user === null) return <LoginScreen onAuth={auth.refresh} onExit={onExit} />;
  return React.cloneElement(children, { user: auth.user, refreshAuth: auth.refresh });
}

function LoginScreen({ onAuth, onExit }) {
  const [form, setForm] = React.useState({ username: '', password: '' });
  const [err, setErr] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  const submit = async (e) => {
    e?.preventDefault();
    setBusy(true); setErr(null);
    try {
      await api.post('/api/auth/login', form);
      await onAuth();
    } catch (e) {
      setErr(e.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'var(--bg)' }}>
      <form onSubmit={submit} style={{
        width: '100%', maxWidth: 380,
        background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 16,
        padding: 28, display: 'flex', flexDirection: 'column', gap: 16,
        boxShadow: 'var(--shadow-md)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 4 }}><Logo size={18} /></div>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', textAlign: 'center' }}>
          Back office · sign in
        </div>
        <h1 style={{
          fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 32, fontWeight: 400,
          letterSpacing: '-0.02em', margin: 0, textAlign: 'center', lineHeight: 1.1,
        }}>
          Welcome back.
        </h1>

        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>Username</span>
          <input value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} autoFocus autoComplete="username"
            style={{ padding: '11px 13px', fontFamily: 'inherit', background: '#fff', border: '.5px solid var(--line-2)', borderRadius: 10, outline: 'none' }}
          />
        </label>
        <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>Password</span>
          <input type="password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} autoComplete="current-password"
            style={{ padding: '11px 13px', fontFamily: 'inherit', background: '#fff', border: '.5px solid var(--line-2)', borderRadius: 10, outline: 'none' }}
          />
        </label>

        {err && <div style={{ padding: '10px 12px', background: 'rgba(212,83,42,.1)', borderRadius: 8, fontSize: 12, color: 'var(--accent)' }}>{err}</div>}

        <Button variant="primary" size="lg" full type="submit" disabled={busy || !form.username || !form.password}>
          {busy ? 'Signing in…' : 'Sign in'}
        </Button>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 6 }}>
          <button type="button" onClick={onExit} style={{ background: 'transparent', border: 0, color: 'var(--muted)', fontSize: 12, cursor: 'pointer' }}>← Back to site</button>
        </div>
      </form>
    </div>
  );
}

const STATUS_META = {
  'new':              { label: 'New',                color: '#D4532A', bg: 'rgba(212,83,42,.10)' },
  'contacted':        { label: 'Contacted',          color: '#3A362C', bg: 'rgba(58,54,44,.08)' },
  'waiting-design':   { label: 'Waiting · Design',   color: '#8B5E3C', bg: 'rgba(139,94,60,.10)' },
  'waiting-approval': { label: 'Waiting · Approval', color: '#6B5842', bg: 'rgba(107,88,66,.10)' },
  'production':       { label: 'Production',         color: '#4A5D3A', bg: 'rgba(74,93,58,.10)' },
  'completed':        { label: 'Completed',          color: '#2A4A2A', bg: 'rgba(42,74,42,.10)' },
};

const STATUS_ORDER = ['new', 'contacted', 'waiting-design', 'waiting-approval', 'production', 'completed'];

function Admin({ onExit, sectors, settings, setSettings, user, refreshAuth }) {
  const [section, setSection] = React.useState('leads');
  const [selectedLead, setSelectedLead] = React.useState(null);
  const [leads, setLeads] = React.useState([]);
  const [navOpen, setNavOpen] = React.useState(false);
  const isMobile = useMedia('(max-width: 900px)');

  const refreshLeads = React.useCallback(() => {
    api.get('/api/leads').then(setLeads).catch(() => {});
  }, []);

  React.useEffect(() => { refreshLeads(); }, [refreshLeads]);

  const updateLeadStatus = async (id, status) => {
    await api.put(`/api/leads/${id}/status`, { status });
    refreshLeads();
    if (selectedLead?.id === id) setSelectedLead(s => ({ ...s, status }));
  };

  const logout = async () => {
    await api.post('/api/auth/logout', {});
    refreshAuth?.();
  };

  const allItems = [
    { id: 'dashboard', label: 'Dashboard',     icon: <DashIcon/>, count: null, roles: ['admin','sales','viewer'] },
    { id: 'leads',     label: 'Leads',         icon: <LeadIcon/>, count: leads.filter(l => l.status === 'new').length, roles: ['admin','sales','viewer'] },
    { id: 'products',  label: 'Products',      icon: <ProdIcon/>, count: null, roles: ['admin','sales','viewer'] },
    { id: 'sectors',   label: 'Sectors',       icon: <SectIcon/>, count: null, roles: ['admin','sales','viewer'] },
    { id: 'team',      label: 'Team & Access', icon: <TeamIcon/>, count: null, roles: ['admin'] },
    { id: 'settings',  label: 'Settings',      icon: <SettIcon/>, count: null, roles: ['admin'] },
  ];
  const navItems = allItems.filter(i => i.roles.includes(user?.access));
  if (!navItems.find(i => i.id === section)) { /* current section removed for this role */ }

  const sidebar = (
    <aside style={{
      background: 'var(--paper)',
      borderRight: isMobile ? 'none' : '.5px solid var(--line)',
      borderBottom: isMobile ? '.5px solid var(--line)' : 'none',
      padding: isMobile ? '16px 14px' : '24px 16px',
      display: 'flex', flexDirection: 'column', gap: isMobile ? 14 : 24,
      position: isMobile ? 'static' : 'sticky', top: 0,
      height: isMobile ? 'auto' : '100vh',
    }}>
      <div style={{ padding: isMobile ? '0 4px' : '0 8px 16px', borderBottom: isMobile ? 'none' : '.5px solid var(--line)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Logo name={settings.company_name} onClick={onExit} />
          {isMobile && (
            <button onClick={() => setNavOpen(o => !o)}
              style={{
                padding: '6px 10px', borderRadius: 8, fontSize: 12,
                background: 'var(--bg-2)', border: '.5px solid var(--line-2)', color: 'var(--ink)', cursor: 'pointer',
              }}
            >
              {navOpen ? 'Hide' : 'Menu'}
            </button>
          )}
        </div>
        {!isMobile && (
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--muted)', marginTop: 8 }}>
            Back Office · v1.0
          </div>
        )}
      </div>

      {(!isMobile || navOpen) && (
        <nav style={{ display: 'flex', flexDirection: isMobile ? 'row' : 'column', flexWrap: 'wrap', gap: isMobile ? 6 : 2 }}>
          {navItems.map(item => {
            const active = section === item.id;
            return (
              <button
                key={item.id}
                onClick={() => { setSection(item.id); setSelectedLead(null); setNavOpen(false); }}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '9px 10px', borderRadius: 8, border: 0,
                  background: active ? 'var(--ink)' : 'transparent',
                  color: active ? 'var(--paper)' : 'var(--ink)',
                  fontSize: 13, fontWeight: 500, textAlign: 'left', cursor: 'pointer',
                  flex: isMobile ? '1 1 auto' : 'initial',
                }}
              >
                <span style={{ display: 'inline-flex', opacity: active ? 1 : 0.7 }}>{item.icon}</span>
                <span style={{ flex: 1 }}>{item.label}</span>
                {item.count != null && item.count > 0 && (
                  <span className="mono" style={{
                    fontSize: 10, padding: '2px 7px', borderRadius: 20,
                    background: active ? 'rgba(255,255,255,.15)' : 'var(--accent)',
                    color: active ? 'var(--paper)' : '#fff',
                  }}>
                    {item.count}
                  </span>
                )}
              </button>
            );
          })}
        </nav>
      )}

      {!isMobile && (
        <div style={{ marginTop: 'auto', padding: '12px 10px', background: 'var(--bg-2)', borderRadius: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%',
              background: 'linear-gradient(135deg, #3A362C, #8B857A)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontSize: 11, fontWeight: 500,
            }}>{(user?.name || '?').split(' ').map(x => x[0]).join('').slice(0,2)}</div>
            <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
              <span style={{ fontSize: 12, fontWeight: 500 }}>{user?.name || 'Signed in'}</span>
              <span className="mono" style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'capitalize' }}>{user?.access || '—'} access</span>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
            <button onClick={logout} style={{
              flex: 1, padding: '6px 8px', borderRadius: 6,
              background: 'transparent', border: '.5px solid var(--line-2)',
              fontSize: 11, color: 'var(--muted)', cursor: 'pointer',
            }}>Sign out</button>
            <button onClick={onExit} style={{
              flex: 1, padding: '6px 8px', borderRadius: 6,
              background: 'transparent', border: '.5px solid var(--line-2)',
              fontSize: 11, color: 'var(--muted)', cursor: 'pointer',
            }}>Exit →</button>
          </div>
        </div>
      )}
      {isMobile && (
        <div style={{ display: 'flex', gap: 6, alignSelf: 'flex-end' }}>
          <button onClick={logout} style={{ background: 'transparent', border: '.5px solid var(--line-2)', borderRadius: 6, padding: '5px 10px', fontSize: 11, color: 'var(--muted)', cursor: 'pointer' }}>Sign out</button>
          <button onClick={onExit} style={{ background: 'transparent', border: '.5px solid var(--line-2)', borderRadius: 6, padding: '5px 10px', fontSize: 11, color: 'var(--muted)', cursor: 'pointer' }}>Exit ↗</button>
        </div>
      )}
    </aside>
  );

  return (
    <div className="admin-shell">
      {sidebar}

      <main style={{ overflow: 'auto' }}>
        {section === 'dashboard' && <AdminDashboard leads={leads} sectors={sectors} onOpenLead={(l) => { setSection('leads'); setSelectedLead(l); }} />}
        {section === 'leads' && (
          selectedLead
            ? <LeadDetail lead={leads.find(l => l.id === selectedLead.id) || selectedLead} sectors={sectors} onBack={() => setSelectedLead(null)} onUpdateStatus={updateLeadStatus} />
            : <LeadsList leads={leads} sectors={sectors} onOpen={setSelectedLead} />
        )}
        {section === 'products' && <ProductsAdmin sectors={sectors} user={user} />}
        {section === 'sectors'  && <SectorsAdmin sectors={sectors} user={user} />}
        {section === 'team'     && user?.access === 'admin' && <TeamAdmin currentUser={user} />}
        {section === 'settings' && user?.access === 'admin' && <SettingsAdmin settings={settings} setSettings={setSettings} />}
      </main>
    </div>
  );
}

// ──────────────────────────────────────────────
// Dashboard
// ──────────────────────────────────────────────

function AdminDashboard({ leads, sectors, onOpenLead }) {
  const now = new Date();
  const newLeads = leads.filter(l => l.status === 'new').length;
  const inFlight = leads.filter(l => ['contacted','waiting-design','waiting-approval'].includes(l.status)).length;
  const completed = leads.filter(l => l.status === 'completed').length;
  const revenue = leads.reduce((s, l) => s + (l.total || 0), 0);
  const convertedRevenue = leads.filter(l => ['completed','production'].includes(l.status)).reduce((s, l) => s + (l.total || 0), 0);

  const [teamSales, setTeamSales] = React.useState(null);
  React.useEffect(() => {
    api.get('/api/analytics/team-sales').then(setTeamSales).catch(() => {});
  }, [leads]);

  const bySector = (sectors || []).map(s => ({
    sector: s, count: leads.filter(l => l.sector_id === s.id).length,
  }));
  const maxSectorCount = Math.max(...bySector.map(b => b.count), 1);
  const recent = [...leads].sort((a,b) => (b.created_at || '').localeCompare(a.created_at || '')).slice(0, 5);

  return (
    <div className="pad-lg" style={{ padding: '36px 40px 56px' }}>
      <AdminHeader
        eyebrow="Back office"
        title="Dashboard"
        desc={`Overview for ${now.toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' })}.`}
      />

      <div className="grid-4-mobile-2" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 28 }}>
        <StatCard label="New leads"       value={newLeads}   hint="Awaiting contact" trend="+" accent />
        <StatCard label="In progress"     value={inFlight}   hint="Contacted → Approval" trend="•" />
        <StatCard label="Converted"       value={completed}  hint="Completed deals" trend="✓" />
        <StatCard label="Converted value" value={`£${(convertedRevenue/1000).toFixed(1)}k`} hint="From completed + production" trend="£" />
      </div>

      <div className="two-col" style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 16, marginTop: 28 }}>
        <AdminCard>
          <AdminCardHead title="Pipeline" subtitle="By status" />
          <div style={{ padding: '8px 20px 20px' }}>
            {STATUS_ORDER.map(st => {
              const n = leads.filter(l => l.status === st).length;
              const pct = leads.length === 0 ? 0 : Math.round((n / leads.length) * 100);
              const meta = STATUS_META[st];
              return (
                <div key={st} style={{ display: 'grid', gridTemplateColumns: '160px 1fr 48px', alignItems: 'center', gap: 12, padding: '8px 0', borderBottom: '.5px solid var(--line)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: meta.color }}/>
                    <span style={{ fontSize: 12.5 }}>{meta.label}</span>
                  </div>
                  <div style={{ height: 6, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: meta.color, transition: 'width .6s cubic-bezier(.2,.8,.2,1)' }}/>
                  </div>
                  <span className="mono" style={{ fontSize: 11, textAlign: 'right', color: 'var(--muted)' }}>{n}</span>
                </div>
              );
            })}
          </div>
        </AdminCard>

        <AdminCard>
          <AdminCardHead title="Recent activity" subtitle="Latest leads" />
          <div style={{ padding: '4px 10px 12px' }}>
            {recent.length === 0 && <div style={{ padding: 20, fontSize: 12.5, color: 'var(--muted)', textAlign: 'center' }}>No leads yet.</div>}
            {recent.map(l => (
              <button
                key={l.id}
                onClick={() => onOpenLead(l)}
                style={{
                  width: '100%', textAlign: 'left',
                  display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: 12,
                  padding: '10px', background: 'transparent', border: 0, borderRadius: 8, cursor: 'pointer',
                }}
              >
                <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
                  <span style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {l.company}
                  </span>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>
                    {l.id} · {l.country} · £{(l.total || 0).toLocaleString('en-GB')}
                  </span>
                </div>
                <StatusPill status={l.status} />
              </button>
            ))}
          </div>
        </AdminCard>
      </div>

      {/* ── Sales by Team ── */}
      <div style={{ marginTop: 20 }}>
        <AdminCard>
          <AdminCardHead title="Sales by team" subtitle="Leads moved to Production or Completed" />
          <div style={{ padding: '8px 20px 24px' }}>
            {!teamSales && (
              <div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--muted)', fontSize: 12.5 }}>Loading…</div>
            )}
            {teamSales && teamSales.conversions.length === 0 && (
              <div style={{ padding: '20px 0', textAlign: 'center', color: 'var(--muted)', fontSize: 12.5 }}>
                No conversions yet — they'll appear here as leads are moved to Production or Completed.
              </div>
            )}
            {teamSales && teamSales.conversions.length > 0 && (() => {
              const maxRevenue = Math.max(...teamSales.conversions.map(c => c.revenue), 1);
              const totalDeals = teamSales.conversions.reduce((s, c) => s + c.deals, 0);
              return (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                  {/* Header */}
                  <div className="mono" style={{
                    display: 'grid', gridTemplateColumns: '1fr 80px 80px 100px 80px',
                    gap: 12, padding: '6px 0 10px',
                    fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)',
                    borderBottom: '.5px solid var(--line)',
                  }}>
                    <span>Team member</span>
                    <span style={{ textAlign: 'right' }}>Deals</span>
                    <span style={{ textAlign: 'right' }}>Production</span>
                    <span style={{ textAlign: 'right' }}>Revenue</span>
                    <span style={{ textAlign: 'right' }}>Share</span>
                  </div>
                  {teamSales.conversions.map((c, i) => {
                    const share = totalDeals === 0 ? 0 : Math.round((c.deals / totalDeals) * 100);
                    const barW = maxRevenue === 0 ? 0 : Math.round((c.revenue / maxRevenue) * 100);
                    const initials = c.actor.split(' ').map(x => x[0]).join('').slice(0, 2).toUpperCase();
                    return (
                      <div key={c.actor} style={{
                        display: 'grid', gridTemplateColumns: '1fr 80px 80px 100px 80px',
                        gap: 12, padding: '12px 0', alignItems: 'center',
                        borderBottom: i < teamSales.conversions.length - 1 ? '.5px solid var(--line)' : 'none',
                      }}>
                        {/* Name + bar */}
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                            <div style={{
                              width: 26, height: 26, borderRadius: '50%', flexShrink: 0,
                              background: `hsl(${(i * 67) % 360}, 30%, 40%)`,
                              display: 'flex', alignItems: 'center', justifyContent: 'center',
                              color: '#fff', fontSize: 10, fontWeight: 600,
                            }}>{initials}</div>
                            <span style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                              {c.actor}
                            </span>
                            {i === 0 && <span className="mono" style={{ fontSize: 9, padding: '2px 6px', borderRadius: 20, background: 'rgba(212,83,42,.1)', color: 'var(--accent)', flexShrink: 0 }}>TOP</span>}
                          </div>
                          <div style={{ height: 4, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
                            <div style={{ width: `${barW}%`, height: '100%', background: 'var(--ink)', transition: 'width .8s cubic-bezier(.2,.8,.2,1)', borderRadius: 999 }}/>
                          </div>
                        </div>
                        <span className="mono" style={{ fontSize: 13, textAlign: 'right', fontWeight: 500 }}>{c.deals}</span>
                        <span className="mono" style={{ fontSize: 12, textAlign: 'right', color: 'var(--muted)' }}>{c.in_production}</span>
                        <span className="mono" style={{ fontSize: 13, textAlign: 'right', fontWeight: 500 }}>
                          £{Number(c.revenue).toLocaleString('en-GB', { maximumFractionDigits: 0 })}
                        </span>
                        <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 4 }}>
                          <span className="mono" style={{
                            fontSize: 11, padding: '3px 8px', borderRadius: 20,
                            background: 'var(--bg-2)', color: 'var(--ink)',
                          }}>{share}%</span>
                        </div>
                      </div>
                    );
                  })}
                  {/* Totals row */}
                  <div style={{
                    display: 'grid', gridTemplateColumns: '1fr 80px 80px 100px 80px',
                    gap: 12, padding: '12px 0 0',
                    borderTop: '.5px solid var(--line-2)', marginTop: 4,
                  }}>
                    <span className="mono" style={{ fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--muted)', alignSelf: 'center' }}>Total converted</span>
                    <span className="mono" style={{ fontSize: 13, textAlign: 'right', fontWeight: 600 }}>{totalDeals}</span>
                    <span />
                    <span className="mono" style={{ fontSize: 13, textAlign: 'right', fontWeight: 600 }}>
                      £{teamSales.conversions.reduce((s, c) => s + Number(c.revenue), 0).toLocaleString('en-GB', { maximumFractionDigits: 0 })}
                    </span>
                    <span />
                  </div>
                </div>
              );
            })()}
          </div>
        </AdminCard>
      </div>

      {bySector.length > 0 && (
        <div style={{ marginTop: 20 }}>
          <AdminCard>
            <AdminCardHead title="Leads by sector" subtitle="Distribution" />
            <div className="grid-5-mobile-2" style={{ padding: '12px 20px 24px', display: 'grid', gridTemplateColumns: `repeat(${bySector.length},1fr)`, gap: 14 }}>
              {bySector.map(b => (
                <div key={b.sector.id} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                    <span style={{ fontSize: 12, fontWeight: 500 }}>{b.sector.label.split(' ')[0]}</span>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{b.count}</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2, height: 50 }}>
                    {[...Array(7)].map((_, i) => {
                      const h = Math.max(6, Math.random() * b.count * (50 / maxSectorCount) * 1.2);
                      return <div key={i} style={{ flex: 1, height: h, background: 'var(--ink)', opacity: 0.15 + (i/10), borderRadius: 2 }}/>;
                    })}
                  </div>
                </div>
              ))}
            </div>
          </AdminCard>
        </div>
      )}
    </div>
  );
}

function StatCard({ label, value, hint, trend, accent }) {
  return (
    <div style={{
      padding: 18,
      background: accent ? 'var(--ink)' : 'var(--paper)',
      color: accent ? 'var(--paper)' : 'var(--ink)',
      borderRadius: 14, border: accent ? 'none' : '.5px solid var(--line-2)',
      display: 'flex', flexDirection: 'column', gap: 6,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', opacity: 0.6 }}>
          {label}
        </span>
        <span className="mono" style={{ fontSize: 10, padding: '2px 6px', borderRadius: 20, background: accent ? 'rgba(255,255,255,.12)' : 'rgba(21,19,14,.06)', opacity: 0.8 }}>
          {trend}
        </span>
      </div>
      <div style={{
        fontFamily: 'var(--font-serif)', fontStyle: 'italic',
        fontSize: 38, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1,
      }}>
        {value}
      </div>
      <span style={{ fontSize: 11.5, opacity: 0.65 }}>{hint}</span>
    </div>
  );
}

// ──────────────────────────────────────────────
// Leads
// ──────────────────────────────────────────────

function LeadsList({ leads, sectors, onOpen }) {
  const [query, setQuery] = React.useState('');
  const [countryF, setCountryF] = React.useState('all');
  const [sectorF, setSectorF] = React.useState('all');
  const [statusF, setStatusF] = React.useState('all');
  const [sort, setSort] = React.useState('activity-desc');
  const isMobile = useMedia('(max-width: 900px)');

  const countries = ['all', ...Array.from(new Set(leads.map(l => l.country)))];
  const sectorOpts = ['all', ...(sectors || []).map(s => s.id)];

  const filtered = leads.filter(l => {
    if (query && !`${l.company} ${l.contact} ${l.id}`.toLowerCase().includes(query.toLowerCase())) return false;
    if (countryF !== 'all' && l.country !== countryF) return false;
    if (sectorF !== 'all' && l.sector_id !== sectorF) return false;
    if (statusF !== 'all' && l.status !== statusF) return false;
    return true;
  }).sort((a,b) => {
    if (sort === 'activity-desc') return ((b.last_activity_at || b.created_at) || '').localeCompare((a.last_activity_at || a.created_at) || '');
    if (sort === 'created-desc')  return (b.created_at || '').localeCompare(a.created_at || '');
    if (sort === 'created-asc')   return (a.created_at || '').localeCompare(b.created_at || '');
    if (sort === 'total-desc')    return (b.total || 0) - (a.total || 0);
    if (sort === 'total-asc')     return (a.total || 0) - (b.total || 0);
    return 0;
  });

  const exportCSV = () => {
    const header = ['id','company','contact','phone','country','sector','status','total','units','created_at'];
    const rows = filtered.map(l => header.map(h => JSON.stringify(l[h] ?? l[h.replace('sector','sector_id')] ?? '')).join(','));
    const csv = [header.join(','), ...rows].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `lupipak-leads-${Date.now()}.csv`; a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="pad-lg" style={{ padding: '36px 40px 56px' }}>
      <AdminHeader
        eyebrow="Back office · Leads"
        title="All leads"
        desc={`${filtered.length} of ${leads.length} leads · ${leads.filter(l => l.status === 'new').length} need attention`}
        actions={<Button variant="ghost" size="sm" onClick={exportCSV}>Export CSV</Button>}
      />

      <div className="wrap-mobile" style={{
        marginTop: 24, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap',
        padding: '12px 14px', background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 12,
      }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 200, maxWidth: 320 }}>
          <svg width="12" height="12" viewBox="0 0 16 16" fill="none" style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)' }}>
            <circle cx="7" cy="7" r="5" stroke="currentColor" strokeWidth="1.2"/><path d="M11 11 L14 14" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/>
          </svg>
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search company, contact, ref…"
            style={{ width: '100%', padding: '8px 8px 8px 32px', fontFamily: 'inherit', border: 0, background: 'transparent', outline: 'none' }}
          />
        </div>
        <FilterSelect label="Country" value={countryF} onChange={setCountryF} options={countries.map(c => ({value: c, label: c === 'all' ? 'All countries' : c }))} />
        <FilterSelect label="Sector"  value={sectorF}  onChange={setSectorF}  options={sectorOpts.map(s => ({ value: s, label: s === 'all' ? 'All sectors' : (sectors || []).find(x => x.id === s)?.label || s }))} />
        <FilterSelect label="Status"  value={statusF}  onChange={setStatusF}  options={[{value:'all',label:'All statuses'}, ...STATUS_ORDER.map(s => ({ value: s, label: STATUS_META[s].label }))]} />
        <FilterSelect label="Sort"    value={sort}     onChange={setSort}     options={[
          {value:'activity-desc', label:'Last updated'},
          {value:'created-desc',  label:'Newest first'},
          {value:'created-asc',   label:'Oldest first'},
          {value:'total-desc',    label:'Highest value'},
          {value:'total-asc',     label:'Lowest value'},
        ]}/>
      </div>

      <div style={{ marginTop: 14, background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 12, overflow: 'hidden' }}>
        {!isMobile && (
          <div className="mono" style={{
            display: 'grid',
            gridTemplateColumns: '130px 1fr 160px 110px 120px 100px 150px 30px',
            padding: '10px 18px', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase',
            color: 'var(--muted)', borderBottom: '.5px solid var(--line)', background: 'var(--bg-2)',
          }}>
            <span>Ref</span><span>Company</span><span>Contact</span><span>Sector</span><span style={{textAlign:'right'}}>Value</span><span style={{textAlign:'right'}}>Units</span><span>Last update</span><span/>
          </div>
        )}
        {filtered.map((l, i) => (
          <LeadRow key={l.id} lead={l} sectors={sectors} onOpen={() => onOpen(l)} last={i === filtered.length - 1} isMobile={isMobile} />
        ))}
        {filtered.length === 0 && (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>
            No leads match your filters.
          </div>
        )}
      </div>
    </div>
  );
}

function LeadRow({ lead, sectors, onOpen, last, isMobile }) {
  const createdDate = new Date(lead.created_at);
  const sectorLabel = (sectors || []).find(s => s.id === lead.sector_id)?.label.split(' ')[0] || lead.sector_id;

  // Last-activity display
  const lastAt = lead.last_activity_at || lead.created_at;
  const lastDate = new Date(lastAt);
  const lastFmt = lastDate.toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });
  const lastActor = lead.last_actor && lead.last_actor !== 'System' ? lead.last_actor : null;
  const lastEvent = lead.last_event || '';
  // Summarise event for the list view
  const lastEventShort = lastEvent.startsWith('Status changed to ')
    ? `→ ${lastEvent.replace('Status changed to ', '')}`
    : lastEvent.startsWith('Note: ')
    ? 'Note added'
    : lastEvent.length > 28 ? lastEvent.slice(0, 26) + '…' : lastEvent;

  if (isMobile) {
    return (
      <div onClick={onOpen} style={{
        display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, padding: '14px 16px',
        borderBottom: last ? 'none' : '.5px solid var(--line)', cursor: 'pointer',
      }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 13.5, fontWeight: 500 }}>{lead.company}</span>
            <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{lead.id}</span>
          </div>
          <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 3 }}>
            {lead.contact} · {lead.country} · {sectorLabel}
          </div>
          <div style={{ marginTop: 6, display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <StatusPill status={lead.status} />
            <span className="mono" style={{ fontSize: 11.5, fontWeight: 500 }}>£{(lead.total||0).toLocaleString('en-GB')}</span>
            {lastEventShort && <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{lastFmt} · {lastEventShort}</span>}
          </div>
        </div>
        <ArrowRight size={12}/>
      </div>
    );
  }

  return (
    <div onClick={onOpen} style={{
      display: 'grid',
      gridTemplateColumns: '130px 1fr 160px 110px 120px 100px 150px 30px',
      padding: '14px 18px', alignItems: 'center', gap: 10,
      borderBottom: last ? 'none' : '.5px solid var(--line)', cursor: 'pointer',
    }}>
      <span className="mono" style={{ fontSize: 11.5 }}>{lead.id}</span>
      <div>
        <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: '-0.01em' }}>{lead.company}</div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>
          {createdDate.toLocaleDateString('en-GB', { day: '2-digit', month: 'short' })} · {lead.country}
        </div>
      </div>
      <div>
        <div style={{ fontSize: 12.5 }}>{lead.contact}</div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>{lead.method}</div>
      </div>
      <span style={{ fontSize: 12.5 }}>{sectorLabel}</span>
      <span className="mono" style={{ textAlign: 'right', fontSize: 12.5, fontWeight: 500 }}>£{(lead.total||0).toLocaleString('en-GB')}</span>
      <span className="mono" style={{ textAlign: 'right', fontSize: 12, color: 'var(--muted)' }}>{((lead.units||0)/1000).toFixed(0)}k</span>
      <div>
        <StatusPill status={lead.status} />
        <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginTop: 4 }}>
          {lastFmt}{lastActor ? ` · ${lastActor}` : ''}{lastEventShort ? ` · ${lastEventShort}` : ''}
        </div>
      </div>
      <ArrowRight size={12}/>
    </div>
  );
}

function LeadDetail({ lead: initial, sectors, onBack, onUpdateStatus }) {
  const [lead, setLead] = React.useState(null);
  const [note, setNote] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  React.useEffect(() => {
    api.get(`/api/leads/${initial.id}`).then(setLead);
  }, [initial.id]);

  if (!lead) return <PageLoading />;
  const sector = (sectors || []).find(s => s.id === lead.sector_id);

  const changeStatus = async (newStatus) => {
    if (lead.status === newStatus) return;
    setLead(l => ({ ...l, status: newStatus })); // optimistic update
    try {
      await onUpdateStatus(lead.id, newStatus);
      const fresh = await api.get(`/api/leads/${lead.id}`);
      setLead(fresh);
    } catch (e) {
      // revert on failure
      const fresh = await api.get(`/api/leads/${lead.id}`);
      setLead(fresh);
    }
  };

  const saveNote = async () => {
    if (!note.trim()) return;
    setSaving(true);
    try {
      await api.post(`/api/leads/${lead.id}/notes`, { note });
      const fresh = await api.get(`/api/leads/${lead.id}`);
      setLead(fresh);
      setNote('');
    } catch (e) {
      alert('Could not save note: ' + (e.message || 'Unknown error'));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="pad-lg" style={{ padding: '36px 40px 56px' }}>
      <button onClick={onBack} style={{ background:'transparent', border:0, color:'var(--muted)', fontSize:12.5, display:'inline-flex', alignItems:'center', gap:6, marginBottom: 16, cursor: 'pointer' }}>
        <svg width="10" height="10" viewBox="0 0 16 16" fill="none"><path d="M13 8 L3 8 M7 4 L3 8 L7 12" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        All leads
      </button>

      <div className="stack-mobile" style={{ display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'flex-start', gap: 20, paddingBottom: 24, borderBottom: '.5px solid var(--line)' }}>
        <div>
          <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>
            Lead · {lead.id}
          </div>
          <h1 className="responsive-h1" style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 44, margin: 0, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1.05 }}>
            {lead.company}
          </h1>
          <div className="wrap-mobile" style={{ marginTop: 10, display: 'flex', gap: 14, fontSize: 13, color: 'var(--ink-2)', flexWrap: 'wrap' }}>
            <span>{lead.contact}</span>
            <span className="mono" style={{ fontSize: 12.5 }}>{lead.phone}</span>
            <span>{lead.country}</span>
            <span>{sector?.label}</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <Button variant="ghost" size="sm" onClick={() => window.open(`/api/leads/${lead.id}/proforma.pdf`, '_blank')}
            icon={<svg width="12" height="12" viewBox="0 0 16 16" fill="none"><path d="M8 2 V11 M5 8 L8 11 L11 8 M3 13 H13" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>}
          >PDF</Button>
          <Button variant="ghost" size="sm" onClick={() => window.open(`https://wa.me/${lead.phone.replace(/\D/g,'')}`, '_blank')}>WhatsApp</Button>
          <Button variant="ghost" size="sm" onClick={() => window.location.href = `tel:${lead.phone}`}>Call</Button>
        </div>
      </div>

      <div className="two-col-13" style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 20, marginTop: 24 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <AdminCard>
            <AdminCardHead title="Packaging plan" subtitle={`${lead.items?.length || 0} items · ${(lead.units||0).toLocaleString('en-GB')} units`} />
            <div>
              {(lead.items || []).map((it, i) => (
                <div key={it.product_id} className="wrap-mobile" style={{
                  display: 'grid', gridTemplateColumns: '48px 1fr 90px 110px 110px', gap: 12, alignItems: 'center',
                  padding: '14px 20px', borderTop: i === 0 ? 'none' : '.5px solid var(--line)',
                }}>
                  <div style={{ width: 48, height: 48, borderRadius: 8, background: 'var(--bg-2)', display:'flex', alignItems:'center', justifyContent:'center', overflow: 'hidden' }}>
                    <ProductImage product={it} size={48} />
                  </div>
                  <div>
                    <div style={{ fontSize: 13.5, fontWeight: 500 }}>{it.name}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>{it.size} · {it.dims}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 12 }}>£{Number(it.unit).toFixed(3)}</span>
                  <span className="mono" style={{ fontSize: 12, textAlign: 'right' }}>{Number(it.qty).toLocaleString('en-GB')}</span>
                  <span className="mono" style={{ fontSize: 13, fontWeight: 500, textAlign: 'right' }}>£{Math.round(Number(it.unit) * Number(it.qty)).toLocaleString('en-GB')}</span>
                </div>
              ))}
              {(lead.items || []).length === 0 && (
                <div style={{ padding: 24, textAlign: 'center', fontSize: 12, color: 'var(--muted)' }}>No line items recorded.</div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', padding: '16px 20px', borderTop: '1px solid var(--ink)', background: 'var(--bg-2)' }}>
                <span style={{ fontSize: 12.5, fontWeight: 500 }}>Estimate</span>
                <span style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 22, letterSpacing: '-0.015em' }}>
                  £{(lead.total||0).toLocaleString('en-GB')}
                </span>
              </div>
            </div>
          </AdminCard>

          <AdminCard>
            {(() => {
              const timeline = [...(lead.activity || [])].reverse(); // newest first
              const fmtTime = (ts) => new Date(ts).toLocaleString('en-GB', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' });
              const noteCount  = timeline.filter(a => a.event.startsWith('Note: ')).length;
              const totalCount = timeline.length;
              return (
                <>
                  <AdminCardHead
                    title="Timeline"
                    subtitle={`${totalCount} event${totalCount !== 1 ? 's' : ''}${noteCount ? ` · ${noteCount} note${noteCount !== 1 ? 's' : ''}` : ''}`}
                  />
                  <div style={{ padding: '4px 0 0' }}>
                    {timeline.length === 0 && (
                      <div style={{ padding: '16px 20px', fontSize: 12, color: 'var(--muted)' }}>No activity yet.</div>
                    )}
                    {timeline.map((a, i) => {
                      const isNote   = a.event.startsWith('Note: ');
                      const isStatus = a.event.startsWith('Status changed to ');
                      const status   = isStatus ? a.event.replace('Status changed to ', '') : null;
                      const isLast   = i === timeline.length - 1;
                      return (
                        <div key={i} style={{
                          display: 'flex', gap: 14, padding: '12px 20px',
                          borderBottom: isLast ? 'none' : '.5px solid var(--line)',
                          background: isNote ? 'var(--paper)' : 'transparent',
                        }}>
                          {/* Left: timestamp + actor */}
                          <div style={{ minWidth: 90, flexShrink: 0 }}>
                            <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>{fmtTime(a.created_at)}</div>
                            <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginTop: 2 }}>{a.actor}</div>
                          </div>
                          {/* Right: event content */}
                          <div style={{ flex: 1, minWidth: 0 }}>
                            {isNote ? (
                              <div>
                                <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 4 }}>Note</div>
                                <div style={{ fontSize: 13, lineHeight: 1.55, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
                                  {a.event.replace(/^Note: /, '')}
                                </div>
                              </div>
                            ) : isStatus ? (
                              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                                <span style={{ fontSize: 11, color: 'var(--muted)' }}>Status →</span>
                                <StatusPill status={status} />
                              </div>
                            ) : (
                              <span style={{ fontSize: 12.5, color: 'var(--ink-2)' }}>{a.event}</span>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                  {/* Add note */}
                  <div style={{ borderTop: '.5px solid var(--line)', padding: '14px 20px 18px' }}>
                    <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>Add note</div>
                    <textarea
                      placeholder="Discussed artwork turnaround, sent sample swatches…"
                      rows={3} value={note} onChange={(e) => setNote(e.target.value)}
                      style={{
                        width: '100%', padding: '10px 12px', fontFamily: 'inherit',
                        background: 'var(--bg-2)', border: '.5px solid var(--line)', borderRadius: 8,
                        outline: 'none', resize: 'vertical', fontSize: 13,
                      }}
                    />
                    <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 8 }}>
                      <Button variant="primary" size="sm" onClick={saveNote} disabled={saving || !note.trim()}>
                        {saving ? 'Saving…' : 'Add note'}
                      </Button>
                    </div>
                  </div>
                </>
              );
            })()}
          </AdminCard>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <AdminCard>
            <AdminCardHead title="Status" subtitle="Move through the pipeline" />
            <div style={{ padding: '4px 16px 16px', display: 'flex', flexDirection: 'column', gap: 4 }}>
              {STATUS_ORDER.map(s => {
                const active = lead.status === s;
                const meta = STATUS_META[s];
                return (
                  <button
                    key={s}
                    onClick={() => changeStatus(s)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '10px 12px', borderRadius: 8, border: 0,
                      background: active ? meta.bg : 'transparent',
                      color: 'var(--ink)', fontSize: 12.5, textAlign: 'left', cursor: 'pointer',
                    }}
                  >
                    <span style={{
                      width: 14, height: 14, borderRadius: '50%',
                      background: active ? meta.color : 'transparent',
                      border: active ? 'none' : '1px dashed var(--line-2)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
                    }}>
                      {active && <Check size={8}/>}
                    </span>
                    <span style={{ flex: 1, fontWeight: active ? 500 : 400 }}>{meta.label}</span>
                  </button>
                );
              })}
            </div>
          </AdminCard>

          <AdminCard>
            <AdminCardHead title="Details" />
            <div style={{ padding: '4px 20px 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <MetaLine label="Preferred contact" value={lead.method} />
              <MetaLine label="Source" value={lead.source} />
              <MetaLine label="Created" value={new Date(lead.created_at).toLocaleString('en-GB', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })} />
              {lead.notes && <MetaLine label="Submitted notes" value={lead.notes} />}
            </div>
          </AdminCard>

        </div>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────
// Products
// ──────────────────────────────────────────────

function ProductsAdmin({ sectors, user }) {
  const [products, setProducts] = React.useState([]);
  const [selectedId, setSelectedId] = React.useState(null);
  const [showNew, setShowNew] = React.useState(false);

  const refresh = React.useCallback((keepSelected) => {
    api.get('/api/products').then(list => {
      setProducts(list);
      setSelectedId(prev => {
        const p = keepSelected || prev;
        if (p && list.find(x => x.id === p)) return p;
        return list[0]?.id || null;
      });
    });
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  const product = products.find(p => p.id === selectedId);
  const canWrite = can(user, 'admin') || user?.access === 'admin';

  return (
    <div className="pad-lg" style={{ padding: '36px 40px 56px' }}>
      <AdminHeader
        eyebrow="Back office · Catalogue"
        title="Products"
        desc={`${products.length} products across ${sectors?.length || 0} sectors`}
        actions={canWrite && <Button variant="primary" size="sm" icon={<Plus size={11}/>} onClick={() => setShowNew(true)}>New product</Button>}
      />

      {showNew && <NewProductModal sectors={sectors} onClose={() => setShowNew(false)} onCreated={(id) => { setShowNew(false); refresh(id); }} />}

      <div className="two-col" style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 18, marginTop: 24 }}>
        <AdminCard>
          <AdminCardHead title="All products" subtitle="Click to edit" />
          <div style={{ padding: '4px 8px 12px', maxHeight: 560, overflowY: 'auto' }} className="scroll">
            {products.map(p => {
              const active = p.id === selectedId;
              return (
                <button
                  key={p.id}
                  onClick={() => setSelectedId(p.id)}
                  style={{
                    width: '100%', display: 'grid', gridTemplateColumns: '40px 1fr auto', gap: 10,
                    padding: '10px', borderRadius: 8, border: 0,
                    background: active ? 'var(--ink)' : 'transparent',
                    color: active ? 'var(--paper)' : 'var(--ink)',
                    textAlign: 'left', alignItems: 'center', cursor: 'pointer',
                  }}
                >
                  <span style={{ width: 36, height: 36, borderRadius: 6, background: active ? 'rgba(255,255,255,.12)' : 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
                    <ProductImage product={p} size={36}/>
                  </span>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0 }}>
                    <span style={{ fontSize: 12.5, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
                    <span className="mono" style={{ fontSize: 10, opacity: 0.65 }}>{p.variants.length} sizes · MOQ {(p.moq/1000)}k</span>
                    {p.sectors && p.sectors.length > 1 && (
                      <span className="mono" style={{ fontSize: 9.5, opacity: 0.55, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {p.sectors.length} sectors
                      </span>
                    )}
                  </div>
                  <span className="mono" style={{ fontSize: 10, opacity: 0.6 }}>
                    £{(p.pricing[1]?.unit || p.pricing[0]?.unit || 0).toFixed(2)}
                  </span>
                </button>
              );
            })}
          </div>
        </AdminCard>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {product && <ProductEditor key={product.id} product={product} sectors={sectors} products={products} onSaved={() => refresh(product.id)} canWrite={canWrite} />}
        </div>
      </div>
    </div>
  );
}

function SectorMultiSelect({ sectors, value, onChange, disabled }) {
  return (
    <div>
      <div className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>
        Sectors · appears in all selected
      </div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {(sectors || []).map(s => {
          const active = (value || []).includes(s.id);
          return (
            <button
              key={s.id}
              type="button"
              disabled={disabled || (active && value.length === 1)}
              onClick={() => {
                if (disabled) return;
                if (active) {
                  if (value.length === 1) return;
                  onChange(value.filter(id => id !== s.id));
                } else {
                  onChange([...value, s.id]);
                }
              }}
              style={{
                padding: '6px 13px', borderRadius: 20, border: '.5px solid var(--line-2)',
                background: active ? 'var(--ink)' : 'var(--bg-2)',
                color: active ? 'var(--paper)' : 'var(--ink)',
                fontSize: 12, fontWeight: active ? 500 : 400,
                cursor: (disabled || (active && value.length === 1)) ? 'default' : 'pointer',
                opacity: (disabled || (active && value.length === 1)) ? 0.6 : 1,
                transition: 'all .15s',
              }}
            >
              {active && <span style={{ marginRight: 5, opacity: 0.7 }}>✓</span>}
              {s.label}
            </button>
          );
        })}
      </div>
    </div>
  );
}

function NewProductModal({ sectors, onClose, onCreated }) {
  const [form, setForm] = React.useState({ name: '', kind: 'box', blurb: '', moq: 10000, sector_ids: [sectors?.[0]?.id || 'burger'] });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const kinds = ['box','paper','frybox','bucket','nuggetbox','bag','wipe','napkin','saucecup','liner'];

  const submit = async () => {
    setBusy(true); setErr(null);
    try {
      const { sector_ids, ...rest } = form;
      const r = await api.post('/api/products', { ...rest, sector_id: sector_ids[0] });
      if (sector_ids.length > 1) {
        await api.put(`/api/products/${r.id}/sectors`, { sector_ids });
      }
      onCreated?.(r.id);
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  return (
    <Modal title="Create a new product" onClose={onClose} footer={<>
      <Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
      <Button variant="primary" size="sm" onClick={submit} disabled={busy || !form.name}>
        {busy ? 'Creating…' : 'Create product'}
      </Button>
    </>}>
      <EditField label="Name"        value={form.name}      onChange={(v) => setForm({...form, name: v})} />
      <EditField label="Visual kind" value={form.kind}      onChange={(v) => setForm({...form, kind: v})} select options={kinds.map(k => ({value: k, label: k}))} />
      <EditField label="MOQ"         value={String(form.moq)} onChange={(v) => setForm({...form, moq: Number(v)})} type="number" />
      <EditField label="Description" value={form.blurb}     onChange={(v) => setForm({...form, blurb: v})} textarea />
      <SectorMultiSelect sectors={sectors} value={form.sector_ids} onChange={(v) => setForm({...form, sector_ids: v})} />
      {err && <div style={{ fontSize: 12, color: 'var(--accent)' }}>{err}</div>}
    </Modal>
  );
}

function ProductEditor({ product, sectors, products, onSaved, canWrite }) {
  const [name, setName] = React.useState(product.name);
  const [blurb, setBlurb] = React.useState(product.blurb || '');
  const [moq, setMoq] = React.useState(product.moq);
  const [sectorIds, setSectorIds] = React.useState(product.sectors?.length ? product.sectors : [product.sector_id]);
  const [tiers, setTiers] = React.useState(product.pricing);
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState(false);

  const [newVariant, setNewVariant] = React.useState(null);
  const [newPairing, setNewPairing] = React.useState(false);

  const save = async () => {
    setSaving(true);
    await api.put(`/api/products/${product.id}`, { name, blurb, moq: Number(moq), sector_id: sectorIds[0] });
    await api.put(`/api/products/${product.id}/sectors`, { sector_ids: sectorIds });
    await api.put(`/api/products/${product.id}/pricing`, { tiers: tiers.map(t => ({ qty: Number(t.qty), unit: Number(t.unit) })) });
    setSaving(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 1800);
    onSaved?.();
  };

  const updateTier = (i, key, val) => setTiers(ts => ts.map((t, idx) => idx === i ? { ...t, [key]: val } : t));
  const addTier = () => setTiers(ts => [...ts, { qty: (ts[ts.length - 1]?.qty || 10000) * 2, unit: (ts[ts.length - 1]?.unit || 0.3) * 0.8 }]);
  const removeTier = (i) => setTiers(ts => ts.filter((_, idx) => idx !== i));

  const deleteVariant = async (vid) => {
    if (!confirm(`Delete variant "${vid}"?`)) return;
    await api.del(`/api/products/${product.id}/variants/${vid}`);
    onSaved?.();
  };
  const toggleRecommended = async (v) => {
    await api.put(`/api/products/${product.id}/variants/${v.id}`, { recommended: !v.recommended });
    onSaved?.();
  };
  const removePair = async (pid) => {
    await api.del(`/api/products/${product.id}/pairs/${pid}`);
    onSaved?.();
  };

  const deleteProduct = async () => {
    if (!confirm(`Delete "${product.name}"? This cannot be undone.`)) return;
    await api.del(`/api/products/${product.id}`);
    onSaved?.();
  };

  return (
    <>
      <AdminCard>
        <AdminCardHead title="Product images" subtitle="Hero shot + gallery. Drag to upload; star to set hero." />
        <ProductImageUploader product={product} />
      </AdminCard>

      <AdminCard>
        <AdminCardHead title={`Edit · ${product.name}`} subtitle={product.blurb || 'No description'} />
        <div style={{ padding: '8px 20px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <EditField label="Display name" value={name} onChange={setName} disabled={!canWrite} />
          <EditField label="MOQ"          value={String(moq)} onChange={setMoq} type="number" disabled={!canWrite} />
          <EditField label="Product kind" value={product.kind} disabled />
          <div style={{ gridColumn: '1 / -1' }}>
            <EditField label="Description" value={blurb} onChange={setBlurb} textarea disabled={!canWrite} />
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <SectorMultiSelect sectors={sectors} value={sectorIds} onChange={setSectorIds} disabled={!canWrite} />
          </div>
        </div>
      </AdminCard>

      <AdminCard>
        <AdminCardHead title="Sizes (variants)" subtitle={`${product.variants.length} variants`}
          actions={canWrite && <Button variant="ghost" size="sm" icon={<Plus size={11}/>} onClick={() => setNewVariant({ size: '', dims: '', recommended: false })}>Add size</Button>}
        />
        <div className="scroll-x-mobile">
          <div className="mono" style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr 1fr 90px 90px', gap: 10, padding: '10px 20px', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', background: 'var(--bg-2)', borderBottom: '.5px solid var(--line)', minWidth: 560 }}>
            <span>Label</span><span>Dimensions</span><span>SKU</span><span style={{textAlign:'right'}}>Default</span><span/>
          </div>
          {product.variants.map((v, i) => (
            <div key={v.id} style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr 1fr 90px 90px', gap: 10, padding: '12px 20px', alignItems: 'center', fontSize: 13, borderBottom: i === product.variants.length - 1 ? 'none' : '.5px solid var(--line)', minWidth: 560 }}>
              <span>{v.size}</span>
              <span className="mono" style={{ fontSize: 12 }}>{v.dims}</span>
              <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{product.id.toUpperCase().replace(/-/g,'')}-{v.id.toUpperCase()}</span>
              <button onClick={() => canWrite && toggleRecommended(v)}
                style={{
                  justifySelf: 'end', border: 0, cursor: canWrite ? 'pointer' : 'default',
                  padding: '3px 9px', borderRadius: 20, fontSize: 11,
                  background: v.recommended ? 'rgba(212,83,42,.1)' : 'rgba(21,19,14,.05)',
                  color: v.recommended ? 'var(--accent)' : 'var(--muted)',
                }}
                title="Toggle default">
                {v.recommended ? '★ default' : '☆ set default'}
              </button>
              <button onClick={() => deleteVariant(v.id)} disabled={!canWrite}
                style={{ justifySelf: 'end', background: 'transparent', border: '.5px solid var(--line-2)', borderRadius: 6, padding: '4px 8px', fontSize: 11, color: 'var(--muted)', cursor: canWrite ? 'pointer' : 'default' }}>
                Delete
              </button>
            </div>
          ))}
        </div>
      </AdminCard>

      <AdminCard>
        <AdminCardHead title="Pricing tiers" subtitle="Price per unit by quantity"
          actions={canWrite && <Button variant="ghost" size="sm" icon={<Plus size={11}/>} onClick={addTier}>Add tier</Button>}
        />
        <div className="grid-4-mobile-2" style={{ padding: '16px 20px 20px', display: 'grid', gridTemplateColumns: `repeat(${Math.max(tiers.length, 1)}, 1fr)`, gap: 10 }}>
          {tiers.map((t, i) => (
            <div key={i} style={{ position: 'relative', padding: 12, background: 'var(--bg-2)', borderRadius: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {canWrite && (
                <button onClick={() => removeTier(i)}
                  style={{ position: 'absolute', top: 4, right: 4, width: 20, height: 20, borderRadius: 6, border: 0, background: 'transparent', color: 'var(--muted)', cursor: 'pointer' }}>
                  <svg width="10" height="10" viewBox="0 0 16 16"><path d="M4 4 L12 12 M12 4 L4 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
                </button>
              )}
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>From qty</span>
              <input type="number" disabled={!canWrite} value={t.qty} onChange={(e) => updateTier(i, 'qty', Number(e.target.value))}
                style={{ padding: '6px 8px', background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 6, fontFamily: 'inherit', outline: 'none' }}
              />
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>Unit £</span>
              <input type="number" step="0.001" disabled={!canWrite} value={t.unit} onChange={(e) => updateTier(i, 'unit', Number(e.target.value))}
                style={{ padding: '6px 8px', background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 6, fontFamily: 'inherit', outline: 'none' }}
              />
            </div>
          ))}
        </div>
      </AdminCard>

      <AdminCard>
        <AdminCardHead title="Recommended pairings" subtitle="Suggested when this item is added to the set"
          actions={canWrite && <Button variant="ghost" size="sm" icon={<Plus size={11}/>} onClick={() => setNewPairing(true)}>Add pairing</Button>}
        />
        <div style={{ padding: '14px 20px 20px', display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {product.pairs.length === 0 && <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>No pairings yet.</span>}
          {product.pairs.map(pid => {
            const p = products.find(x => x.id === pid);
            if (!p) return null;
            return (
              <div key={pid} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '6px 10px 6px 6px', borderRadius: 20, background: 'var(--bg-2)', border: '.5px solid var(--line-2)', fontSize: 12 }}>
                <span style={{ width: 22, height: 22, borderRadius: 5, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <ProductImage product={p} size={22}/>
                </span>
                <span>{p.name}</span>
                {canWrite && (
                  <button onClick={() => removePair(pid)} style={{ background: 'transparent', border: 0, color: 'var(--muted)', padding: 0, marginLeft: 4, cursor: 'pointer' }}>
                    <svg width="10" height="10" viewBox="0 0 16 16"><path d="M4 4 L12 12 M12 4 L4 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
                  </button>
                )}
              </div>
            );
          })}
        </div>
      </AdminCard>

      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
        {canWrite ? (
          <Button variant="ghost" size="sm" onClick={deleteProduct}>Delete product</Button>
        ) : <span/>}
        <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          {saved && <span className="mono fade-in" style={{ fontSize: 11, color: '#4A5D3A', letterSpacing: '0.06em', textTransform: 'uppercase' }}>Saved ✓</span>}
          {canWrite && (
            <Button variant="primary" size="sm" onClick={save} disabled={saving}>
              {saving ? 'Saving…' : 'Save changes'}
            </Button>
          )}
        </div>
      </div>

      {newVariant && (
        <Modal title="Add size / variant" onClose={() => setNewVariant(null)} footer={<>
          <Button variant="ghost" size="sm" onClick={() => setNewVariant(null)}>Cancel</Button>
          <Button variant="primary" size="sm" disabled={!newVariant.size}
            onClick={async () => { await api.post(`/api/products/${product.id}/variants`, newVariant); setNewVariant(null); onSaved?.(); }}>
            Add size
          </Button>
        </>}>
          <EditField label="Size label" value={newVariant.size} onChange={(v) => setNewVariant(x => ({...x, size: v}))} />
          <EditField label="Dimensions" value={newVariant.dims} onChange={(v) => setNewVariant(x => ({...x, dims: v}))} />
          <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
            <input type="checkbox" checked={newVariant.recommended} onChange={(e) => setNewVariant(x => ({...x, recommended: e.target.checked}))}/>
            <span>Make this the default size</span>
          </label>
        </Modal>
      )}

      {newPairing && (
        <AddPairingModal
          product={product} products={products}
          onClose={() => setNewPairing(false)}
          onSaved={() => { setNewPairing(false); onSaved?.(); }}
        />
      )}
    </>
  );
}

function AddPairingModal({ product, products, onClose, onSaved }) {
  const available = products.filter(p => p.id !== product.id && !product.pairs.includes(p.id));
  const [pick, setPick] = React.useState(available[0]?.id || '');
  return (
    <Modal title="Add pairing" onClose={onClose} footer={<>
      <Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
      <Button variant="primary" size="sm" disabled={!pick}
        onClick={async () => { await api.post(`/api/products/${product.id}/pairs`, { pair_id: pick }); onSaved?.(); }}>
        Add pairing
      </Button>
    </>}>
      {available.length === 0 ? (
        <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>All other products are already paired.</span>
      ) : (
        <EditField label="Pair with" value={pick} onChange={setPick} select options={available.map(p => ({ value: p.id, label: p.name }))}/>
      )}
    </Modal>
  );
}

// ──────────────────────────────────────────────
// Product image uploader — wired to /api/products/:id/images
// ──────────────────────────────────────────────

function ProductImageUploader({ product }) {
  const [images, setImages] = React.useState([]);
  const [dragOver, setDragOver] = React.useState(false);
  const [pending, setPending] = React.useState([]); // local {id, preview, progress, name, size}
  const inputRef = React.useRef(null);

  const refresh = React.useCallback(() => {
    api.get(`/api/products/${product.id}/images`).then(setImages);
  }, [product.id]);

  React.useEffect(() => { refresh(); }, [refresh]);

  const readFileAsDataUrl = (file) => new Promise((resolve, reject) => {
    const r = new FileReader();
    r.onerror = () => reject(r.error);
    r.onload = () => resolve(r.result);
    r.readAsDataURL(file);
  });

  const uploadFile = async (file) => {
    if (!file.type.startsWith('image/')) return;
    const localId = Math.random().toString(36).slice(2, 9);
    const preview = URL.createObjectURL(file);
    setPending(p => [...p, { id: localId, preview, progress: 10, name: file.name, size: file.size }]);
    try {
      const data = await readFileAsDataUrl(file);
      setPending(p => p.map(x => x.id === localId ? { ...x, progress: 60 } : x));
      await api.post(`/api/products/${product.id}/images`, { filename: file.name, data });
      setPending(p => p.filter(x => x.id !== localId));
      URL.revokeObjectURL(preview);
      refresh();
    } catch (e) {
      setPending(p => p.map(x => x.id === localId ? { ...x, progress: 0, error: e.message } : x));
    }
  };

  const processFiles = (files) => { Array.from(files).forEach(uploadFile); };

  const setHero = async (imgId) => {
    await api.put(`/api/products/${product.id}/images/${imgId}/hero`, {});
    refresh();
  };
  const removeImage = async (imgId) => {
    await api.del(`/api/products/${product.id}/images/${imgId}`);
    refresh();
  };

  const formatSize = (b) => b < 1024 * 1024 ? `${(b/1024).toFixed(0)} KB` : `${(b/1024/1024).toFixed(1)} MB`;

  return (
    <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div
        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={(e) => { e.preventDefault(); setDragOver(false); processFiles(e.dataTransfer.files); }}
        onClick={() => inputRef.current?.click()}
        style={{
          display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 16, alignItems: 'center',
          padding: '18px 20px',
          background: dragOver ? 'rgba(212,83,42,.06)' : 'var(--bg-2)',
          border: dragOver ? '1px dashed var(--accent)' : '1px dashed var(--line-2)',
          borderRadius: 12, cursor: 'pointer',
        }}
      >
        <div style={{ width: 56, height: 56, borderRadius: 10, background: 'var(--paper)', border: '.5px solid var(--line-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <rect x="3" y="5" width="18" height="14" rx="2" stroke="currentColor" strokeWidth="1.2"/>
            <circle cx="9" cy="10" r="1.5" fill="currentColor"/>
            <path d="M3 17 L9 12 L14 15 L17 13 L21 17" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
          <span style={{ fontSize: 13.5, fontWeight: 500 }}>
            {dragOver ? 'Drop to upload' : `Drag & drop images of ${product.name}`}
          </span>
          <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>
            PNG, JPG, WebP, AVIF · up to 10 MB each · or click to browse
          </span>
        </div>
        <Button variant="primary" size="sm" icon={<Plus size={11}/>} onClick={(e) => { e.stopPropagation(); inputRef.current?.click(); }}>
          Upload
        </Button>
        <input
          ref={inputRef} type="file" accept="image/*" multiple
          onChange={(e) => processFiles(e.target.files)}
          style={{ position: 'absolute', left: -9999, top: -9999, opacity: 0 }}
        />
      </div>

      {(images.length > 0 || pending.length > 0) && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
          {pending.map((img) => (
            <div key={img.id} style={{
              position: 'relative', aspectRatio: '1 / 1',
              background: 'var(--bg-2)', borderRadius: 10, overflow: 'hidden',
              border: '.5px solid var(--line-2)',
            }}>
              <img src={img.preview} alt={img.name} style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: 0.6 }}/>
              <div style={{
                position: 'absolute', inset: 0, background: 'rgba(21,19,14,.35)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'rgba(255,255,255,.9)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {img.error
                    ? <span className="mono" style={{ fontSize: 9, color: 'var(--accent)' }}>ERR</span>
                    : <span className="mono" style={{ fontSize: 10, fontWeight: 500 }}>{Math.round(img.progress)}%</span>}
                </div>
              </div>
            </div>
          ))}
          {images.map((img) => (
            <div key={img.id} style={{
              position: 'relative', aspectRatio: '1 / 1',
              background: 'var(--bg-2)', borderRadius: 10, overflow: 'hidden',
              border: img.is_hero ? `1.5px solid var(--accent)` : '.5px solid var(--line-2)',
            }}>
              <img src={img.url} alt={img.filename} style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>

              {img.is_hero && (
                <div style={{
                  position: 'absolute', top: 6, left: 6,
                  padding: '3px 7px', borderRadius: 20,
                  background: 'var(--accent)', color: '#fff',
                  fontSize: 9.5, fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase', fontFamily: 'var(--font-mono)',
                }}>Hero</div>
              )}

              <div style={{ position: 'absolute', top: 6, right: 6, display: 'flex', gap: 4 }}>
                {!img.is_hero && (
                  <button onClick={() => setHero(img.id)} title="Set as hero"
                    style={{ width: 22, height: 22, borderRadius: 6, border: 0, background: 'rgba(250,248,243,.9)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                    <svg width="11" height="11" viewBox="0 0 16 16"><path d="M8 2 L10 6 L14 6.5 L11 9.5 L12 14 L8 11.5 L4 14 L5 9.5 L2 6.5 L6 6 Z" stroke="currentColor" strokeWidth="1.1" fill="none" strokeLinejoin="round"/></svg>
                  </button>
                )}
                <button onClick={() => removeImage(img.id)} title="Remove"
                  style={{ width: 22, height: 22, borderRadius: 6, border: 0, background: 'rgba(21,19,14,.75)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
                  <svg width="10" height="10" viewBox="0 0 16 16"><path d="M4 4 L12 12 M12 4 L4 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
                </button>
              </div>

              <div style={{
                position: 'absolute', bottom: 0, left: 0, right: 0,
                padding: '14px 8px 6px',
                background: 'linear-gradient(to top, rgba(21,19,14,.75), transparent)',
                color: '#fff',
              }}>
                <div style={{ fontSize: 10.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{img.filename}</div>
                <div className="mono" style={{ fontSize: 9, opacity: 0.7 }}>{formatSize(img.size)}</div>
              </div>
            </div>
          ))}
        </div>
      )}

      {images.length === 0 && pending.length === 0 && (
        <div style={{
          display: 'grid', gridTemplateColumns: '88px 1fr', gap: 16, alignItems: 'center',
          padding: '14px 16px', background: 'var(--paper)', border: '.5px solid var(--line)', borderRadius: 10,
        }}>
          <div style={{ width: 88, height: 88, background: 'var(--bg-2)', borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <ProductThumb kind={product.kind} size={72}/>
          </div>
          <div>
            <div style={{ fontSize: 12.5, fontWeight: 500, marginBottom: 4 }}>Currently using auto-generated illustration</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)', lineHeight: 1.5 }}>
              Upload real product photography to replace the placeholder across the catalogue, scene, and proforma.
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────
// Modal dialog primitive
// ──────────────────────────────────────────────

function Modal({ title, onClose, children, footer }) {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(21,19,14,.35)', backdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16,
      animation: 'fadeIn .15s ease both',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 440,
        background: 'var(--paper)', border: '.5px solid var(--line-2)',
        borderRadius: 16, boxShadow: 'var(--shadow-lg)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
        animation: 'scaleIn .18s cubic-bezier(.2,.8,.2,1) both',
      }}>
        <div style={{ padding: '16px 20px', borderBottom: '.5px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ margin: 0, fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em' }}>{title}</h3>
          <button onClick={onClose} style={{
            width: 28, height: 28, borderRadius: 8, border: '.5px solid var(--line-2)',
            background: 'transparent', color: 'var(--ink)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="11" height="11" viewBox="0 0 16 16"><path d="M4 4 L12 12 M12 4 L4 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
          </button>
        </div>
        <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {children}
        </div>
        {footer && <div style={{ padding: '14px 20px', borderTop: '.5px solid var(--line)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          {footer}
        </div>}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────
// Sectors
// ──────────────────────────────────────────────

function SectorsAdmin({ sectors: initial, user }) {
  const [sectors, setSectors] = React.useState(initial || []);
  const [showNew, setShowNew] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  React.useEffect(() => setSectors(initial || []), [initial]);

  const canWrite = user?.access === 'admin';

  const refresh = () => api.get('/api/sectors').then(setSectors);

  const createSector = async (payload) => {
    await api.post('/api/sectors', payload);
    setShowNew(false);
    refresh();
  };

  const deleteSector = async (id) => {
    if (!confirm(`Delete sector "${id}"? Products will also be removed.`)) return;
    await api.del(`/api/sectors/${id}`);
    refresh();
  };

  return (
    <div className="pad-lg" style={{ padding: '36px 40px 56px' }}>
      <AdminHeader
        eyebrow="Back office · Catalogue"
        title="Sectors"
        desc={`${sectors?.length || 0} active · Shown on the homepage picker`}
        actions={canWrite && <Button variant="primary" size="sm" icon={<Plus size={11}/>} onClick={() => setShowNew(true)}>New sector</Button>}
      />
      <div className="two-col" style={{ marginTop: 24, display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
        {(sectors || []).map((s, i) => (
          <AdminCard key={s.id}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, padding: 20, alignItems: 'center' }}>
              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>
                  Sector · 0{i+1}
                </div>
                <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 26, letterSpacing: '-0.015em', marginTop: 4 }}>
                  {s.label}
                </div>
                <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2 }}>{s.sub}</div>
                <div className="mono" style={{ fontSize: 11, marginTop: 10, color: 'var(--muted)' }}>
                  {s.kcal} products
                </div>
              </div>
              {canWrite && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <Button variant="ghost" size="sm" onClick={() => setEditing(s)}>Edit</Button>
                  <Button variant="ghost" size="sm" onClick={() => deleteSector(s.id)}>Delete</Button>
                </div>
              )}
            </div>
          </AdminCard>
        ))}
      </div>

      {showNew && <SectorModal onClose={() => setShowNew(false)} onSubmit={createSector} title="Create a new sector" />}
      {editing && <SectorModal onClose={() => setEditing(null)} title={`Edit · ${editing.label}`}
        initial={editing}
        onSubmit={async (p) => { await api.put(`/api/sectors/${editing.id}`, p); setEditing(null); refresh(); }}
      />}
    </div>
  );
}

function SectorModal({ onClose, onSubmit, title, initial }) {
  const [form, setForm] = React.useState({ id: initial?.id || '', label: initial?.label || '', sub: initial?.sub || '' });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const isEdit = !!initial;

  const submit = async () => {
    setBusy(true); setErr(null);
    try { await onSubmit(isEdit ? { label: form.label, sub: form.sub } : form); }
    catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  return (
    <Modal title={title} onClose={onClose} footer={<>
      <Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
      <Button variant="primary" size="sm" onClick={submit} disabled={busy || !form.label || (!isEdit && !form.id)}>
        {busy ? 'Saving…' : isEdit ? 'Save' : 'Create sector'}
      </Button>
    </>}>
      {!isEdit && <EditField label="ID (slug)" value={form.id} onChange={(v) => setForm({...form, id: v.toLowerCase().replace(/[^a-z0-9]+/g, '-')})} />}
      <EditField label="Label"       value={form.label} onChange={(v) => setForm({...form, label: v})} />
      <EditField label="Description" value={form.sub}   onChange={(v) => setForm({...form, sub: v})} />
      {err && <div style={{ fontSize: 12, color: 'var(--accent)' }}>{err}</div>}
    </Modal>
  );
}

// ──────────────────────────────────────────────
// Settings — THE admin-customisable core (contact + address)
// ──────────────────────────────────────────────

// ──────────────────────────────────────────────
// Team & Access — dedicated section (admin only)
// ──────────────────────────────────────────────

const ROLE_DEFS = {
  admin: {
    label: 'Administrator',
    tint: 'var(--accent)',
    bg: 'rgba(212,83,42,.10)',
    summary: 'Full control — can change anything.',
    capabilities: [
      'Edit company profile, contact info, address',
      'Create, edit, delete sectors & products',
      'Upload product images, manage pricing tiers',
      'Invite team members & change access levels',
      'View audit log & integrations',
      'All leads — view, status change, add notes',
    ],
  },
  sales: {
    label: 'Sales',
    tint: '#4A5D3A',
    bg: 'rgba(74,93,58,.10)',
    summary: 'Front-line — runs the customer pipeline.',
    capabilities: [
      'View all leads with full details',
      'Change lead status through the pipeline',
      'Add internal notes on leads',
      'View products, sectors & company settings',
      '✗ Cannot edit products, pricing, or team',
    ],
  },
  viewer: {
    label: 'Viewer',
    tint: '#8B857A',
    bg: 'rgba(21,19,14,.06)',
    summary: 'Read-only — observer access for stakeholders.',
    capabilities: [
      'View dashboard, leads & catalogue',
      'View settings for reference',
      '✗ Cannot make any changes',
    ],
  },
};

// Permission matrix rows — mirrors the server's ROLE_ALLOW table.
const CAPABILITY_MATRIX = [
  { label: 'View dashboard & leads',   admin: true,  sales: true,  viewer: true  },
  { label: 'View products & catalogue', admin: true,  sales: true,  viewer: true  },
  { label: 'View company settings',     admin: true,  sales: false, viewer: false },
  { label: 'Change lead status',        admin: true,  sales: true,  viewer: false },
  { label: 'Add notes to leads',        admin: true,  sales: true,  viewer: false },
  { label: 'Create / edit products',    admin: true,  sales: false, viewer: false },
  { label: 'Upload product images',     admin: true,  sales: false, viewer: false },
  { label: 'Manage pricing tiers',      admin: true,  sales: false, viewer: false },
  { label: 'Create / edit sectors',     admin: true,  sales: false, viewer: false },
  { label: 'Edit settings / address',   admin: true,  sales: false, viewer: false },
  { label: 'Invite & manage team',      admin: true,  sales: false, viewer: false },
  { label: 'View audit log',            admin: true,  sales: false, viewer: false },
];

function AuditEventDot({ action }) {
  const color =
    action?.startsWith('auth.')     ? '#8B5E3C' :
    action?.startsWith('team.')     ? 'var(--accent)' :
    action?.startsWith('settings.') ? '#6B5842' :
    action?.startsWith('product.')  ? '#4A5D3A' :
    action?.startsWith('sector.')   ? '#4A5D3A' :
    action?.startsWith('lead.')     ? '#075E54' :
    'var(--muted)';
  return <span style={{ width: 6, height: 6, borderRadius: '50%', background: color, flexShrink: 0 }}/>;
}

function TeamAdmin({ currentUser }) {
  const [members, setMembers] = React.useState([]);
  const [audit, setAudit] = React.useState([]);
  const [editing, setEditing] = React.useState(null);
  const [filter, setFilter] = React.useState('all');

  const refresh = () => {
    api.get('/api/team').then(setMembers);
    api.get('/api/audit?limit=40').then(setAudit).catch(() => setAudit([]));
  };
  React.useEffect(() => { refresh(); }, []);

  const byRole = (r) => members.filter(m => m.access === r);
  const active = members.filter(m => m.active).length;

  const visibleMembers = filter === 'all' ? members : members.filter(m => m.access === filter);

  return (
    <div className="pad-lg" style={{ padding: '36px 40px 56px' }}>
      <AdminHeader
        eyebrow="Back office · Access"
        title="Team & Access"
        desc={`${active} active members · ${byRole('admin').length} admin · ${byRole('sales').length} sales · ${byRole('viewer').length} viewer`}
        actions={<Button variant="primary" size="sm" icon={<Plus size={11}/>}
          onClick={() => setEditing({ name: '', role: '', email: '', username: '', password: '', access: 'viewer', active: true })}
        >Invite member</Button>}
      />

      {/* Role overview cards */}
      <div className="grid-4-mobile-2" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginTop: 28 }}>
        {Object.entries(ROLE_DEFS).map(([key, def]) => (
          <div key={key}
            style={{
              padding: 18,
              background: 'var(--paper)',
              border: `.5px solid ${key === 'admin' ? 'rgba(212,83,42,.4)' : 'var(--line-2)'}`,
              borderRadius: 14,
              display: 'flex', flexDirection: 'column', gap: 10,
            }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', padding: '3px 8px', borderRadius: 20, background: def.bg, color: def.tint }}>
                {def.label}
              </span>
              <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>{byRole(key).length} members</span>
            </div>
            <div style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 22, letterSpacing: '-0.015em', lineHeight: 1.15 }}>
              {def.summary}
            </div>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 4 }}>
              {def.capabilities.map((c, i) => (
                <li key={i} style={{ fontSize: 12, color: 'var(--ink-2)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                  <span style={{ color: c.startsWith('✗') ? 'var(--muted)' : def.tint, flexShrink: 0 }}>{c.startsWith('✗') ? '' : '·'}</span>
                  <span style={{ color: c.startsWith('✗') ? 'var(--muted)' : 'inherit' }}>{c.replace(/^✗ /, '')}</span>
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>

      {/* Members list with role filter */}
      <AdminCard style={{ marginTop: 20 }}>
        <AdminCardHead
          title="Members"
          subtitle={`${visibleMembers.length} shown · click a row to edit`}
          actions={
            <div style={{ display: 'flex', gap: 4, background: 'rgba(21,19,14,.04)', padding: 3, borderRadius: 8 }}>
              {['all', 'admin', 'sales', 'viewer'].map(k => (
                <button
                  key={k}
                  onClick={() => setFilter(k)}
                  style={{
                    padding: '5px 10px', fontSize: 11, borderRadius: 6, border: 0,
                    background: filter === k ? 'var(--paper)' : 'transparent',
                    color: filter === k ? 'var(--ink)' : 'var(--muted)',
                    boxShadow: filter === k ? '0 1px 2px rgba(21,19,14,.08)' : 'none',
                    textTransform: 'capitalize', cursor: 'pointer',
                  }}
                >{k}</button>
              ))}
            </div>
          }
        />
        <div>
          {visibleMembers.map((m, i) => (
            <div key={m.id}
              onClick={() => setEditing(m)}
              style={{
                display: 'grid', gridTemplateColumns: '36px 1fr 140px 130px 24px',
                gap: 14, padding: '14px 20px', alignItems: 'center', cursor: 'pointer',
                borderTop: i === 0 ? 'none' : '.5px solid var(--line)',
              }}>
              <div style={{
                width: 36, height: 36, borderRadius: '50%',
                background: 'linear-gradient(135deg,#3A362C,#8B857A)', color: '#fff',
                fontSize: 12, fontWeight: 500, display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{m.name.split(' ').map(x => x[0]).join('').slice(0,2)}</div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500, display: 'inline-flex', gap: 10, alignItems: 'center' }}>
                  {m.name}
                  {currentUser?.uid === m.id && <span className="mono" style={{ fontSize: 9, padding: '1px 6px', borderRadius: 20, background: 'var(--bg-2)', color: 'var(--muted)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>YOU</span>}
                </div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>
                  {m.role}{m.email ? ` · ${m.email}` : ''}{m.username ? ` · @${m.username}` : ''}
                </div>
              </div>
              <span className="mono" style={{
                fontSize: 11, padding: '4px 10px', borderRadius: 20,
                background: ROLE_DEFS[m.access]?.bg, color: ROLE_DEFS[m.access]?.tint,
                fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.06em',
                justifySelf: 'start',
              }}>
                {ROLE_DEFS[m.access]?.label || m.access}
              </span>
              <span className="mono" style={{ fontSize: 11, color: m.active ? '#4A5D3A' : 'var(--muted)' }}>
                <span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', marginRight: 6, background: m.active ? '#4A5D3A' : 'var(--muted)' }}/>
                {m.active ? 'Active' : 'Inactive'}
              </span>
              <ArrowRight size={12}/>
            </div>
          ))}
          {visibleMembers.length === 0 && (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>
              No members match this filter.
            </div>
          )}
        </div>
      </AdminCard>

      {/* Permission matrix + audit feed */}
      <div className="two-col" style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 18, marginTop: 20 }}>
        <AdminCard>
          <AdminCardHead title="Permission matrix" subtitle="What each role can do at a glance" />
          <div className="scroll-x-mobile">
            <div className="mono" style={{
              display: 'grid', gridTemplateColumns: '1fr 60px 60px 60px', gap: 10,
              padding: '10px 20px', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)',
              background: 'var(--bg-2)', borderBottom: '.5px solid var(--line)', minWidth: 460,
            }}>
              <span>Capability</span>
              <span style={{ textAlign: 'center' }}>Admin</span>
              <span style={{ textAlign: 'center' }}>Sales</span>
              <span style={{ textAlign: 'center' }}>Viewer</span>
            </div>
            {CAPABILITY_MATRIX.map((row, i) => (
              <div key={i} style={{
                display: 'grid', gridTemplateColumns: '1fr 60px 60px 60px', gap: 10,
                padding: '10px 20px', alignItems: 'center', fontSize: 12.5,
                borderBottom: i === CAPABILITY_MATRIX.length - 1 ? 'none' : '.5px solid var(--line)', minWidth: 460,
              }}>
                <span>{row.label}</span>
                {['admin','sales','viewer'].map(r => (
                  <span key={r} style={{ textAlign: 'center', color: row[r] ? ROLE_DEFS[r].tint : 'var(--muted)', fontSize: row[r] ? 14 : 13 }}>
                    {row[r] ? '✓' : '·'}
                  </span>
                ))}
              </div>
            ))}
          </div>
        </AdminCard>

        <AdminCard>
          <AdminCardHead title="Recent activity" subtitle={`${audit.length} events · who did what`} />
          <div style={{ padding: '4px 20px 16px', maxHeight: 440, overflowY: 'auto' }} className="scroll">
            {audit.length === 0 && (
              <div style={{ padding: 20, textAlign: 'center', fontSize: 12, color: 'var(--muted)' }}>No activity yet.</div>
            )}
            {audit.map(a => (
              <div key={a.id} style={{
                display: 'grid', gridTemplateColumns: '14px 1fr auto', gap: 10, padding: '10px 0',
                borderBottom: '.5px solid var(--line)', alignItems: 'flex-start',
              }}>
                <AuditEventDot action={a.action} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, lineHeight: 1.4 }}>
                    <strong style={{ fontWeight: 500 }}>{a.actor_name}</strong>
                    {' '}<span className="mono" style={{ fontSize: 10, color: 'var(--muted)', padding: '1px 5px', borderRadius: 4, background: 'var(--bg-2)' }}>{a.action}</span>
                  </div>
                  {a.summary && <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>{a.summary}</div>}
                </div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--muted)', whiteSpace: 'nowrap' }}>
                  {timeAgo(a.created_at)}
                </span>
              </div>
            ))}
          </div>
        </AdminCard>
      </div>

      {editing && (
        <TeamMemberModal
          member={editing}
          onClose={() => setEditing(null)}
          onSaved={() => { setEditing(null); refresh(); }}
        />
      )}
    </div>
  );
}

function timeAgo(isoish) {
  if (!isoish) return '';
  // SQLite format "YYYY-MM-DD HH:MM:SS" is UTC — normalise to ISO
  const iso = isoish.includes('T') ? isoish : isoish.replace(' ', 'T') + 'Z';
  const diff = Date.now() - new Date(iso).getTime();
  if (Number.isNaN(diff)) return '';
  const s = Math.floor(diff / 1000);
  if (s < 60) return 'just now';
  const m = Math.floor(s / 60); if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60); if (h < 24) return `${h}h ago`;
  const d = Math.floor(h / 24); if (d < 7)  return `${d}d ago`;
  return new Date(iso).toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });
}

function SettingsAdmin({ settings, setSettings }) {
  const [form, setForm] = React.useState(settings || {});
  const [team, setTeam] = React.useState([]);
  const [integrations, setIntegrations] = React.useState([]);
  const [saving, setSaving] = React.useState(false);
  const [saved, setSaved] = React.useState(false);
  const [editingMember, setEditingMember] = React.useState(null);

  const refreshTeam = () => api.get('/api/team').then(setTeam);

  React.useEffect(() => { setForm(settings || {}); }, [settings]);
  React.useEffect(() => {
    refreshTeam();
    api.get('/api/integrations').then(setIntegrations);
  }, []);

  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const save = async () => {
    setSaving(true);
    const fresh = await api.put('/api/settings', form);
    setSettings(fresh);
    setSaving(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  return (
    <div className="pad-lg" style={{ padding: '36px 40px 56px' }}>
      <AdminHeader
        eyebrow="Back office"
        title="Settings"
        desc="Anything a customer sees — contact info, address, brand strings — lives here."
        actions={<>
          {saved && <span className="mono" style={{ fontSize: 11, color: '#4A5D3A', letterSpacing: '0.06em', textTransform: 'uppercase', alignSelf: 'center' }}>Saved ✓</span>}
          <Button variant="primary" size="sm" onClick={save} disabled={saving}>
            {saving ? 'Saving…' : 'Save changes'}
          </Button>
        </>}
      />

      <div className="two-col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, marginTop: 24 }}>
        <AdminCard>
          <AdminCardHead title="Brand" subtitle="Shown in header, footer, proforma" />
          <div style={{ padding: '14px 20px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <EditField label="Company name" value={form.company_name || ''} onChange={(v) => update('company_name', v)} />
            <EditField label="Tagline"      value={form.tagline || ''}      onChange={(v) => update('tagline', v)} />
            <EditField label="Accent colour" value={form.accent || '#D4532A'} onChange={(v) => update('accent', v)} />
            <EditField label="Footer note"  value={form.footer_note || ''}  onChange={(v) => update('footer_note', v)} />
          </div>
        </AdminCard>

        <AdminCard>
          <AdminCardHead title="Contact" subtitle="How customers reach you" />
          <div style={{ padding: '14px 20px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <EditField label="Email" value={form.email || ''} onChange={(v) => update('email', v)} />
            <EditField label="Phone" value={form.phone || ''} onChange={(v) => update('phone', v)} />
          </div>
        </AdminCard>

        <WhatsAppSettingsCard form={form} update={update} />

        <AdminCard>
          <AdminCardHead title="Address" subtitle="Registered address shown on proforma" />
          <div style={{ padding: '14px 20px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <EditField label="Address line 1" value={form.address_line1 || ''} onChange={(v) => update('address_line1', v)} />
            <EditField label="Address line 2" value={form.address_line2 || ''} onChange={(v) => update('address_line2', v)} />
            <EditField label="City"           value={form.address_city || ''}  onChange={(v) => update('address_city', v)} />
            <EditField label="Postcode"       value={form.address_postcode || ''} onChange={(v) => update('address_postcode', v)} />
            <EditField label="Country"        value={form.address_country || ''} onChange={(v) => update('address_country', v)} />
            <EditField label="City header label" value={form.city_label || ''}  onChange={(v) => update('city_label', v)} />
          </div>
        </AdminCard>

        <AdminCard>
          <AdminCardHead title="Business" subtitle="VAT, lead times" />
          <div style={{ padding: '14px 20px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <EditField label="VAT number"    value={form.vat_number || ''}    onChange={(v) => update('vat_number', v)} />
            <EditField label="Lead time"     value={form.lead_time_days || ''} onChange={(v) => update('lead_time_days', v)} />
          </div>
        </AdminCard>

        <AdminCard>
          <AdminCardHead title="Team & access" subtitle={`${team.length} members`}
            actions={<Button variant="ghost" size="sm" icon={<Plus size={11}/>} onClick={() => setEditingMember({ name: '', role: '', email: '', username: '', password: '', access: 'viewer', active: true })}>Invite member</Button>}
          />
          <div style={{ padding: '8px 20px 20px' }}>
            {team.map((m, i) => (
              <div key={m.id} style={{ display: 'grid', gridTemplateColumns: '32px 1fr auto', gap: 12, alignItems: 'center', padding: '10px 0', borderBottom: i === team.length - 1 ? 'none' : '.5px solid var(--line)' }}>
                <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'linear-gradient(135deg,#3A362C,#8B857A)', color: '#fff', fontSize: 11, fontWeight: 500, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {m.name.split(' ').map(x => x[0]).join('').slice(0,2)}
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                    {m.name}
                    <span className="mono" style={{ fontSize: 10, padding: '2px 7px', borderRadius: 20, background: m.access === 'admin' ? 'rgba(212,83,42,.12)' : m.access === 'sales' ? 'rgba(74,93,58,.12)' : 'rgba(21,19,14,.06)', color: m.access === 'admin' ? 'var(--accent)' : m.access === 'sales' ? '#4A5D3A' : 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                      {m.access}
                    </span>
                    {!m.active && <span className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>inactive</span>}
                  </div>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>
                    {m.role} · {m.email}{m.username ? ` · @${m.username}` : ''}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <Button variant="ghost" size="sm" onClick={() => setEditingMember(m)}>Edit</Button>
                </div>
              </div>
            ))}
          </div>
        </AdminCard>

        <AdminCard>
          <AdminCardHead title="Integrations" subtitle="Connect your stack" />
          <div style={{ padding: '8px 20px 20px' }}>
            {integrations.map((m, i) => (
              <div key={m.name} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 0', borderBottom: i === integrations.length - 1 ? 'none' : '.5px solid var(--line)' }}>
                <span style={{ fontSize: 13 }}>{m.name}</span>
                <span className="mono" style={{ fontSize: 11, padding: '3px 8px', borderRadius: 20, background: m.status === 'Connected' ? 'rgba(74,93,58,.12)' : 'rgba(21,19,14,.06)', color: m.status === 'Connected' ? '#4A5D3A' : 'var(--muted)' }}>
                  {m.status}
                </span>
              </div>
            ))}
          </div>
        </AdminCard>
      </div>

      {editingMember && (
        <TeamMemberModal
          member={editingMember}
          onClose={() => setEditingMember(null)}
          onSaved={() => { setEditingMember(null); refreshTeam(); }}
        />
      )}
    </div>
  );
}

function WhatsAppSettingsCard({ form, update }) {
  const parsePrompts = (raw) => {
    if (!raw) return [];
    try { const p = JSON.parse(raw); return Array.isArray(p) ? p : []; } catch { return []; }
  };
  const prompts = parsePrompts(form.whatsapp_quick_prompts);

  const setPrompts = (next) => update('whatsapp_quick_prompts', JSON.stringify(next));
  const addPrompt = () => setPrompts([...prompts, { label: 'New prompt', text: '' }]);
  const updatePrompt = (i, patch) => setPrompts(prompts.map((p, idx) => idx === i ? { ...p, ...patch } : p));
  const removePrompt = (i) => setPrompts(prompts.filter((_, idx) => idx !== i));

  const testLink = `https://wa.me/${(form.whatsapp_number || '').replace(/\D/g, '')}?text=${encodeURIComponent((form.whatsapp_default_message || 'Hi').replace(/\{\{company\}\}/g, form.company_name || 'Lupipak'))}`;

  return (
    <AdminCard style={{ gridColumn: '1 / -1', borderColor: 'rgba(37,211,102,0.35)' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: '40px 1fr auto', gap: 12, alignItems: 'center',
        padding: '16px 20px', borderBottom: '.5px solid var(--line)',
        background: 'linear-gradient(90deg, rgba(37,211,102,0.06), transparent 60%)',
      }}>
        <div style={{
          width: 36, height: 36, borderRadius: '50%',
          background: '#25D366', display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 0 0 3px rgba(37,211,102,0.18)',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="#fff"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.966-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.198-.347.223-.644.074-.297-.148-1.254-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.297-.497.1-.198.05-.371-.025-.52-.074-.148-.669-1.611-.916-2.207-.241-.579-.487-.5-.669-.51-.173-.007-.371-.009-.57-.009-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.247-.694.247-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12.003 2.001h-.005A9.96 9.96 0 0 0 2 12a9.96 9.96 0 0 0 1.913 5.857L2 22l4.27-1.89A9.96 9.96 0 0 0 12.003 22 9.96 9.96 0 0 0 22 12.002 9.96 9.96 0 0 0 12.003 2z"/></svg>
        </div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: '-0.01em' }}>WhatsApp Business</div>
          <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 2 }}>
            Customer-facing launcher, homepage card, and proforma form pull everything from here
          </div>
        </div>
        {form.whatsapp_number && (
          <a href={testLink} target="_blank" rel="noopener noreferrer"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '8px 12px', borderRadius: 8, background: '#25D366', color: '#fff',
              fontSize: 12, fontWeight: 500, textDecoration: 'none',
            }}>
            Test chat <ArrowRight size={11}/>
          </a>
        )}
      </div>

      <div style={{ padding: '16px 20px 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <EditField label="WhatsApp number (digits only, no +)" value={form.whatsapp_number || ''} onChange={(v) => update('whatsapp_number', v)} />
        <EditField label="Display format (shown to users)"     value={form.whatsapp_display || ''} onChange={(v) => update('whatsapp_display', v)} />
        <EditField label="Business hours"                      value={form.whatsapp_hours || ''}   onChange={(v) => update('whatsapp_hours', v)} />
        <EditField label="Reply SLA (e.g. 2hr)"                value={form.whatsapp_reply_sla || ''} onChange={(v) => update('whatsapp_reply_sla', v)} />
        <EditField label="Presence" value={form.whatsapp_status || 'online'} onChange={(v) => update('whatsapp_status', v)} select options={[
          { value: 'online',  label: '● Online — replying now' },
          { value: 'away',    label: '◐ Away — within SLA' },
          { value: 'offline', label: '○ Offline — outside hours' },
        ]} />
        <EditField label="Business description (under the name)" value={form.whatsapp_business_description || ''} onChange={(v) => update('whatsapp_business_description', v)} />
        <div style={{ gridColumn: '1 / -1' }}>
          <EditField label="Welcome message (first bubble in the popover)"
            value={form.whatsapp_welcome_message || ''} onChange={(v) => update('whatsapp_welcome_message', v)} textarea />
        </div>
        <div style={{ gridColumn: '1 / -1' }}>
          <EditField label="Default outbound message — use {{company}} as a placeholder"
            value={form.whatsapp_default_message || ''} onChange={(v) => update('whatsapp_default_message', v)} textarea />
        </div>

        <div style={{ gridColumn: '1 / -1', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>
              Quick reply prompts ({prompts.length})
            </span>
            <button onClick={addPrompt}
              style={{
                padding: '4px 8px', fontSize: 11, fontFamily: 'inherit',
                background: 'var(--bg-2)', border: '.5px solid var(--line-2)', borderRadius: 6, cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 4,
              }}>
              <Plus size={10}/> Add prompt
            </button>
          </div>
          {prompts.length === 0 ? (
            <div style={{ padding: '12px 14px', background: 'var(--bg-2)', borderRadius: 8, fontSize: 11.5, color: 'var(--muted)' }}>
              No quick prompts — add some to make it faster for customers to pick a common question.
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {prompts.map((p, i) => (
                <div key={i} style={{
                  display: 'grid', gridTemplateColumns: '160px 1fr 24px', gap: 8, alignItems: 'center',
                  padding: '8px 10px', background: 'var(--bg-2)', borderRadius: 8,
                }}>
                  <input value={p.label} onChange={(e) => updatePrompt(i, { label: e.target.value })}
                    placeholder="Button label"
                    style={{ padding: '6px 8px', fontFamily: 'inherit', background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 6, outline: 'none' }}
                  />
                  <input value={p.text} onChange={(e) => updatePrompt(i, { text: e.target.value })}
                    placeholder="Pre-filled message — use {{company}} to inject name"
                    style={{ padding: '6px 8px', fontFamily: 'inherit', background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 6, outline: 'none' }}
                  />
                  <button onClick={() => removePrompt(i)} title="Remove"
                    style={{ width: 22, height: 22, border: 0, background: 'transparent', color: 'var(--muted)', cursor: 'pointer' }}>
                    <svg width="10" height="10" viewBox="0 0 16 16"><path d="M4 4 L12 12 M12 4 L4 12" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </AdminCard>
  );
}

function TeamMemberModal({ member, onClose, onSaved }) {
  const isNew = !member?.id;
  const [form, setForm] = React.useState({
    name: member.name || '', role: member.role || '', email: member.email || '',
    username: member.username || '', password: '', access: member.access || 'viewer',
    active: member.active !== false,
  });
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async () => {
    setBusy(true); setErr(null);
    try {
      const payload = { ...form };
      if (!payload.password) delete payload.password;
      if (isNew) await api.post('/api/team', payload);
      else       await api.put(`/api/team/${member.id}`, payload);
      onSaved?.();
    } catch (e) { setErr(e.message); }
    finally { setBusy(false); }
  };

  const remove = async () => {
    if (!confirm(`Remove ${form.name}?`)) return;
    setBusy(true);
    try { await api.del(`/api/team/${member.id}`); onSaved?.(); }
    catch (e) { setErr(e.message); setBusy(false); }
  };

  return (
    <Modal title={isNew ? 'Invite team member' : `Edit · ${member.name}`} onClose={onClose} footer={<>
      {!isNew && <Button variant="ghost" size="sm" onClick={remove} disabled={busy} style={{ marginRight: 'auto' }}>Remove</Button>}
      <Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
      <Button variant="primary" size="sm" onClick={submit} disabled={busy || !form.name || !form.email}>
        {busy ? 'Saving…' : (isNew ? 'Invite' : 'Save')}
      </Button>
    </>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <EditField label="Name"     value={form.name}     onChange={(v) => setForm({...form, name: v})} />
        <EditField label="Role / title" value={form.role} onChange={(v) => setForm({...form, role: v})} />
        <EditField label="Email"    value={form.email}    onChange={(v) => setForm({...form, email: v})} />
        <EditField label="Username" value={form.username} onChange={(v) => setForm({...form, username: v})} />
        <EditField label="Access level" value={form.access} onChange={(v) => setForm({...form, access: v})} select options={[
          { value: 'admin',  label: 'Admin — full access' },
          { value: 'sales',  label: 'Sales — leads only' },
          { value: 'viewer', label: 'Viewer — read only' },
        ]} />
        <EditField label={isNew ? 'Password' : 'New password (blank = keep)'} value={form.password} onChange={(v) => setForm({...form, password: v})} type="password" />
      </div>
      {!isNew && (
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, marginTop: 4 }}>
          <input type="checkbox" checked={form.active} onChange={(e) => setForm({...form, active: e.target.checked})}/>
          <span>Account active</span>
        </label>
      )}
      {err && <div style={{ fontSize: 12, color: 'var(--accent)' }}>{err}</div>}
    </Modal>
  );
}

// ──────────────────────────────────────────────
// Shared
// ──────────────────────────────────────────────

function AdminHeader({ eyebrow, title, desc, actions }) {
  return (
    <div className="stack-mobile" style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 20, alignItems: 'flex-end' }}>
      <div>
        <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 8 }}>
          {eyebrow}
        </div>
        <h1 className="responsive-h1" style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontSize: 44, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, lineHeight: 1 }}>
          {title}
        </h1>
        {desc && <p style={{ marginTop: 10, fontSize: 14, color: 'var(--muted)', maxWidth: 560 }}>{desc}</p>}
      </div>
      {actions && <div style={{ display: 'flex', gap: 8 }}>{actions}</div>}
    </div>
  );
}

function AdminCard({ children, style }) {
  return <div style={{ background: 'var(--paper)', border: '.5px solid var(--line-2)', borderRadius: 14, overflow: 'hidden', ...style }}>{children}</div>;
}

function AdminCardHead({ title, subtitle, actions }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12, alignItems: 'center', padding: '16px 20px 12px', borderBottom: '.5px solid var(--line)' }}>
      <div>
        <div style={{ fontSize: 13.5, fontWeight: 500, letterSpacing: '-0.01em' }}>{title}</div>
        {subtitle && <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 3 }}>{subtitle}</div>}
      </div>
      {actions}
    </div>
  );
}

function StatusPill({ status }) {
  const meta = STATUS_META[status] || STATUS_META.new;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '4px 8px', borderRadius: 20, fontSize: 11,
      background: meta.bg, color: meta.color, fontWeight: 500,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: '50%', background: meta.color }}/>
      {meta.label}
    </span>
  );
}

function FilterSelect({ label, value, onChange, options }) {
  return (
    <label style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5 }}>
      <span className="mono" style={{ color: 'var(--muted)', fontSize: 10, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{label}</span>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{
          border: '.5px solid var(--line-2)', background: 'var(--bg-2)',
          padding: '5px 8px', borderRadius: 6, fontFamily: 'inherit', color: 'var(--ink)', outline: 'none',
        }}
      >
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </label>
  );
}

function EditField({ label, value, onChange, select, textarea, options, disabled, type }) {
  const base = {
    padding: '9px 11px', fontFamily: 'inherit',
    background: 'var(--bg-2)', border: '.5px solid var(--line)', borderRadius: 8, outline: 'none',
    width: '100%', opacity: disabled ? 0.6 : 1,
  };
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--muted)' }}>{label}</span>
      {textarea ? (
        <textarea value={value ?? ''} disabled={disabled} onChange={(e) => onChange?.(e.target.value)} rows={2} style={{ ...base, resize: 'vertical' }}/>
      ) : select ? (
        <select value={value ?? ''} disabled={disabled} onChange={(e) => onChange?.(e.target.value)} style={base}>
          {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
        </select>
      ) : (
        <input type={type || 'text'} value={value ?? ''} disabled={disabled} onChange={(e) => onChange?.(e.target.value)} style={base}/>
      )}
    </label>
  );
}

function MetaLine({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 12.5, gap: 12 }}>
      <span className="mono" style={{ color: 'var(--muted)', fontSize: 10.5, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</span>
      <span style={{ textAlign: 'right', wordBreak: 'break-word' }}>{value}</span>
    </div>
  );
}

const DashIcon = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><rect x="2" y="2" width="5" height="7" rx="1" stroke="currentColor" strokeWidth="1.2"/><rect x="9" y="2" width="5" height="4" rx="1" stroke="currentColor" strokeWidth="1.2"/><rect x="9" y="8" width="5" height="6" rx="1" stroke="currentColor" strokeWidth="1.2"/><rect x="2" y="11" width="5" height="3" rx="1" stroke="currentColor" strokeWidth="1.2"/></svg>;
const LeadIcon = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M2 4 H14 M2 8 H14 M2 12 H14" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;
const ProdIcon = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M8 2 L14 5 V11 L8 14 L2 11 V5 Z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/><path d="M2 5 L8 8 L14 5 M8 8 V14" stroke="currentColor" strokeWidth="1.2"/></svg>;
const SectIcon = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.2"/><path d="M8 2 V14 M2 8 H14" stroke="currentColor" strokeWidth="1.2"/></svg>;
const SettIcon = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="2.5" stroke="currentColor" strokeWidth="1.2"/><path d="M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;
const TeamIcon = () => <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="5.5" cy="6" r="2.2" stroke="currentColor" strokeWidth="1.2"/><circle cx="11" cy="6.5" r="1.8" stroke="currentColor" strokeWidth="1.2"/><path d="M1.5 13.5 C 2 10.5 4 10 5.5 10 C 7 10 9 10.5 9.5 13.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/><path d="M10 13.5 C 10.3 11.5 11.5 11 12.5 11 C 13.5 11 14.3 11.5 14.5 13.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;

Object.assign(window, { Admin });
