// =============================================================
// AM (Account Manager) portal — separate area for Clicky staff
// to manage their book of clients. Two-tier login (Client / AM)
// drops AMs into a portfolio dashboard from which they can drill
// into any individual client portal (with an AM ribbon overlay).
// =============================================================

const { useState } = React;

// AM's own profile — persisted to localStorage so edits survive
// reloads. Falls back to these defaults on first run.
const AM_USER_DEFAULTS = {
  name: 'Joe Marshall',
  firstName: 'Joe',
  role: 'Head of Client Strategy',
  email: 'joe@clicky.co.uk',
  phone: '+44 161 808 1888',
  bio: '12 years across paid and lifecycle, ex-AMV BBDO. Lead AM on Cornish hospitality + DTC pods at Clicky.',
  avatar: 'assets/team/joe.png',
  hue: 200,
  calendarUrl: 'https://cal.com/joe-marshall/15min',
  timezone: 'Europe/London',
  workingHours: '9:00 – 17:30',
  notifications: {
    clientFlags:        true,   // email me when a client goes critical
    contractApprovals:  true,
    weeklyDigest:       true,
    aiSuggestionDaily:  false,
    invoiceOverdue:     true,
  },
};

const loadAmProfile = () => {
  try {
    const raw = localStorage.getItem('clicky_am_profile');
    if (raw) return { ...AM_USER_DEFAULTS, ...JSON.parse(raw) };
  } catch (e) {}
  return { ...AM_USER_DEFAULTS };
};
const saveAmProfile = (p) => {
  try { localStorage.setItem('clicky_am_profile', JSON.stringify(p)); } catch(e) {}
};

// Live AM_USER object — mutated in place when profile is saved so
// every script tag's bare reference picks up the new values on
// the next render.
const AM_USER = loadAmProfile();

// 15 mock clients — diverse UK SMB mix. Health distribution roughly
// 9 good · 4 watch · 2 critical so the portfolio reads realistically.
const AM_CLIENTS = [
  {
    id: 'evergreen',
    name: 'Evergreen Escapes',
    shortName: 'Evergreen',
    industry: 'Self-catering lodge holidays · Cornwall',
    url: 'evergreen-escapes.co.uk',
    tier: 'Premier',
    mrr: 4250,
    health: 'good',
    services: ['Google Ads', 'Meta Ads', 'SEO', 'Maintenance Pro', 'GA4 Tagging'],
    contact: 'Daniel Trevethan',
    contactRole: 'Owner',
    lastContact: '2 days ago',
    nextRenewal: '01 Mar 2027',
    isLive: true,
    thisWeek: [
      { kind: 'report',  label: 'April performance report due',         when: 'Wed 6 May' },
      { kind: 'opp',     label: 'Maintenance Pro upsell decision',      when: 'This week' },
    ],
  },
  {
    id: 'halcyon',
    name: 'Halcyon Dental',
    shortName: 'Halcyon',
    industry: 'Private dental clinic · West London',
    url: 'halcyondental.co.uk',
    tier: 'Pro',
    mrr: 2400,
    health: 'watch',
    services: ['Google Ads', 'SEO'],
    contact: 'Dr Priya Kapoor',
    contactRole: 'Practice Owner',
    lastContact: '5 days ago',
    nextRenewal: '12 Aug 2026',
    thisWeek: [
      { kind: 'flag',   label: 'Search spend pacing 12% over budget',    when: 'Today' },
      { kind: 'ticket', label: 'GA4 conversion mismatch — needs reply',  when: 'Yesterday' },
    ],
  },
  {
    id: 'wickham',
    name: 'Wickham & Co.',
    shortName: 'Wickham',
    industry: 'Family law firm · Bristol',
    url: 'wickhamco.legal',
    tier: 'Pro',
    mrr: 3100,
    health: 'good',
    services: ['Google Ads', 'SEO', 'Local SEO'],
    contact: 'Eleanor Wickham',
    contactRole: 'Managing Partner',
    lastContact: '1 week ago',
    nextRenewal: '01 Oct 2026',
    thisWeek: [
      { kind: 'report', label: 'Quarterly review deck',                  when: 'Thu 7 May' },
    ],
  },
  {
    id: 'northwind',
    name: 'Northwind Cycles',
    shortName: 'Northwind',
    industry: 'DTC ebike retailer · Glasgow → UK',
    url: 'northwindcycles.co.uk',
    tier: 'Premier',
    mrr: 6200,
    health: 'watch',
    services: ['Google Ads', 'Meta Ads', 'TikTok Ads', 'SEO', 'CRO', 'Email'],
    contact: 'Callum Reid',
    contactRole: 'Head of Growth',
    lastContact: '3 days ago',
    nextRenewal: '15 Nov 2026',
    thisWeek: [
      { kind: 'flag',   label: 'ROAS dipping — Performance Max review',  when: 'Today' },
      { kind: 'opp',    label: 'TikTok creative test green-lit',         when: 'This week' },
      { kind: 'report', label: 'April spend reconciliation',             when: 'Fri 8 May' },
    ],
  },
  {
    id: 'mariner',
    name: 'Mariner Boats',
    shortName: 'Mariner',
    industry: 'Marine engineering · Plymouth',
    url: 'marinerboats.co.uk',
    tier: 'Standard',
    mrr: 950,
    health: 'good',
    services: ['Google Ads'],
    contact: 'Ian Petrie',
    contactRole: 'Director',
    lastContact: '2 weeks ago',
    nextRenewal: '20 Jan 2027',
    thisWeek: [],
  },
  {
    id: 'saffron',
    name: 'Saffron Collective',
    shortName: 'Saffron',
    industry: 'Indian restaurant group · Manchester',
    url: 'saffroncollective.com',
    tier: 'Pro',
    mrr: 2750,
    health: 'good',
    services: ['Google Ads', 'Meta Ads', 'Local SEO', 'Reservations attribution'],
    contact: 'Aditi Sharma',
    contactRole: 'Marketing Director',
    lastContact: 'Yesterday',
    nextRenewal: '03 Sep 2026',
    thisWeek: [
      { kind: 'opp',    label: 'New Liverpool venue — onboarding kickoff', when: 'Tue 5 May' },
    ],
  },
  {
    id: 'ridgeline',
    name: 'Ridgeline Roofing',
    shortName: 'Ridgeline',
    industry: 'Roofing & insulation · North Yorkshire',
    url: 'ridgelineroofing.co.uk',
    tier: 'Standard',
    mrr: 1150,
    health: 'watch',
    services: ['Google Ads', 'Local SEO'],
    contact: 'Mark Holloway',
    contactRole: 'Owner',
    lastContact: '4 days ago',
    nextRenewal: '01 Jul 2026',
    thisWeek: [
      { kind: 'flag',   label: 'Lead quality flagged — Form spam up 23%', when: 'Today' },
    ],
  },
  {
    id: 'beacon',
    name: 'Beacon Reads',
    shortName: 'Beacon',
    industry: "Children's literacy charity · National",
    url: 'beaconreads.org.uk',
    tier: 'Standard',
    mrr: 0,
    mrrNote: 'Google Ad Grants pro-bono',
    health: 'good',
    services: ['Google Ad Grants', 'SEO'],
    contact: 'Sarah Whitfield',
    contactRole: 'Director of Engagement',
    lastContact: '1 week ago',
    nextRenewal: 'Pro-bono · annual',
    thisWeek: [
      { kind: 'report', label: 'Grants compliance review',                when: 'Mon 4 May' },
    ],
  },
  {
    id: 'lumen',
    name: 'Lumen Skincare',
    shortName: 'Lumen',
    industry: 'DTC clean beauty · UK + DE',
    url: 'lumenskincare.com',
    tier: 'Premier',
    mrr: 5400,
    health: 'critical',
    services: ['Google Ads', 'Meta Ads', 'TikTok Ads', 'Influencer attribution', 'Email/SMS'],
    contact: 'Olivia Brennan',
    contactRole: 'CMO',
    lastContact: 'Today',
    nextRenewal: '14 Dec 2026',
    thisWeek: [
      { kind: 'flag',   label: 'CAC up 38% — emergency review call',      when: 'Today' },
      { kind: 'flag',   label: 'Meta creative fatigue across 4 ad sets',  when: 'Today' },
      { kind: 'report', label: 'CAC unwind report for Olivia',            when: 'Tue 5 May' },
    ],
  },
  {
    id: 'kestrel',
    name: 'Kestrel Fitness',
    shortName: 'Kestrel',
    industry: 'Boutique gym chain · London (4 sites)',
    url: 'kestrelfitness.co.uk',
    tier: 'Pro',
    mrr: 2200,
    health: 'good',
    services: ['Google Ads', 'Meta Ads', 'Local SEO'],
    contact: 'Rob Davenport',
    contactRole: 'Founder',
    lastContact: '6 days ago',
    nextRenewal: '01 Jun 2026',
    thisWeek: [
      { kind: 'renewal', label: 'Renewal conversation — June',            when: 'Fri 8 May' },
    ],
  },
  {
    id: 'apex',
    name: 'Apex Motors',
    shortName: 'Apex',
    industry: 'Used car dealership · Leeds',
    url: 'apexmotorsleeds.co.uk',
    tier: 'Standard',
    mrr: 1300,
    health: 'good',
    services: ['Google Ads', 'Vehicle inventory feeds'],
    contact: 'Gareth Morley',
    contactRole: 'Sales Director',
    lastContact: '10 days ago',
    nextRenewal: '01 Feb 2027',
    thisWeek: [],
  },
  {
    id: 'threadbare',
    name: 'Threadbare Vintage',
    shortName: 'Threadbare',
    industry: 'DTC vintage fashion · UK',
    url: 'threadbarevintage.co.uk',
    tier: 'Pro',
    mrr: 2100,
    health: 'critical',
    services: ['Meta Ads', 'TikTok Ads', 'SEO', 'Email'],
    contact: 'Nia Okafor',
    contactRole: 'Founder',
    lastContact: '2 days ago',
    nextRenewal: '20 Sep 2026',
    thisWeek: [
      { kind: 'flag',   label: 'Conv. rate down 31% post site re-skin',   when: 'Today' },
      { kind: 'ticket', label: 'Meta pixel events misfiring on PDP',      when: 'Today' },
    ],
  },
  {
    id: 'glasshouse',
    name: 'Glasshouse Studios',
    shortName: 'Glasshouse',
    industry: 'Wedding photography · Cotswolds',
    url: 'glasshousestudios.co.uk',
    tier: 'Standard',
    mrr: 850,
    health: 'good',
    services: ['Google Ads', 'SEO'],
    contact: 'Henry Ashworth',
    contactRole: 'Owner',
    lastContact: '2 weeks ago',
    nextRenewal: '01 May 2026',
    thisWeek: [
      { kind: 'renewal', label: 'Renewal — overdue by 1 day',             when: 'Today' },
    ],
  },
  {
    id: 'tideway',
    name: 'Tideway Logistics',
    shortName: 'Tideway',
    industry: 'B2B haulage · Felixstowe',
    url: 'tidewaylogistics.co.uk',
    tier: 'Pro',
    mrr: 2900,
    health: 'watch',
    services: ['Google Ads', 'LinkedIn Ads', 'SEO'],
    contact: 'Phil Walmsley',
    contactRole: 'Commercial Director',
    lastContact: '4 days ago',
    nextRenewal: '15 Oct 2026',
    thisWeek: [
      { kind: 'flag',   label: 'Quality Score drop on freight terms',     when: 'Today' },
    ],
  },
  {
    id: 'hearth',
    name: 'Hearth & Home',
    shortName: 'Hearth & Home',
    industry: 'Furniture retailer · 6 showrooms',
    url: 'hearthandhomeuk.co.uk',
    tier: 'Premier',
    mrr: 4750,
    health: 'good',
    services: ['Google Ads', 'Meta Ads', 'SEO', 'Shopping feeds', 'CRO'],
    contact: 'Vanessa Kim',
    contactRole: 'Head of Digital',
    lastContact: '3 days ago',
    nextRenewal: '01 Apr 2027',
    thisWeek: [
      { kind: 'report', label: 'Shopping feed health audit',              when: 'Wed 6 May' },
      { kind: 'opp',    label: 'CRO scope-of-work proposal due',          when: 'Fri 8 May' },
    ],
  },
];

// Stash on window so other scripts can read.
Object.assign(window, { AM_USER, AM_CLIENTS });

// Mutate window.CLIENT so the existing client portal screens render
// for whichever client the AM has drilled into. We keep a snapshot of
// the original Evergreen client object so we can restore on exit.
const __CLICKY_ORIGINAL_CLIENT__ = window.CLIENT ? { ...window.CLIENT } : null;
window.swapActiveClient = (clientId) => {
  if (!window.CLIENT) return;
  const c = AM_CLIENTS.find(x => x.id === clientId);
  if (!c) {
    // restore original
    if (__CLICKY_ORIGINAL_CLIENT__) {
      Object.assign(window.CLIENT, __CLICKY_ORIGINAL_CLIENT__);
    }
    return;
  }
  Object.assign(window.CLIENT, {
    name: c.name,
    shortName: c.shortName,
    url: c.url,
    contact: c.contact,
    contactRole: c.contactRole,
    tier: c.tier,
  });
};

// =============================================================
// Login screen — two-tile route picker. Mock auth, persists choice.
// =============================================================
const LoginScreen = ({ onLogin }) => {
  return (
    <div style={{
      minHeight: '100vh',
      display: 'grid', placeItems: 'center',
      background: 'linear-gradient(180deg, #f4f4f5 0%, #e8eef9 100%)',
      padding: 24,
    }}>
      <div style={{
        width: '100%', maxWidth: 720,
        background: 'var(--surface)',
        border: '1px solid var(--border)',
        borderRadius: 'var(--radius)',
        boxShadow: '0 12px 40px rgba(24,24,27,0.08)',
        padding: '40px 36px 32px',
      }}>
        {/* Brand */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 14, marginBottom: 28 }}>
          <img src="assets/clicky-logo.png" alt="Clicky" style={{ height: 48, width: 'auto', display: 'block' }} />
          <div style={{ width: 1, height: 32, background: 'var(--border)' }} />
          <div>
            <div style={{ fontSize: 9, color: 'var(--text-faint)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.14em' }}>Enterprise</div>
            <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-0.005em' }}>Client Portal</div>
          </div>
        </div>

        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <h1 style={{ fontSize: 22, fontWeight: 700, margin: 0, letterSpacing: '-0.02em' }}>Sign in to continue</h1>
          <p style={{ fontSize: 13, color: 'var(--text-muted)', margin: '6px 0 0' }}>Choose how you'd like to enter the portal.</p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          {/* Client tile */}
          <button
            onClick={() => onLogin('client')}
            style={{
              padding: '20px 18px', textAlign: 'left',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--radius)',
              cursor: 'pointer', fontFamily: 'inherit',
              transition: 'border-color 120ms ease, box-shadow 120ms ease, transform 80ms ease',
              display: 'flex', flexDirection: 'column', gap: 12,
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--primary)'; e.currentTarget.style.boxShadow = '0 4px 14px rgba(37,99,235,0.10)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.boxShadow = 'none'; }}
            onMouseDown={e => { e.currentTarget.style.transform = 'translateY(1px)'; }}
            onMouseUp={e => { e.currentTarget.style.transform = 'translateY(0)'; }}
          >
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: 'color-mix(in oklab, var(--primary) 12%, transparent)',
              color: 'var(--primary)', display: 'grid', placeItems: 'center',
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 21h18"/><path d="M5 21V7l8-4 8 4v14"/><path d="M9 21v-8h6v8"/></svg>
            </div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>I'm a Clicky client</div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2, lineHeight: 1.5 }}>
                See your performance, reports, contracts and your Clicky team.
              </div>
            </div>
            <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--primary)', fontSize: 12, fontWeight: 600 }}>
              Continue
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </div>
          </button>

          {/* AM tile */}
          <button
            onClick={() => onLogin('am')}
            style={{
              padding: '20px 18px', textAlign: 'left',
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--radius)',
              cursor: 'pointer', fontFamily: 'inherit',
              transition: 'border-color 120ms ease, box-shadow 120ms ease, transform 80ms ease',
              display: 'flex', flexDirection: 'column', gap: 12,
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = '#0f172a'; e.currentTarget.style.boxShadow = '0 4px 14px rgba(15,23,42,0.10)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.boxShadow = 'none'; }}
            onMouseDown={e => { e.currentTarget.style.transform = 'translateY(1px)'; }}
            onMouseUp={e => { e.currentTarget.style.transform = 'translateY(0)'; }}
          >
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: 'color-mix(in oklab, #0f172a 92%, transparent)',
              color: '#fff', display: 'grid', placeItems: 'center',
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M16 11h.01M11 11h.01"/></svg>
            </div>
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>I'm at Clicky</div>
                <span style={{
                  display: 'inline-flex', alignItems: 'center',
                  padding: '1px 6px', borderRadius: 99,
                  background: '#0f172a', color: '#fff', fontSize: 9, fontWeight: 700,
                  letterSpacing: '0.06em',
                }}>STAFF</span>
              </div>
              <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2, lineHeight: 1.5 }}>
                Account manager view: portfolio of {AM_CLIENTS.length} clients, this week's queue, drill into any account.
              </div>
            </div>
            <div style={{ marginTop: 'auto', display: 'flex', alignItems: 'center', gap: 6, color: 'var(--text)', fontSize: 12, fontWeight: 600 }}>
              Continue
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </div>
          </button>
        </div>

        <div style={{ marginTop: 24, fontSize: 11, color: 'var(--text-faint)', textAlign: 'center' }}>
          Mock sign-in for prototype. Production would use Clicky SSO.
        </div>
      </div>
    </div>
  );
};

// =============================================================
// AM sidebar — distinct from client sidebar (dark internal-staff
// feel; no client account-manager card).
// =============================================================
const AmSidebar = ({ active, setActive, onSignOut, onOpenClient, currentClientId }) => {
  const queueCount = AM_CLIENTS.reduce((n, c) => n + c.thisWeek.length, 0);
  const NavRow = ({ id, icon, label, badge }) => {
    const isActive = active === id;
    return (
      <button
        onClick={() => setActive(id)}
        style={{
          display: 'flex', alignItems: 'center', gap: 10,
          width: '100%', padding: '8px 12px',
          background: isActive ? 'rgba(255,255,255,0.08)' : 'transparent',
          color: isActive ? '#fff' : 'rgba(255,255,255,0.7)',
          border: 'none', borderRadius: 6,
          fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
          textAlign: 'left', cursor: 'pointer',
          transition: 'background 120ms ease, color 120ms ease',
        }}
        onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; }}
        onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
      >
        <span style={{ width: 16, height: 16, display: 'inline-grid', placeItems: 'center', flexShrink: 0 }}>{icon}</span>
        <span style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</span>
        {badge != null && (
          <span style={{
            fontSize: 10, fontWeight: 600, padding: '1px 6px', borderRadius: 99,
            background: 'rgba(255,255,255,0.10)', color: 'rgba(255,255,255,0.8)',
            minWidth: 18, textAlign: 'center',
          }}>{badge}</span>
        )}
      </button>
    );
  };

  return (
    <aside style={{
      width: 260, flexShrink: 0,
      background: '#0f172a',
      color: '#fff',
      display: 'flex', flexDirection: 'column',
      height: '100vh', position: 'sticky', top: 0,
      overflowY: 'auto',
    }}>
      {/* Brand */}
      <div style={{
        padding: '16px 16px 14px',
        borderBottom: '1px solid rgba(255,255,255,0.08)',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <img src="assets/clicky-logo-vert-white.png" alt="Clicky" style={{ height: 36, width: 'auto', display: 'block' }} />
        <div style={{ width: 1, height: 28, background: 'rgba(255,255,255,0.12)' }} />
        <div style={{ minWidth: 0 }}>
          <div style={{
            fontSize: 9, color: 'rgba(255,255,255,0.5)', fontWeight: 600,
            textTransform: 'uppercase', letterSpacing: '0.12em',
          }}>Account Manager</div>
          <div style={{ fontSize: 12, color: '#fff', fontWeight: 600 }}>Internal</div>
        </div>
      </div>

      {/* AM profile — click to open profile settings */}
      <button
        onClick={() => setActive('profile')}
        title="My profile"
        style={{
          margin: 12, padding: 10,
          background: active === 'profile' ? 'rgba(255,255,255,0.10)' : 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.06)',
          borderRadius: 8, fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', gap: 10,
          cursor: 'pointer', textAlign: 'left',
          transition: 'background 120ms ease',
        }}
        onMouseEnter={e => { if (active !== 'profile') e.currentTarget.style.background = 'rgba(255,255,255,0.06)'; }}
        onMouseLeave={e => { if (active !== 'profile') e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; }}
      >
        <PersonAvatar name={AM_USER.name} size={36} hue={AM_USER.hue} src={AM_USER.avatar} />
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: '#fff', lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{AM_USER.name}</div>
          <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.55)', marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{AM_USER.role}</div>
        </div>
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'rgba(255,255,255,0.4)', flexShrink: 0 }}><path d="M9 6l6 6-6 6"/></svg>
      </button>

      {/* Nav */}
      <div style={{ padding: '4px 8px', display: 'flex', flexDirection: 'column', gap: 1 }}>
        <NavRow id="portfolio" label="Portfolio"
          icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg>}
          badge={AM_CLIENTS.length}
        />
        <NavRow id="thisweek" label="This Week"
          icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 11h18"/></svg>}
          badge={queueCount}
        />
        <NavRow id="reports" label="Reports queue"
          icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>}
        />
        <NavRow id="performance" label="Performance flags"
          icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4 22V4M4 4h12l-2 4 2 4H4"/></svg>}
        />
        <NavRow id="team" label="Internal team"
          icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3.5"/><circle cx="17" cy="9" r="2.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0"/><path d="M15 20a5 5 0 0 1 6.5-4.8"/></svg>}
        />
        <NavRow id="profile" label="My profile"
          icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>}
        />
      </div>

      <div style={{ flex: 1 }} />

      {/* Quick switch — clients */}
      <div style={{ padding: '8px 12px', borderTop: '1px solid rgba(255,255,255,0.08)' }}>
        <div style={{
          fontSize: 9, color: 'rgba(255,255,255,0.4)', fontWeight: 600,
          textTransform: 'uppercase', letterSpacing: '0.10em', padding: '6px 4px 4px',
        }}>Quick switch</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 1, maxHeight: 220, overflowY: 'auto' }}>
          {AM_CLIENTS.slice(0, 6).map(c => (
            <button key={c.id}
              onClick={() => onOpenClient(c.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 8,
                width: '100%', padding: '6px 8px',
                background: currentClientId === c.id ? 'rgba(255,255,255,0.08)' : 'transparent',
                color: currentClientId === c.id ? '#fff' : 'rgba(255,255,255,0.7)',
                border: 'none', borderRadius: 6, cursor: 'pointer',
                fontSize: 12, fontFamily: 'inherit', textAlign: 'left',
              }}
              onMouseEnter={e => { if (currentClientId !== c.id) e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; }}
              onMouseLeave={e => { if (currentClientId !== c.id) e.currentTarget.style.background = 'transparent'; }}
            >
              <span style={{
                width: 6, height: 6, borderRadius: '50%', flexShrink: 0,
                background: c.health === 'good' ? '#22c55e' : c.health === 'watch' ? '#f59e0b' : '#ef4444',
              }}/>
              <span style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.shortName}</span>
            </button>
          ))}
          <div style={{ fontSize: 10.5, color: 'rgba(255,255,255,0.4)', padding: '4px 8px' }}>
            +{AM_CLIENTS.length - 6} more in Portfolio
          </div>
        </div>
      </div>

      {/* Sign out */}
      <div style={{ padding: 12, borderTop: '1px solid rgba(255,255,255,0.08)' }}>
        <button onClick={onSignOut} style={{
          width: '100%', padding: '8px 10px',
          background: 'transparent', color: 'rgba(255,255,255,0.7)',
          border: '1px solid rgba(255,255,255,0.10)', borderRadius: 6,
          fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
          cursor: 'pointer',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/></svg>
          Sign out
        </button>
      </div>
    </aside>
  );
};

// =============================================================
// AM topbar — slim, no search, just title + AM utility actions.
// =============================================================
const AmTopbar = ({ title, subtitle, actions }) => (
  <div style={{
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    gap: 16, padding: '14px 24px',
    background: 'var(--surface)',
    borderBottom: '1px solid var(--border)',
    position: 'sticky', top: 0, zIndex: 20,
  }}>
    <div style={{ minWidth: 0 }}>
      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{title}</div>
      {subtitle && <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 1 }}>{subtitle}</div>}
    </div>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>{actions}</div>
  </div>
);

// =============================================================
// Health pill — used everywhere a client appears.
// =============================================================
const HealthPill = ({ health }) => {
  const map = {
    good:     { label: 'On track', color: '#16a34a', bg: 'color-mix(in oklab, #16a34a 12%, transparent)' },
    watch:    { label: 'Watch',    color: '#d97706', bg: 'color-mix(in oklab, #d97706 14%, transparent)' },
    critical: { label: 'Critical', color: '#dc2626', bg: 'color-mix(in oklab, #dc2626 14%, transparent)' },
  };
  const t = map[health] || map.good;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '2px 8px', borderRadius: 99,
      background: t.bg, color: t.color,
      fontSize: 10.5, fontWeight: 600,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: '50%', background: t.color }}/>
      {t.label}
    </span>
  );
};

const TierBadge = ({ tier }) => {
  const map = {
    Premier:  { color: '#7c3aed', bg: 'color-mix(in oklab, #7c3aed 10%, transparent)' },
    Pro:      { color: '#2563eb', bg: 'color-mix(in oklab, #2563eb 10%, transparent)' },
    Standard: { color: '#52525b', bg: 'var(--surface-2)' },
  };
  const t = map[tier] || map.Standard;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      padding: '1px 7px', borderRadius: 99,
      background: t.bg, color: t.color,
      fontSize: 9.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase',
    }}>{tier}</span>
  );
};

const KIND_ICONS = {
  report:  { icon: <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>, color: '#2563eb', label: 'Report' },
  flag:    { icon: <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 22V4M4 4h12l-2 4 2 4H4"/></svg>, color: '#dc2626', label: 'Flag' },
  ticket:  { icon: <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a1 1 0 0 0 0 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3a1 1 0 0 0 0-2z"/></svg>, color: '#d97706', label: 'Ticket' },
  opp:     { icon: <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2v4M12 18v4M2 12h4M18 12h4M5 5l3 3M16 16l3 3M5 19l3-3M16 8l3-3"/></svg>, color: '#7c3aed', label: 'Opportunity' },
  renewal: { icon: <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9 9 0 0 1 7 3"/><path d="M3 5v6h6M21 12a9 9 0 0 1-9 9 9 9 0 0 1-7-3"/><path d="M21 19v-6h-6"/></svg>, color: '#16a34a', label: 'Renewal' },
};

// =============================================================
// Portfolio screen — grid of all 15 clients.
// =============================================================
const AmPortfolioScreen = ({ onOpenClient }) => {
  const [healthFilter, setHealthFilter] = useState('all');
  const [tierFilter, setTierFilter] = useState('all');
  const [sortBy, setSortBy] = useState('attention');
  const [search, setSearch] = useState('');

  const totalMrr = AM_CLIENTS.reduce((n, c) => n + (c.mrr || 0), 0);
  const flags = AM_CLIENTS.filter(c => c.health !== 'good').length;
  const reportsDue = AM_CLIENTS.reduce((n, c) => n + c.thisWeek.filter(t => t.kind === 'report').length, 0);

  const filtered = AM_CLIENTS
    .filter(c => healthFilter === 'all' || c.health === healthFilter)
    .filter(c => tierFilter === 'all' || c.tier === tierFilter)
    .filter(c => !search.trim() || c.name.toLowerCase().includes(search.toLowerCase()) || c.industry.toLowerCase().includes(search.toLowerCase()))
    .sort((a, b) => {
      if (sortBy === 'attention') {
        const score = c => (c.health === 'critical' ? 1000 : c.health === 'watch' ? 500 : 0) + c.thisWeek.length * 10;
        return score(b) - score(a);
      }
      if (sortBy === 'mrr')   return (b.mrr || 0) - (a.mrr || 0);
      if (sortBy === 'name')  return a.name.localeCompare(b.name);
      return 0;
    });

  return (
    <div>
      <AmTopbar
        title="Your portfolio"
        subtitle={`${AM_CLIENTS.length} active clients · led by ${AM_USER.name}`}
        actions={<>
          <button style={{
            padding: '6px 12px', borderRadius: 6,
            background: 'var(--surface-2)', color: 'var(--text)',
            border: '1px solid var(--border)', fontSize: 12, fontFamily: 'inherit',
            fontWeight: 500, cursor: 'pointer',
          }}>Export CSV</button>
          <button style={{
            padding: '6px 12px', borderRadius: 6,
            background: '#0f172a', color: '#fff',
            border: '1px solid #0f172a', fontSize: 12, fontFamily: 'inherit',
            fontWeight: 500, cursor: 'pointer',
          }}>+ Add client</button>
        </>}
      />

      <div style={{ padding: 24, maxWidth: 1400, width: '100%', margin: '0 auto' }}>
        {/* Summary strip */}
        <Card padding={0} style={{ marginBottom: 16 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)' }}>
            {[
              { label: 'Active clients',    value: AM_CLIENTS.length, sub: `${AM_CLIENTS.filter(c => c.tier === 'Premier').length} Premier · ${AM_CLIENTS.filter(c => c.tier === 'Pro').length} Pro · ${AM_CLIENTS.filter(c => c.tier === 'Standard').length} Standard` },
              { label: 'Combined MRR',      value: `£${(totalMrr/1000).toFixed(1)}k`, sub: `${AM_CLIENTS.filter(c => c.mrr === 0).length} pro-bono` },
              { label: 'Health flags',      value: flags, sub: `${AM_CLIENTS.filter(c => c.health === 'critical').length} critical · ${AM_CLIENTS.filter(c => c.health === 'watch').length} watch`, tone: flags > 4 ? 'warning' : 'muted' },
              { label: 'Reports due / wk',  value: reportsDue, sub: 'across the book' },
            ].map((s, i) => (
              <div key={s.label} style={{
                padding: '16px 20px',
                borderLeft: i === 0 ? 'none' : '1px solid var(--border)',
              }}>
                <div style={{ fontSize: 10, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>{s.label}</div>
                <div style={{
                  fontSize: 22, fontWeight: 700, fontVariantNumeric: 'tabular-nums', marginTop: 4, letterSpacing: '-0.01em',
                  color: s.tone === 'warning' ? 'var(--warning)' : 'var(--text)',
                }}>{s.value}</div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{s.sub}</div>
              </div>
            ))}
          </div>
        </Card>

        {/* Filters */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '6px 10px', background: 'var(--surface)',
            border: '1px solid var(--border)', borderRadius: 'var(--radius)',
            flex: 1, minWidth: 220, maxWidth: 360,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--text-faint)' }}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
            <input
              value={search}
              onChange={e => setSearch(e.target.value)}
              placeholder="Search clients…"
              style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 13, color: 'var(--text)', fontFamily: 'inherit' }}
            />
          </div>
          <SegmentedControl value={healthFilter} onChange={setHealthFilter} options={[
            { value: 'all',      label: 'All' },
            { value: 'critical', label: 'Critical' },
            { value: 'watch',    label: 'Watch' },
            { value: 'good',     label: 'On track' },
          ]} />
          <SegmentedControl value={tierFilter} onChange={setTierFilter} options={[
            { value: 'all',      label: 'All tiers' },
            { value: 'Premier',  label: 'Premier' },
            { value: 'Pro',      label: 'Pro' },
            { value: 'Standard', label: 'Standard' },
          ]} />
          <SegmentedControl value={sortBy} onChange={setSortBy} options={[
            { value: 'attention', label: 'Attention' },
            { value: 'mrr',       label: 'MRR' },
            { value: 'name',      label: 'A–Z' },
          ]} />
        </div>

        {/* Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 12 }}>
          {filtered.map(c => <PortfolioCard key={c.id} c={c} onOpen={() => onOpenClient(c.id)} />)}
          {filtered.length === 0 && (
            <div style={{
              gridColumn: '1 / -1',
              padding: '60px 20px',
              textAlign: 'center', color: 'var(--text-muted)', fontSize: 13,
              background: 'var(--surface)', border: '1px dashed var(--border)', borderRadius: 'var(--radius)',
            }}>
              No clients match those filters.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const SegmentedControl = ({ value, onChange, options }) => (
  <div style={{
    display: 'inline-flex',
    background: 'var(--surface-2)',
    border: '1px solid var(--border)',
    borderRadius: 6, padding: 2,
  }}>
    {options.map(o => (
      <button key={o.value} onClick={() => onChange(o.value)} style={{
        padding: '5px 10px', fontSize: 11.5, fontWeight: 500, fontFamily: 'inherit',
        background: value === o.value ? 'var(--surface)' : 'transparent',
        color: value === o.value ? 'var(--text)' : 'var(--text-muted)',
        border: 'none', borderRadius: 4, cursor: 'pointer',
        boxShadow: value === o.value ? 'var(--shadow-sm)' : 'none',
      }}>{o.label}</button>
    ))}
  </div>
);

const PortfolioCard = ({ c, onOpen }) => (
  <button onClick={onOpen} style={{
    textAlign: 'left', padding: 0,
    background: 'var(--surface)',
    border: '1px solid var(--border)',
    borderRadius: 'var(--radius)',
    cursor: 'pointer',
    transition: 'border-color 120ms ease, box-shadow 120ms ease',
    display: 'flex', flexDirection: 'column',
    overflow: 'hidden', fontFamily: 'inherit',
  }}
    onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--primary)'; e.currentTarget.style.boxShadow = 'var(--shadow-md)'; }}
    onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.boxShadow = 'none'; }}
  >
    {/* Header row */}
    <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
          <div style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--text)', letterSpacing: '-0.01em' }}>{c.name}</div>
          <TierBadge tier={c.tier} />
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>{c.industry}</div>
      </div>
      <HealthPill health={c.health} />
    </div>

    {/* Stats row */}
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)' }}>
      {[
        { label: 'MRR',      value: c.mrr ? `£${c.mrr.toLocaleString()}` : '—', sub: c.mrrNote || 'monthly' },
        { label: 'Services', value: c.services.length,                          sub: 'active' },
        { label: 'Queue',    value: c.thisWeek.length,                          sub: 'this week' },
      ].map((s, i) => (
        <div key={s.label} style={{
          padding: '10px 12px',
          borderLeft: i === 0 ? 'none' : '1px solid var(--border)',
        }}>
          <div style={{ fontSize: 9, color: 'var(--text-faint)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.label}</div>
          <div style={{ fontSize: 14, fontWeight: 700, fontVariantNumeric: 'tabular-nums', marginTop: 2, color: 'var(--text)' }}>{s.value}</div>
          <div style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 1 }}>{s.sub}</div>
        </div>
      ))}
    </div>

    {/* This-week list */}
    <div style={{ padding: '10px 16px', flex: 1, minHeight: 64 }}>
      {c.thisWeek.length === 0 ? (
        <div style={{ fontSize: 11.5, color: 'var(--text-faint)', fontStyle: 'italic' }}>Nothing on the queue this week.</div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {c.thisWeek.slice(0, 2).map((t, i) => {
            const k = KIND_ICONS[t.kind] || KIND_ICONS.report;
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11.5 }}>
                <span style={{ color: k.color, display: 'inline-flex', flexShrink: 0 }}>{k.icon}</span>
                <span style={{ color: 'var(--text)', flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.label}</span>
                <span style={{ color: 'var(--text-faint)', fontSize: 10.5, flexShrink: 0 }}>{t.when}</span>
              </div>
            );
          })}
          {c.thisWeek.length > 2 && (
            <div style={{ fontSize: 10.5, color: 'var(--text-faint)' }}>+{c.thisWeek.length - 2} more</div>
          )}
        </div>
      )}
    </div>

    {/* Footer */}
    <div style={{
      padding: '10px 16px', borderTop: '1px solid var(--border)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: 'var(--surface-2)',
    }}>
      <div style={{ fontSize: 10.5, color: 'var(--text-muted)' }}>
        {c.contact} · last contact {c.lastContact}
      </div>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: 'var(--primary)', fontSize: 11.5, fontWeight: 600 }}>
        Open
        <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
      </div>
    </div>
  </button>
);

// =============================================================
// This Week — flat action queue across the portfolio.
// =============================================================
const AmThisWeekScreen = ({ onOpenClient }) => {
  const all = AM_CLIENTS.flatMap(c => c.thisWeek.map(t => ({ ...t, client: c })));
  const grouped = {
    flag:    all.filter(t => t.kind === 'flag'),
    ticket:  all.filter(t => t.kind === 'ticket'),
    report:  all.filter(t => t.kind === 'report'),
    renewal: all.filter(t => t.kind === 'renewal'),
    opp:     all.filter(t => t.kind === 'opp'),
  };
  const order = ['flag', 'ticket', 'renewal', 'report', 'opp'];

  return (
    <div>
      <AmTopbar
        title="This week"
        subtitle={`${all.length} items across ${AM_CLIENTS.filter(c => c.thisWeek.length).length} clients`}
      />
      <div style={{ padding: 24, maxWidth: 1100, width: '100%', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {order.map(kind => {
          const items = grouped[kind];
          if (!items.length) return null;
          const k = KIND_ICONS[kind];
          return (
            <Card key={kind} padding={0}>
              <div style={{
                padding: '12px 16px', borderBottom: '1px solid var(--border)',
                display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <span style={{
                  width: 24, height: 24, borderRadius: 6, flexShrink: 0,
                  background: 'color-mix(in oklab, ' + k.color + ' 12%, transparent)',
                  color: k.color, display: 'grid', placeItems: 'center',
                }}>{k.icon}</span>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{k.label}s</div>
                <div style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--text-muted)' }}>{items.length} item{items.length === 1 ? '' : 's'}</div>
              </div>
              <div>
                {items.map((t, i) => (
                  <button key={i} onClick={() => onOpenClient(t.client.id)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 12,
                      width: '100%', padding: '11px 16px',
                      background: 'transparent', border: 'none',
                      borderTop: i === 0 ? 'none' : '1px solid var(--border)',
                      cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-2)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >
                    <HealthPill health={t.client.health} />
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{t.label}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 1 }}>
                        {t.client.name} · {t.client.contact}
                      </div>
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--text-muted)', flexShrink: 0 }}>{t.when}</div>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--text-faint)', flexShrink: 0 }}><path d="M5 12h14M13 6l6 6-6 6"/></svg>
                  </button>
                ))}
              </div>
            </Card>
          );
        })}
        {all.length === 0 && (
          <div style={{
            padding: '60px 20px', textAlign: 'center',
            color: 'var(--text-muted)', fontSize: 13,
            background: 'var(--surface)', border: '1px dashed var(--border)', borderRadius: 'var(--radius)',
          }}>
            Inbox zero. Nothing on the queue this week.
          </div>
        )}
      </div>
    </div>
  );
};

// =============================================================
// Placeholder screens for nav items we haven't fully built.
// =============================================================
const AmStubScreen = ({ title, subtitle, icon }) => (
  <div>
    <AmTopbar title={title} subtitle={subtitle} />
    <div style={{ padding: 24, maxWidth: 800, margin: '0 auto' }}>
      <div style={{
        padding: '60px 20px', textAlign: 'center',
        background: 'var(--surface)', border: '1px dashed var(--border)', borderRadius: 'var(--radius)',
      }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12, margin: '0 auto 14px',
          background: 'var(--surface-2)', display: 'grid', placeItems: 'center',
          color: 'var(--text-faint)',
        }}>{icon}</div>
        <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{title} — coming soon</div>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4, maxWidth: 380, marginLeft: 'auto', marginRight: 'auto' }}>
          We'll wire this up next. For now, work the portfolio and this-week queue.
        </div>
      </div>
    </div>
  </div>
);

// =============================================================
// AM ribbon — slim bar shown above the client topbar when an AM
// has drilled into a specific client. Communicates "you are
// internal staff viewing this account" + offers fast switching.
// =============================================================
const AmRibbon = ({ clientId, onBack, onSwitchClient, onOpenSetup, setupOpen }) => {
  const c = AM_CLIENTS.find(x => x.id === clientId);
  const [open, setOpen] = useState(false);
  if (!c) return null;
  return (
    <div style={{
      background: '#0f172a',
      color: '#fff',
      padding: '8px 16px',
      display: 'flex', alignItems: 'center', gap: 12,
      fontSize: 12,
      borderBottom: '1px solid rgba(255,255,255,0.10)',
      position: 'sticky', top: 0, zIndex: 30,
    }}>
      <button onClick={onBack} style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '4px 10px', borderRadius: 6,
        background: 'rgba(255,255,255,0.08)', color: '#fff',
        border: 'none', fontSize: 11.5, fontWeight: 500, fontFamily: 'inherit',
        cursor: 'pointer',
      }}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M11 18l-6-6 6-6"/></svg>
        Back to portfolio
      </button>

      <span style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '2px 8px', borderRadius: 99,
        background: 'rgba(255,255,255,0.10)',
        fontSize: 9.5, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
      }}>
        <span style={{ width: 5, height: 5, borderRadius: '50%', background: '#22c55e' }}/>
        AM view
      </span>

      <span style={{ color: 'rgba(255,255,255,0.55)', fontSize: 11.5 }}>Viewing as {AM_USER.firstName}:</span>

      {/* Client switcher */}
      <div style={{ position: 'relative' }}>
        <button onClick={() => setOpen(v => !v)} style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 10px', borderRadius: 6,
          background: 'rgba(255,255,255,0.08)', color: '#fff',
          border: '1px solid rgba(255,255,255,0.10)',
          fontSize: 12, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: '50%',
            background: c.health === 'good' ? '#22c55e' : c.health === 'watch' ? '#f59e0b' : '#ef4444',
          }}/>
          {c.name}
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6 6 6-6"/></svg>
        </button>
        {open && (
          <>
            <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 31 }}/>
            <div style={{
              position: 'absolute', top: 'calc(100% + 6px)', left: 0,
              minWidth: 260, maxHeight: 360, overflowY: 'auto',
              background: '#0f172a',
              border: '1px solid rgba(255,255,255,0.12)',
              borderRadius: 8, padding: 4,
              boxShadow: '0 12px 32px rgba(0,0,0,0.4)',
              zIndex: 32,
            }}>
              {AM_CLIENTS.map(other => (
                <button key={other.id}
                  onClick={() => { setOpen(false); onSwitchClient(other.id); }}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 8,
                    width: '100%', padding: '7px 10px',
                    background: other.id === clientId ? 'rgba(255,255,255,0.08)' : 'transparent',
                    color: '#fff', border: 'none', borderRadius: 6,
                    fontSize: 12, fontFamily: 'inherit', textAlign: 'left', cursor: 'pointer',
                  }}
                  onMouseEnter={e => { if (other.id !== clientId) e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; }}
                  onMouseLeave={e => { if (other.id !== clientId) e.currentTarget.style.background = 'transparent'; }}
                >
                  <span style={{
                    width: 6, height: 6, borderRadius: '50%', flexShrink: 0,
                    background: other.health === 'good' ? '#22c55e' : other.health === 'watch' ? '#f59e0b' : '#ef4444',
                  }}/>
                  <span style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{other.name}</span>
                  <span style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', flexShrink: 0 }}>{other.tier}</span>
                </button>
              ))}
            </div>
          </>
        )}
      </div>

      <div style={{ marginLeft: 'auto', fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>
        {c.thisWeek.length > 0 && <>{c.thisWeek.length} item{c.thisWeek.length === 1 ? '' : 's'} in this week's queue · </>}
        {c.contact}
      </div>

      {/* Client setup gear — full AM control panel */}
      <button
        onClick={onOpenSetup}
        title={setupOpen ? 'Close client setup' : 'Open client setup (AM only)'}
        aria-label="Client setup"
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '4px 10px', borderRadius: 6,
          background: setupOpen ? '#fff' : 'rgba(255,255,255,0.08)',
          color: setupOpen ? '#0f172a' : '#fff',
          border: '1px solid ' + (setupOpen ? '#fff' : 'rgba(255,255,255,0.10)'),
          fontSize: 11.5, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
        }}
      >
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.6 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
        {setupOpen ? 'Close setup' : 'Setup'}
      </button>
    </div>
  );
};

// =============================================================
// Top-level AM portal shell — sidebar + selected screen.
// =============================================================
const AmPortal = ({ onSignOut, onOpenClient, initialActive = 'portfolio' }) => {
  const [active, setActive] = useState(initialActive);

  let screen;
  if (active === 'portfolio')        screen = <AmPortfolioScreen onOpenClient={onOpenClient} />;
  else if (active === 'thisweek')    screen = <AmThisWeekScreen onOpenClient={onOpenClient} />;
  else if (active === 'reports')     screen = <AmStubScreen title="Reports queue" subtitle="All bespoke reports across the book — drafts, in progress and shipped" icon={<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>} />;
  else if (active === 'performance') screen = <AmStubScreen title="Performance flags" subtitle="Targets and channel anomalies surfaced from ClickyAI™ across the portfolio" icon={<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M4 22V4M4 4h12l-2 4 2 4H4"/></svg>} />;
  else if (active === 'team')        screen = <AmStubScreen title="Internal team" subtitle="Capacity, focus areas and who's on which account this week" icon={<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="9" cy="8" r="3.5"/><circle cx="17" cy="9" r="2.5"/><path d="M2.5 20a6.5 6.5 0 0 1 13 0"/><path d="M15 20a5 5 0 0 1 6.5-4.8"/></svg>} />;
  else if (active === 'profile')     screen = <AmProfileScreen />;
  else                                screen = <AmPortfolioScreen onOpenClient={onOpenClient} />;

  return (
    <div style={{ display: 'flex', minHeight: '100vh' }}>
      <AmSidebar
        active={active}
        setActive={setActive}
        onSignOut={onSignOut}
        onOpenClient={onOpenClient}
        currentClientId={null}
      />
      <main style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        {screen}
      </main>
    </div>
  );
};

// =============================================================
// AM rail — slim 64px dark rail shown on the far left when an
// AM has drilled into a client. Keeps AM workspace controls
// (portfolio, this-week, sign out) one click away without
// taking sidebar real-estate from the client portal underneath.
// =============================================================
const AmRail = ({ onBackToPortfolio, onGoThisWeek, onSignOut, currentClientId }) => {
  const queueCount = AM_CLIENTS.reduce((n, c) => n + c.thisWeek.length, 0);
  const RailBtn = ({ label, badge, onClick, children }) => (
    <button onClick={onClick} title={label} aria-label={label}
      style={{
        position: 'relative',
        width: 44, height: 44, borderRadius: 8,
        background: 'transparent',
        color: 'rgba(255,255,255,0.7)',
        border: '1px solid transparent',
        cursor: 'pointer',
        display: 'grid', placeItems: 'center',
        transition: 'background 120ms ease, color 120ms ease, border-color 120ms ease',
      }}
      onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.06)'; e.currentTarget.style.color = '#fff'; }}
      onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'rgba(255,255,255,0.7)'; }}
    >
      {children}
      {badge != null && badge > 0 && (
        <span style={{
          position: 'absolute', top: 4, right: 4,
          minWidth: 16, height: 16, padding: '0 4px',
          borderRadius: 99, background: '#ef4444', color: '#fff',
          fontSize: 9, fontWeight: 700, letterSpacing: '-0.01em',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          border: '2px solid #0f172a',
        }}>{badge}</span>
      )}
    </button>
  );

  return (
    <aside style={{
      width: 64, flexShrink: 0,
      background: '#0f172a',
      color: '#fff',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      padding: '12px 0',
      borderRight: '1px solid rgba(255,255,255,0.08)',
      gap: 6,
      position: 'sticky', top: 0,
      height: '100vh',
    }}>
      {/* Brand mark */}
      <div title="Clicky · Account Manager" style={{
        width: 40, height: 40, borderRadius: 8,
        background: 'rgba(255,255,255,0.06)',
        display: 'grid', placeItems: 'center',
        marginBottom: 4,
      }}>
        <img src="assets/clicky-logo-vert-white.png" alt="Clicky" style={{ height: 24, width: 'auto', display: 'block' }} />
      </div>

      <div style={{ height: 1, width: 32, background: 'rgba(255,255,255,0.10)', margin: '4px 0 6px' }}/>

      {/* AM avatar */}
      <div title={`${AM_USER.name} · ${AM_USER.role}`} style={{ marginBottom: 4 }}>
        <PersonAvatar name={AM_USER.name} size={36} hue={AM_USER.hue} src={AM_USER.avatar} />
      </div>

      {/* Portfolio */}
      <RailBtn label="Back to portfolio" onClick={onBackToPortfolio}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg>
      </RailBtn>

      {/* This week */}
      <RailBtn label="This week" badge={queueCount} onClick={onGoThisWeek}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M8 3v4M16 3v4M3 11h18"/></svg>
      </RailBtn>

      <div style={{ flex: 1 }} />

      {/* Sign out */}
      <RailBtn label="Sign out" onClick={onSignOut}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="M16 17l5-5-5-5M21 12H9"/></svg>
      </RailBtn>
    </aside>
  );
};

// =============================================================
// AM profile screen — manage the account manager's own identity,
// contact info, calendar, working hours, and notification prefs.
// Saves to localStorage and mutates the live AM_USER object so
// every other surface (rail, ribbon, sidebar card) updates.
// =============================================================
const AmProfileScreen = () => {
  const [p, setP] = useState(() => loadAmProfile());
  const [saved, setSaved] = useState(false);

  const update = (patch) => {
    const next = { ...p, ...patch };
    setP(next);
    saveAmProfile(next);
    Object.assign(AM_USER, next); // mutate live object so other surfaces re-read
    setSaved(true);
    clearTimeout(window.__amProfileSavedTimer);
    window.__amProfileSavedTimer = setTimeout(() => setSaved(false), 1500);
  };
  const updateNotif = (key, value) => update({ notifications: { ...p.notifications, [key]: value } });

  // Avatar preview — accept an uploaded file and turn it into a data URL.
  const onAvatarFile = (file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => update({ avatar: e.target.result });
    reader.readAsDataURL(file);
  };

  return (
    <div>
      <AmTopbar
        title="My profile"
        subtitle="How you appear to clients in the portal, on reports and in calendar invites."
        actions={
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '4px 10px', borderRadius: 99,
            background: saved ? 'color-mix(in oklab, #16a34a 12%, transparent)' : 'var(--surface-2)',
            color: saved ? '#16a34a' : 'var(--text-faint)',
            fontSize: 11, fontWeight: 600,
            transition: 'background 200ms ease, color 200ms ease',
          }}>
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>
            {saved ? 'Saved' : 'Auto-saves'}
          </span>
        }
      />

      <div style={{ padding: 24, maxWidth: 880, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 18 }}>
        {/* Identity card */}
        <Card>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 18 }}>
            <div style={{ position: 'relative' }}>
              <PersonAvatar name={p.name} size={84} hue={p.hue} src={p.avatar} />
              <label style={{
                position: 'absolute', bottom: -2, right: -2,
                width: 28, height: 28, borderRadius: '50%',
                background: '#0f172a', color: '#fff',
                display: 'grid', placeItems: 'center',
                cursor: 'pointer', border: '2px solid var(--surface)',
              }} title="Upload new photo">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
                <input type="file" accept="image/*" style={{ display: 'none' }}
                  onChange={e => onAvatarFile(e.target.files?.[0])} />
              </label>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 18, fontWeight: 700 }}>{p.name}</div>
              <div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 2 }}>{p.role}</div>
              <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 4, fontFamily: 'JetBrains Mono' }}>{p.email}</div>
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Full name">
              <input value={p.name}
                onChange={e => {
                  const name = e.target.value;
                  const firstName = name.split(' ')[0] || '';
                  update({ name, firstName });
                }}
                style={input()} />
            </Field>
            <Field label="Role / title">
              <input value={p.role} onChange={e => update({ role: e.target.value })} style={input()} />
            </Field>
            <Field label="Email">
              <input type="email" value={p.email} onChange={e => update({ email: e.target.value })} style={input()} />
            </Field>
            <Field label="Phone">
              <input value={p.phone} onChange={e => update({ phone: e.target.value })} style={input()} />
            </Field>
            <Field label="Calendar booking link">
              <input value={p.calendarUrl} onChange={e => update({ calendarUrl: e.target.value })}
                placeholder="https://cal.com/you/15min" style={input()} />
            </Field>
            <Field label="Timezone">
              <select value={p.timezone} onChange={e => update({ timezone: e.target.value })} style={input()}>
                {['Europe/London','Europe/Dublin','Europe/Paris','America/New_York','America/Los_Angeles','Asia/Singapore','Australia/Sydney'].map(z => <option key={z}>{z}</option>)}
              </select>
            </Field>
            <Field label="Working hours">
              <input value={p.workingHours} onChange={e => update({ workingHours: e.target.value })}
                placeholder="9:00 – 17:30" style={input()} />
            </Field>
          </div>

          <div style={{ marginTop: 12 }}>
            <Field label="Bio (shown on the client's My Clicky Team page)">
              <textarea value={p.bio} onChange={e => update({ bio: e.target.value })}
                placeholder="Short bio — what you focus on, who you've worked with."
                style={{ ...input(), minHeight: 70, resize: 'vertical', fontFamily: 'inherit' }} />
            </Field>
          </div>
        </Card>

        {/* Notifications */}
        <Card>
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Notifications</div>
            <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>
              When we email you. Everything goes to {p.email}.
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { id: 'clientFlags',       label: 'Client critical alerts',    desc: 'Email me when one of my clients flips to critical.' },
              { id: 'contractApprovals', label: 'Contract approval needed',  desc: 'Email me when a contract needs my sign-off.' },
              { id: 'invoiceOverdue',    label: 'Invoice overdue',           desc: 'Email me when one of my clients has an invoice 7+ days overdue.' },
              { id: 'aiSuggestionDaily', label: 'Daily AI suggestion digest', desc: 'Morning summary of new ClickyAI suggestions across my book.' },
              { id: 'weeklyDigest',      label: 'Weekly portfolio digest',   desc: 'Monday roundup — health, MRR moves, this-week\'s queue.' },
            ].map(n => (
              <label key={n.id} style={{
                display: 'flex', alignItems: 'flex-start', gap: 10,
                padding: '10px 12px', borderRadius: 6,
                border: '1px solid var(--border)', cursor: 'pointer',
                background: p.notifications[n.id] ? 'color-mix(in oklab, var(--primary) 4%, var(--surface))' : 'var(--surface)',
                transition: 'background 120ms ease',
              }}>
                <input type="checkbox" checked={!!p.notifications[n.id]}
                  onChange={e => updateNotif(n.id, e.target.checked)}
                  style={{ marginTop: 2 }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{n.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{n.desc}</div>
                </div>
              </label>
            ))}
          </div>
        </Card>

        {/* Qualifications & certifications */}
        <QualificationsCard amName={p.name} />

        {/* Account / security (mock) */}
        <Card>
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Account & security</div>
            <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>
              Mock controls for the prototype.
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <SettingRow label="Password" value="Last changed 3 months ago" cta="Change password" />
            <SettingRow label="Two-factor authentication" value="Enabled · Authenticator app" cta="Manage 2FA" />
            <SettingRow label="Active sessions" value="2 sessions · macOS · Chrome" cta="Sign out other sessions" tone="negative" />
          </div>
        </Card>
      </div>
    </div>
  );
};

// =============================================================
// Qualifications card — lives inside AmProfileScreen. Lists the
// AM's certifications and lets them connect Google / Meta / LinkedIn
// (mock — simulates an API pull) or add one manually. Edits flow
// straight to the client-facing TeamProfilePanel via the shared
// localStorage store.
// =============================================================
const QualificationsCard = ({ amName }) => {
  const [list, setList] = useState(() => window.getTeamQualifications(amName) || []);
  const [editing, setEditing] = useState(null);
  const [connecting, setConnecting] = useState(null); // 'google' | 'meta' | 'linkedin' | null

  const persist = (next) => {
    setList(next);
    window.setTeamQualifications(amName, next);
  };

  const upsert = (q) => {
    const idx = list.findIndex(x => x.id === q.id);
    persist(idx >= 0 ? list.map(x => x.id === q.id ? q : x) : [...list, q]);
    setEditing(null);
  };
  const remove = (id) => {
    if (confirm('Remove this qualification?')) persist(list.filter(q => q.id !== id));
  };
  const startManualAdd = () => setEditing({
    id: 'q-' + Date.now(),
    name: '', issuer: '', issuerSlug: 'manual',
    issued: '', verified: false, source: 'manual',
    isNew: true,
  });

  // Mock "Connect" flow — pretends to fetch certs from the platform's
  // certification API. Surfaces a 1-second "connecting" spinner, then
  // appends 1-3 new verified quals tagged with the appropriate source.
  const connect = (provider) => {
    setConnecting(provider);
    const sample = ({
      google: [
        { name: 'Google Ads Video Certification',     issued: 'May 2025' },
        { name: 'Google Ads Apps Certification',      issued: 'May 2025' },
        { name: 'Google Ads Measurement',             issued: 'Apr 2025' },
      ],
      meta: [
        { name: 'Meta Certified Media Planning Professional', issued: 'Apr 2025' },
        { name: 'Meta Certified Creative Strategy Professional', issued: 'Mar 2025' },
      ],
      linkedin: [
        { name: 'LinkedIn Marketing Solutions Certified Marketing Insider', issued: 'Feb 2025' },
      ],
    })[provider] || [];
    setTimeout(() => {
      const issuer = provider === 'google' ? 'Google' : provider === 'meta' ? 'Meta' : 'LinkedIn';
      const additions = sample
        .filter(s => !list.some(q => q.name === s.name))
        .map((s, i) => ({
          id: `q-${provider}-${Date.now()}-${i}`,
          name: s.name, issuer, issuerSlug: provider,
          issued: s.issued, verified: true, source: `${provider}-api`,
        }));
      persist([...list, ...additions]);
      setConnecting(null);
    }, 950);
  };

  const verifiedCount = list.filter(q => q.verified).length;

  return (
    <Card>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12, gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600 }}>Qualifications & certifications</div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 2 }}>
            {list.length} listed{verifiedCount > 0 && <> · <span style={{ color: 'var(--positive)', fontWeight: 600 }}>{verifiedCount} verified</span></>}
            <> · shown on your profile in the client's "Your Team" page.</>
          </div>
        </div>
        <button onClick={startManualAdd} style={{
          padding: '7px 12px', borderRadius: 6,
          background: '#0f172a', color: '#fff', border: '1px solid #0f172a',
          fontSize: 12, fontFamily: 'inherit', fontWeight: 500, cursor: 'pointer', whiteSpace: 'nowrap',
        }}>+ Add manually</button>
      </div>

      {/* Connect buttons — mock platform API pulls */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 14 }}>
        {[
          { id: 'google',   label: 'Connect Google',   sub: 'Pull from Skillshop',          hue: '#4285f4' },
          { id: 'meta',     label: 'Connect Meta',     sub: 'Pull from Meta Blueprint',     hue: '#0866ff' },
          { id: 'linkedin', label: 'Connect LinkedIn', sub: 'Pull from LinkedIn Marketing', hue: '#0a66c2' },
        ].map(p => {
          const isConnecting = connecting === p.id;
          return (
            <button key={p.id}
              disabled={!!connecting}
              onClick={() => connect(p.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 12px', borderRadius: 8,
                background: 'var(--surface)',
                border: '1px solid color-mix(in oklab, ' + p.hue + ' 28%, var(--border))',
                cursor: connecting ? 'wait' : 'pointer', fontFamily: 'inherit', textAlign: 'left',
                opacity: connecting && !isConnecting ? 0.55 : 1,
                transition: 'background 120ms ease, transform 80ms ease',
              }}
              onMouseEnter={e => { if (!connecting) e.currentTarget.style.background = 'color-mix(in oklab, ' + p.hue + ' 5%, var(--surface))'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'var(--surface)'; }}
            >
              <window.IssuerMark slug={p.id} size={28} />
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text)' }}>
                  {isConnecting ? 'Connecting…' : p.label}
                </div>
                <div style={{ fontSize: 10.5, color: 'var(--text-muted)', marginTop: 2 }}>
                  {isConnecting ? 'Pulling certifications' : p.sub}
                </div>
              </div>
              {isConnecting ? (
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={p.hue} strokeWidth="2" strokeLinecap="round" style={{
                  flexShrink: 0,
                  animation: 'searchSpin 800ms linear infinite',
                }}>
                  <path d="M21 12a9 9 0 1 1-9-9" />
                </svg>
              ) : (
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ color: p.hue, flexShrink: 0 }}><path d="M5 12h14M13 6l6 6-6 6"/></svg>
              )}
            </button>
          );
        })}
      </div>

      {/* List */}
      <window.QualificationsList
        qualifications={list}
        onEdit={(q) => setEditing(q)}
        onRemove={remove}
      />

      {editing && (
        <QualificationEditModal
          qualification={editing}
          onClose={() => setEditing(null)}
          onSave={upsert}
        />
      )}
    </Card>
  );
};

const QualificationEditModal = ({ qualification, onClose, onSave }) => {
  const [q, setQ] = useState(qualification);
  const update = (patch) => setQ(prev => ({ ...prev, ...patch }));
  const inp = {
    padding: '7px 10px', fontSize: 12.5,
    background: 'var(--surface)', color: 'var(--text)',
    border: '1px solid var(--border)', borderRadius: 6,
    fontFamily: 'inherit', outline: 'none',
  };
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 220,
      background: 'rgba(15,23,42,0.45)', backdropFilter: 'blur(4px)',
      display: 'grid', placeItems: 'center', padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 480,
        background: 'var(--surface)', border: '1px solid var(--border)',
        borderRadius: 'var(--radius)', boxShadow: '0 24px 60px rgba(15,23,42,0.30)',
      }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border)' }}>
          <div style={{ fontSize: 9.5, color: 'var(--text-faint)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.10em' }}>Qualification</div>
          <div style={{ fontSize: 14, fontWeight: 700, marginTop: 2 }}>{q.isNew ? 'Add a qualification' : 'Edit qualification'}</div>
        </div>
        <div style={{ padding: 20, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Certification name</span>
            <input value={q.name} onChange={e => update({ name: e.target.value })} placeholder="e.g. Google Ads Search Certification" style={inp} autoFocus />
          </label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Issuer</span>
              <input value={q.issuer} onChange={e => update({ issuer: e.target.value })} placeholder="Google, Meta, HubSpot…" style={inp} />
            </label>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Logo</span>
              <select value={q.issuerSlug} onChange={e => update({ issuerSlug: e.target.value })} style={inp}>
                <option value="manual">— Generic —</option>
                <option value="google">Google</option>
                <option value="meta">Meta</option>
                <option value="microsoft">Microsoft</option>
                <option value="linkedin">LinkedIn</option>
                <option value="tiktok">TikTok</option>
                <option value="hubspot">HubSpot</option>
              </select>
            </label>
          </div>
          <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>Issued</span>
            <input value={q.issued} onChange={e => update({ issued: e.target.value })} placeholder="e.g. Apr 2025" style={inp} />
          </label>
        </div>
        <div style={{ padding: '12px 20px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button onClick={onClose} style={{
            padding: '7px 14px', borderRadius: 6, background: 'var(--surface-2)', color: 'var(--text)',
            border: '1px solid var(--border)', fontSize: 12, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
          }}>Cancel</button>
          <button
            onClick={() => onSave(q)}
            disabled={!q.name.trim() || !q.issuer.trim()}
            style={{
              padding: '7px 14px', borderRadius: 6,
              background: q.name.trim() && q.issuer.trim() ? '#0f172a' : 'var(--surface-2)',
              color: q.name.trim() && q.issuer.trim() ? '#fff' : 'var(--text-faint)',
              border: '1px solid ' + (q.name.trim() && q.issuer.trim() ? '#0f172a' : 'var(--border)'),
              fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
              cursor: q.name.trim() && q.issuer.trim() ? 'pointer' : 'not-allowed',
            }}
          >{q.isNew ? 'Add qualification' : 'Save'}</button>
        </div>
      </div>
    </div>
  );
};

const SettingRow = ({ label, value, cta, tone }) => (
  <div style={{
    display: 'flex', alignItems: 'center', gap: 12,
    padding: '10px 12px', borderRadius: 6,
    background: 'var(--surface-2)', border: '1px solid var(--border)',
  }}>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 12.5, fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{value}</div>
    </div>
    <button style={{
      padding: '6px 12px', borderRadius: 6,
      background: 'var(--surface)', color: tone === 'negative' ? 'var(--negative)' : 'var(--text)',
      border: '1px solid ' + (tone === 'negative' ? 'color-mix(in oklab, var(--negative) 30%, var(--border))' : 'var(--border)'),
      fontSize: 11.5, fontWeight: 500, fontFamily: 'inherit', cursor: 'pointer',
    }}>{cta}</button>
  </div>
);

// Tiny re-implementations of Field/input from am-setup.jsx so we don't
// depend on load order of script tags.
const Field = ({ label, children }) => (
  <label style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
    <span style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</span>
    {children}
  </label>
);
const input = () => ({
  padding: '7px 10px', fontSize: 12.5,
  background: 'var(--surface)', color: 'var(--text)',
  border: '1px solid var(--border)', borderRadius: 6,
  fontFamily: 'inherit', outline: 'none',
});

Object.assign(window, {
  LoginScreen, AmPortal, AmRibbon, AmRail, AmProfileScreen, HealthPill, TierBadge,
  AM_USER, loadAmProfile, saveAmProfile,
});
