// ScrollJob v2 — Admin (5 screens)
// Same teal palette as the rest. Internal-only — Cloudflare Access locked.
// Sidebar lists every app + Audit log. Compact dense tables, batch action bar.

// Tiny form helpers — defined locally to avoid cross-script eval ordering issues
// with Babel external scripts.
function AdmRow({ children }) {
  return <div style={{ display: 'grid', gridTemplateColumns: `repeat(${React.Children.count(children)}, 1fr)`, gap: 14, marginBottom: 14 }}>{children}</div>;
}
function AdmFieldCol({ label, children, full }) {
  return (
    <div style={{ gridColumn: full ? '1 / -1' : 'auto', marginBottom: 12 }}>
      <label style={{ display: 'block', fontSize: 12, color: V2.muted, fontWeight: 600, marginBottom: 6 }}>{label}</label>
      {children}
    </div>
  );
}
function AdmFieldInput({ value }) {
  return (
    <input defaultValue={value} style={{
      width: '100%', padding: '8px 11px', border: `1px solid ${V2.line}`,
      borderRadius: 7, fontSize: 13, outline: 'none', fontFamily: V2.font,
      color: V2.ink, background: '#fff', boxSizing: 'border-box',
    }} />
  );
}

// ─── Top strip + sidebar ────────────────────────────────────────────────
function AdminTop() {
  return (
    <header style={{
      background: '#fff', borderBottom: `1px solid ${V2.line}`,
      padding: '12px 24px', display: 'flex', alignItems: 'center', gap: 16,
      position: 'sticky', top: 0, zIndex: 50,
    }}>
      <V2Logo size={28} />
      <span style={{
        padding: '3px 9px', background: V2.primary, color: '#fff',
        borderRadius: 6, fontSize: 11, fontWeight: 800, letterSpacing: '0.08em',
      }}>ADMIN</span>
      <nav style={{ fontSize: 13, color: V2.muted, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <span style={{ color: V2.faint, fontFamily: V2.fontMono }}>/admin</span>
      </nav>
      <span style={{ flex: 1 }} />
      <div style={{ position: 'relative' }}>
        <Icon name="search" size={15} color={V2.muted}
              style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)' }} />
        <input placeholder="Search anything · ⌘K" style={{
          width: 320, padding: '8px 12px 8px 34px',
          background: V2.bgAlt, border: `1px solid ${V2.line}`, borderRadius: 8,
          fontSize: 13, color: V2.ink, fontFamily: V2.font, outline: 'none', boxSizing: 'border-box',
        }} />
      </div>
      <V2RegionPill />
      <V2Button variant="ghost" size="sm" icon="bell">3</V2Button>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{
          width: 30, height: 30, borderRadius: '50%',
          background: `linear-gradient(135deg, ${V2.primary}, ${V2.primaryDark})`,
          color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 12, fontWeight: 700,
        }}>OD</span>
        <span style={{ fontSize: 13, fontWeight: 600, color: V2.ink }}>Olha D.</span>
      </div>
    </header>
  );
}

function AdminSide({ active }) {
  const apps = [
    ['dashboard',   'Dashboard',         'home'],
    ['mod',         'Moderation queue',  'shield', 18],
    'divider',
    ['jobs',        'Jobs',              'briefcase', 12480],
    ['companies',   'Companies',         'building',   782],
    ['users',       'Users',             'user',     142_840],
    ['blog',        'Blog',              'document'],
    ['analytics',   'Analytics',         'trending'],
    ['audit',       'Audit log',         'eye'],
    'divider',
    ['settings',    'Settings',          'sliders'],
  ];
  return (
    <aside style={{
      width: 240, flexShrink: 0, background: V2.bgAlt, padding: '16px 12px',
      borderRight: `1px solid ${V2.line}`, height: '100%',
    }}>
      <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {apps.map((it, i) => {
          if (it === 'divider') {
            return <div key={i} style={{ height: 1, background: V2.line, margin: '8px 0' }} />;
          }
          const [k, label, icon, count] = it;
          const on = active === k;
          return (
            <a key={k} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '8px 12px', borderRadius: 8,
              background: on ? '#fff' : 'transparent',
              color: on ? V2.ink : V2.text,
              fontSize: 13.5, fontWeight: on ? 600 : 500,
              textDecoration: 'none', cursor: 'pointer',
              boxShadow: on ? V2.shadowSm : 'none',
            }}>
              <Icon name={icon} size={16} color={on ? V2.primary : V2.muted} />
              <span style={{ flex: 1 }}>{label}</span>
              {count != null && (
                <span style={{ fontSize: 11, color: V2.faint, fontVariantNumeric: 'tabular-nums' }}>
                  {count > 9999 ? `${(count / 1000).toFixed(0)}k` : count.toLocaleString()}
                </span>
              )}
            </a>
          );
        })}
      </nav>
    </aside>
  );
}

function AdminFrame({ active, breadcrumbs, children }) {
  return (
    <div style={{ background: V2.bg, fontFamily: V2.font, color: V2.ink, minHeight: '100%' }}>
      <AdminTop />
      <div style={{ display: 'flex', minHeight: 'calc(100% - 53px)' }}>
        <AdminSide active={active} />
        <div style={{ flex: 1, minWidth: 0 }}>
          {breadcrumbs && (
            <nav style={{
              padding: '14px 28px', borderBottom: `1px solid ${V2.line}`, background: '#fff',
              fontSize: 13, color: V2.muted,
            }}>
              {breadcrumbs.map((b, i, arr) => (
                <span key={i}>
                  {i < arr.length - 1
                    ? <a style={{ color: V2.primary, textDecoration: 'none', fontWeight: 500 }}>{b}</a>
                    : <span style={{ color: V2.ink, fontWeight: 600 }}>{b}</span>}
                  {i < arr.length - 1 && <span style={{ margin: '0 8px', color: V2.faint }}>›</span>}
                </span>
              ))}
            </nav>
          )}
          <main style={{ padding: 28 }}>{children}</main>
        </div>
      </div>
    </div>
  );
}

// ─── 1) ADMIN SIGN IN ────────────────────────────────────────────────────
function V2AdminLoginScreen() {
  return (
    <div style={{ background: V2.bg, fontFamily: V2.font, color: V2.ink, minHeight: '100%' }}>
      <div style={{
        minHeight: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 40, position: 'relative',
      }}>
        <div aria-hidden style={{
          position: 'absolute', inset: 0,
          background: `radial-gradient(circle at 20% 20%, ${V2.primarySoft} 0, transparent 40%), radial-gradient(circle at 80% 60%, #E0F2FE 0, transparent 40%)`,
        }} />
        <div style={{
          background: '#fff', borderRadius: V2.rXl, boxShadow: V2.shadowXl,
          width: 440, padding: 36, position: 'relative',
          border: `1px solid ${V2.line}`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 28 }}>
            <V2Logo size={32} />
            <span style={{
              padding: '3px 9px', background: V2.primary, color: '#fff',
              borderRadius: 6, fontSize: 11, fontWeight: 800, letterSpacing: '0.08em',
            }}>ADMIN</span>
          </div>
          <h1 style={{
            margin: '0 0 6px', fontSize: 22, fontWeight: 700, color: V2.ink, letterSpacing: '-0.02em',
          }}>Sign in to admin</h1>
          <p style={{ margin: '0 0 24px', fontSize: 13.5, color: V2.muted }}>
            Staff and moderators only. All actions are logged.
          </p>
          <V2Button variant="primary" size="lg" full icon="shield">Continue with Okta SSO</V2Button>
          <AuthDivider />
          <AuthInput label="Staff email" type="email" defaultValue="ops-mod@scrolljob.org" />
          <AuthInput label="Password" type="password" defaultValue="············" />
          <V2Button variant="dark" size="lg" full>Sign in</V2Button>
          <p style={{
            textAlign: 'center', marginTop: 22, fontSize: 12, color: V2.muted, lineHeight: 1.55,
          }}>
            Admin is protected by Cloudflare Access. Unauthorised attempts are blocked at the edge.
          </p>
        </div>
      </div>
    </div>
  );
}

// ─── 2) ADMIN DASHBOARD ─────────────────────────────────────────────────
function V2AdminDashboardScreen() {
  return (
    <AdminFrame active="dashboard" breadcrumbs={['Admin', 'Dashboard']}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 22, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 style={{ margin: '0 0 4px', fontSize: 26, fontWeight: 700, color: V2.ink, letterSpacing: '-0.02em' }}>
            Good morning, Olha
          </h1>
          <p style={{ margin: 0, fontSize: 14, color: V2.muted }}>
            Tuesday 14 May 2026 · 09:42 · production · UK region
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <V2Button variant="secondary" size="sm" icon="eye">View public site</V2Button>
          <V2Button variant="primary" size="sm" icon="shield">Open moderation queue</V2Button>
        </div>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <V2Stat label="Awaiting moderation" value="18" delta="+4 since 09:00" deltaTone="success" icon="shield" />
        <V2Stat label="Live jobs"             value="12,480" delta="+182 in 24h" icon="briefcase" />
        <V2Stat label="New sign-ups today"    value="184" delta="+22 vs avg" icon="user" />
        <V2Stat label="Emails sent (24h)"     value="142k" sub="98.7% success" icon="mail" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18, marginBottom: 22 }}>
        {/* Moderation queue preview */}
        <div style={{
          background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rLg,
        }}>
          <header style={{
            padding: '14px 22px', borderBottom: `1px solid ${V2.line}`,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <h2 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: V2.ink }}>Moderation queue · pending</h2>
            <a style={{ color: V2.primary, fontSize: 13, fontWeight: 600, textDecoration: 'none' }}>Open queue (18) →</a>
          </header>
          <div style={{ padding: '4px 22px 14px' }}>
            {[
              { co: 'Stripe',    cat: 'Tech',        t: 'Senior Backend Engineer', age: '12 min', status: 'pending' },
              { co: 'NHS Trust', cat: 'Healthcare',  t: 'Senior Care Coordinator', age: '38 min', status: 'pending' },
              { co: 'DPD',       cat: 'Logistics',   t: 'Delivery Driver — Cat-B', age: '1 hr',   status: 'pending' },
              { co: 'Acme Co.',  cat: 'Retail',      t: 'Marketing Lead — earn $$$', age: '2 hr', status: 'flagged' },
              { co: 'Bunq',      cat: 'Office',      t: 'Customer Operations Lead', age: '3 hr',  status: 'pending' },
            ].map((j, i, arr) => (
              <div key={i} style={{
                padding: '11px 0', display: 'flex', alignItems: 'center', gap: 10,
                borderBottom: i < arr.length - 1 ? `1px solid ${V2.lineSoft}` : 'none',
              }}>
                <V2CompanyAvatar name={j.co} category={j.cat} size={32} radius={8} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: V2.ink }}>{j.t}</span>
                    <V2Badge tone={j.status === 'flagged' ? 'danger' : 'warn'} size="sm">{j.status}</V2Badge>
                  </div>
                  <div style={{ fontSize: 12, color: V2.muted, marginTop: 2 }}>{j.co} · {j.cat}</div>
                </div>
                <span style={{ fontSize: 12, color: V2.muted }}>{j.age}</span>
                <div style={{ display: 'inline-flex', gap: 5 }}>
                  <button style={modBtn(V2.success)}>Approve</button>
                  <button style={modBtn(V2.danger, true)}>Reject</button>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Audit log preview */}
        <div style={{
          background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rLg,
        }}>
          <header style={{
            padding: '14px 22px', borderBottom: `1px solid ${V2.line}`,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <h2 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: V2.ink }}>Recent admin actions</h2>
            <a style={{ color: V2.primary, fontSize: 13, fontWeight: 600, textDecoration: 'none' }}>Audit log →</a>
          </header>
          <div style={{ padding: '4px 22px 14px' }}>
            {[
              ['OD', 'Olha D.',    'approved', 'Job #14821 · Senior Python at Monzo', '2 min'],
              ['IG', 'Ihor G.',    'rejected', 'Job #14819 · Marketing Lead · spam',  '8 min'],
              ['OD', 'Olha D.',    'verified', 'Lavender House Care · employer',      '24 min'],
              ['MK', 'Mariia K.',  'created',  'EmailCampaign · UK weekly highlights','1 hr'],
              ['IG', 'Ihor G.',    'rotated',  'ExportAPIKey · partner-indeed-uk',    '3 hr'],
            ].map(([initials, name, what, target, when], i, arr) => (
              <div key={i} style={{
                padding: '10px 0', display: 'flex', alignItems: 'flex-start', gap: 10,
                borderBottom: i < arr.length - 1 ? `1px solid ${V2.lineSoft}` : 'none',
                fontSize: 13, color: V2.text,
              }}>
                <span style={{
                  width: 26, height: 26, borderRadius: '50%',
                  background: `linear-gradient(135deg, ${V2.primary}, ${V2.primaryDark})`,
                  color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 700, flexShrink: 0,
                }}>{initials}</span>
                <div style={{ flex: 1 }}>
                  <strong style={{ color: V2.ink }}>{name}</strong>{' '}
                  <span style={{ color: V2.muted }}>{what}</span>{' '}
                  <span>{target}</span>
                  <div style={{ fontSize: 11.5, color: V2.muted, marginTop: 2 }}>{when} ago</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* All apps grid */}
      <h2 style={{
        fontSize: 12, fontWeight: 700, color: V2.muted,
        textTransform: 'uppercase', letterSpacing: '0.08em', margin: '4px 0 12px',
      }}>All apps</h2>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[
          ['Jobs',      'briefcase', '12,480', '+182 / 24h'],
          ['Companies', 'building',  '782',    '+4 / 24h'],
          ['Users',     'user',      '142,840', '+184 / 24h'],
          ['Applications', 'check',  '38,214', '+1,420 / 24h'],
          ['Blog',      'document',  '142',    '+0'],
          ['Email campaigns', 'mail', '96',    'Active: 4'],
          ['Analytics', 'trending',  '1.8m',   'events/day'],
          ['Audit log', 'eye',       '14,218', 'entries / 30d'],
        ].map(([t, icon, val, sub]) => (
          <a key={t} style={{
            display: 'block', background: '#fff',
            border: `1px solid ${V2.line}`, borderRadius: V2.rMd, padding: 16,
            textDecoration: 'none', color: 'inherit',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <span style={{
                width: 30, height: 30, borderRadius: 8, background: V2.primarySoft,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              }}>
                <Icon name={icon} size={15} color={V2.primary} />
              </span>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: V2.ink }}>{t}</span>
            </div>
            <div style={{ fontSize: 20, fontWeight: 800, color: V2.ink, letterSpacing: '-0.02em' }}>{val}</div>
            <div style={{ fontSize: 11.5, color: V2.muted, marginTop: 4 }}>{sub}</div>
          </a>
        ))}
      </div>
    </AdminFrame>
  );
}

function modBtn(color, ghost) {
  return {
    padding: '5px 10px', borderRadius: 6,
    border: `1px solid ${color}50`,
    background: ghost ? '#fff' : color + '15',
    color, fontSize: 11.5, fontWeight: 700, cursor: 'pointer',
    fontFamily: V2.font, whiteSpace: 'nowrap',
  };
}

// ─── 3) JOBS CHANGELIST ─────────────────────────────────────────────────
const ADMIN_JOBS = [
  { id: 14821, title: 'Senior Python Engineer',     co: 'Monzo Bank',         loc: 'London, UK',    cat: 'Tech',         status: 'pending',  tier: 'standard', boost: 0,  score: 0.91, type: 'Full-time', src: 'employer-submit', views: 0,    pub: '—' },
  { id: 14820, title: 'Care Assistant',              co: 'Lavender House',     loc: 'Bristol, UK',   cat: 'Healthcare',   status: 'pending',  tier: 'featured', boost: 12, score: 0.88, type: 'Part-time', src: 'employer-submit', views: 0,    pub: '—' },
  { id: 14819, title: 'Marketing Lead — earn $$$',   co: 'Acme Corp',          loc: 'London, UK',    cat: 'Retail',       status: 'flagged',  tier: 'standard', boost: 0,  score: 0.12, type: 'Full-time', src: 'employer-submit', views: 0,    pub: '—' },
  { id: 14817, title: 'Warehouse Operative — Day',   co: 'Bridgewater',        loc: 'Manchester',    cat: 'Logistics',    status: 'approved', tier: 'featured', boost: 12, score: 0.94, type: 'Full-time', src: 'feed-indeed',     views: 1842, pub: '14.05.2026' },
  { id: 14815, title: 'Delivery Driver — Local',     co: 'Mercury Couriers',   loc: 'Birmingham',    cat: 'Driving',      status: 'approved', tier: 'sponsored',boost: 30, score: 0.97, type: 'Full-time', src: 'employer-submit', views: 612,  pub: '14.05.2026' },
  { id: 14811, title: 'Hotel Receptionist',          co: 'The Bramley',        loc: 'Edinburgh',     cat: 'Hospitality',  status: 'approved', tier: 'standard', boost: 0,  score: 0.82, type: 'Full-time', src: 'feed-workable',   views: 248,  pub: '13.05.2026' },
  { id: 14808, title: 'Registered Nurse — Day Unit', co: 'St. Margaret\u2019s',loc: 'Leicester',     cat: 'Healthcare',   status: 'approved', tier: 'standard', boost: 0,  score: 0.74, type: 'Full-time', src: 'feed-trac',       views: 482,  pub: '13.05.2026' },
  { id: 14797, title: 'Office Administrator',        co: 'Northgate',          loc: 'Leeds',         cat: 'Office',       status: 'rejected', tier: 'standard', boost: 0,  score: 0.18, type: 'Full-time', src: 'employer-submit', views: 0,    pub: '—' },
];

function V2AdminJobsListScreen() {
  return (
    <AdminFrame active="jobs" breadcrumbs={['Admin', 'Jobs', 'All jobs']}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 16, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 700, color: V2.ink, letterSpacing: '-0.02em' }}>Jobs</h1>
          <p style={{ margin: 0, fontSize: 13.5, color: V2.muted }}>12,480 jobs · 18 pending moderation · 12,442 live</p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <V2Button variant="secondary" size="sm" icon="document">Import</V2Button>
          <V2Button variant="secondary" size="sm" icon="document">Export</V2Button>
          <V2Button variant="primary" size="sm" icon="plus">Add job</V2Button>
        </div>
      </header>

      {/* Filter row + chips */}
      <div style={{
        background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rMd,
        padding: 12, marginBottom: 14, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap',
      }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 280 }}>
          <Icon name="search" size={15} color={V2.muted}
                style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)' }} />
          <input placeholder="Search title, company, ID, slug, affiliate id…" style={{
            width: '100%', padding: '8px 12px 8px 34px',
            background: V2.bgAlt, border: `1px solid ${V2.line}`, borderRadius: 8,
            fontSize: 13, color: V2.ink, fontFamily: V2.font, outline: 'none', boxSizing: 'border-box',
          }} />
        </div>
        {[['Pending', 18, true], ['Flagged', 4], ['Featured · live', 122], ['Stale 7d+', 38]].map(([t, n, on]) => (
          <button key={t} style={{
            padding: '7px 12px', borderRadius: 999, fontSize: 12.5, fontWeight: 600,
            border: `1px solid ${on ? V2.primary : V2.line}`,
            background: on ? V2.primarySoft : '#fff',
            color: on ? V2.primaryInk : V2.text,
            cursor: 'pointer', fontFamily: V2.font,
            display: 'inline-flex', alignItems: 'center', gap: 5,
          }}>{t} <span style={{ fontSize: 11, color: V2.faint }}>{n}</span></button>
        ))}
      </div>

      {/* Batch action bar — pinned when rows selected */}
      <div style={{
        position: 'sticky', top: 53, zIndex: 5,
        background: V2.ink, color: '#fff', padding: '10px 18px',
        borderRadius: V2.rMd, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 12,
        boxShadow: V2.shadowMd,
      }}>
        <span style={{ fontSize: 13, fontWeight: 600 }}>3 rows selected</span>
        <span style={{ flex: 1 }} />
        <button style={modBtn(V2.success)}>Approve</button>
        <button style={modBtn(V2.danger, true)}>Reject</button>
        <button style={{
          padding: '5px 10px', borderRadius: 6, background: 'rgba(255,255,255,0.10)',
          color: '#fff', border: '1px solid rgba(255,255,255,0.15)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: V2.font,
        }}>Edit tier…</button>
        <button style={{
          padding: '5px 10px', borderRadius: 6, background: 'transparent',
          color: '#CFD4DC', border: 'none', fontSize: 11.5, cursor: 'pointer', fontFamily: V2.font,
        }}>Deselect</button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '220px minmax(0, 1fr)', gap: 14, alignItems: 'start' }}>
        <aside style={{
          background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rMd,
          padding: 14, position: 'sticky', top: 130,
        }}>
          <h3 style={{ margin: '0 0 10px', fontSize: 11, fontWeight: 700, color: V2.muted, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Filter</h3>
          <AdminFilter label="Status" items={[['All', 12480], ['Pending', 18, true], ['Approved', 12420], ['Rejected', 38], ['Flagged', 4]]} />
          <AdminFilter label="Tier" items={[['Standard', 12260], ['Featured', 184, true], ['Sponsored', 36]]} />
          <AdminFilter label="Source" items={[['feed-indeed', 4218, true], ['feed-greenhouse', 2418], ['feed-workable', 1842], ['employer-submit', 982]]} />
          <AdminFilter label="Region" items={[['UK', 12480, true], ['US', 0], ['EU', 0]]} />
        </aside>

        <div style={{
          background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rMd, overflow: 'hidden',
        }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: V2.bgAlt, borderBottom: `1px solid ${V2.line}` }}>
                {[
                  <input key="all" type="checkbox" style={{ accentColor: V2.primary }} />,
                  'Title', 'Company', 'Location', 'Category', 'Status', 'Tier', 'Score', 'Views', 'Source', 'Published',
                ].map((h, i) => (
                  <th key={i} style={{
                    textAlign: typeof h === 'string' ? 'left' : 'center',
                    padding: '10px 14px', color: V2.muted, fontWeight: 700,
                    fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.06em', whiteSpace: 'nowrap',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {ADMIN_JOBS.map((j, i) => (
                <tr key={j.id} style={{
                  borderBottom: i < ADMIN_JOBS.length - 1 ? `1px solid ${V2.lineSoft}` : 'none',
                  background: i < 3 ? V2.primarySoft + '50' : '#fff',
                }}>
                  <td style={{ padding: '10px 14px', textAlign: 'center' }}>
                    <input type="checkbox" defaultChecked={i < 3} style={{ accentColor: V2.primary }} />
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <a style={{ color: V2.primary, textDecoration: 'none', fontWeight: 600 }}>{j.title}</a>
                    <div style={{ color: V2.faint, fontSize: 11, marginTop: 1 }}>#{j.id}</div>
                  </td>
                  <td style={{ padding: '10px 14px', color: V2.text }}>{j.co}</td>
                  <td style={{ padding: '10px 14px', color: V2.text }}>{j.loc}</td>
                  <td style={{ padding: '10px 14px' }}><V2CatPill name={j.cat} size="sm" /></td>
                  <td style={{ padding: '10px 14px' }}>
                    <V2Badge size="sm" tone={
                      j.status === 'approved' ? 'success' :
                      j.status === 'pending' ? 'warn' :
                      j.status === 'flagged' ? 'danger' : 'neutral'
                    }>{j.status}</V2Badge>
                  </td>
                  <td style={{ padding: '10px 14px' }}>
                    <V2TierBadge tier={j.tier} />
                  </td>
                  <td style={{ padding: '10px 14px', fontVariantNumeric: 'tabular-nums', fontWeight: 600, color: j.score >= 0.8 ? V2.success : j.score >= 0.5 ? V2.warn : V2.danger }}>
                    {j.score.toFixed(2)}
                  </td>
                  <td style={{ padding: '10px 14px', textAlign: 'right', color: V2.text, fontVariantNumeric: 'tabular-nums' }}>{j.views}</td>
                  <td style={{ padding: '10px 14px', color: V2.muted, fontSize: 11.5, fontFamily: V2.fontMono }}>{j.src}</td>
                  <td style={{ padding: '10px 14px', color: V2.muted, fontSize: 11.5 }}>{j.pub}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div style={{
            padding: '10px 16px', borderTop: `1px solid ${V2.line}`,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 12.5, color: V2.muted,
          }}>
            <span>Showing 1–8 of 12,480 jobs</span>
            <span style={{ display: 'inline-flex', gap: 6 }}>
              <button style={pgBtn(true)}>1</button>
              <button style={pgBtn()}>2</button>
              <button style={pgBtn()}>3</button>
              <button style={pgBtn()}>…</button>
              <button style={pgBtn()}>1560</button>
            </span>
          </div>
        </div>
      </div>
    </AdminFrame>
  );
}

function AdminFilter({ label, items }) {
  return (
    <div style={{ marginBottom: 14 }}>
      <div style={{ fontSize: 11.5, fontWeight: 700, color: V2.ink, marginBottom: 6 }}>{label}</div>
      {items.map(([t, n, on]) => (
        <a key={t} style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          padding: '5px 8px', borderRadius: 5,
          background: on ? V2.primarySoft : 'transparent',
          color: on ? V2.primaryInk : V2.text,
          fontSize: 12.5, fontWeight: on ? 600 : 500,
          textDecoration: 'none', cursor: 'pointer', marginBottom: 1,
        }}>
          <span>{t}</span>
          <span style={{ fontSize: 11, color: on ? V2.primary : V2.faint }}>{n.toLocaleString ? n.toLocaleString() : n}</span>
        </a>
      ))}
    </div>
  );
}

function pgBtn(on) {
  return {
    padding: '4px 10px', borderRadius: 5,
    background: on ? V2.primary : '#fff', color: on ? '#fff' : V2.text,
    border: `1px solid ${on ? V2.primary : V2.line}`,
    fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: V2.font, minWidth: 28,
  };
}

// ─── 4) JOBS CHANGE FORM ─────────────────────────────────────────────────
function V2AdminJobsEditScreen() {
  return (
    <AdminFrame active="jobs" breadcrumbs={['Admin', 'Jobs', 'Senior Python Engineer · Monzo (#14821)']}>
      <header style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
        marginBottom: 20, flexWrap: 'wrap', gap: 12,
      }}>
        <div>
          <h1 style={{ margin: '0 0 6px', fontSize: 22, fontWeight: 700, color: V2.ink, letterSpacing: '-0.02em' }}>
            Edit job · <span style={{ color: V2.muted, fontWeight: 500 }}>#14821</span> Senior Python Engineer
          </h1>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            <V2Badge tone="warn" size="md">pending</V2Badge>
            <span style={{ fontSize: 12.5, color: V2.muted }}>
              Submitted by <strong style={{ color: V2.text }}>hiring@monzo.com</strong> · 2 hours ago · source <code style={{ background: V2.bgAlt, padding: '1px 6px', borderRadius: 4, fontFamily: V2.fontMono }}>employer-submit</code>
            </span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button style={modBtn(V2.success)}>Approve</button>
          <button style={modBtn(V2.danger, true)}>Reject</button>
          <button style={modBtn(V2.warn, true)}>Mark pending</button>
        </div>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: '3fr 2fr', gap: 18, alignItems: 'start' }}>
        {/* Form */}
        <div>
          <AdminFieldSet title="Moderation" open>
            <AdmRow>
              <AdmFieldCol label="Status">
                <select defaultValue="pending" style={adminSelect()}>
                  <option>pending</option><option>approved</option><option>rejected</option>
                </select>
              </AdmFieldCol>
              <AdmFieldCol label="Submitted by"><AdmFieldInput value="hiring@monzo.com" /></AdmFieldCol>
            </AdmRow>
          </AdminFieldSet>

          <AdminFieldSet title="Core" open>
            <AdmFieldCol label="Title" full><AdmFieldInput value="Senior Python Engineer" /></AdmFieldCol>
            <AdmRow>
              <AdmFieldCol label="Company"><AdmFieldInput value="Monzo Bank" /></AdmFieldCol>
              <AdmFieldCol label="Slug"><AdmFieldInput value="senior-python-engineer-monzo-14821" /></AdmFieldCol>
            </AdmRow>
            <AdmRow>
              <AdmFieldCol label="Location"><AdmFieldInput value="London, UK" /></AdmFieldCol>
              <AdmFieldCol label="Category">
                <select defaultValue="Tech" style={adminSelect()}>
                  {Object.keys(V2.cats).map((c) => <option key={c}>{c}</option>)}
                </select>
              </AdmFieldCol>
            </AdmRow>
            <AdmRow>
              <AdmFieldCol label="Employment type">
                <select defaultValue="Full-time" style={adminSelect()}>
                  <option>Full-time</option><option>Part-time</option><option>Contract</option><option>Graduate</option>
                </select>
              </AdmFieldCol>
              <AdmFieldCol label="Work mode">
                <select defaultValue="Hybrid" style={adminSelect()}>
                  <option>On-site</option><option>Hybrid</option><option>Remote</option>
                </select>
              </AdmFieldCol>
            </AdmRow>
          </AdminFieldSet>

          <AdminFieldSet title="Description" open>
            <AdmFieldCol label="Short" full>
              <textarea defaultValue="Join the Platform team at Monzo — async-first Python services, sensible PostgreSQL, deep observability culture." style={adminTextarea(3)} />
            </AdmFieldCol>
            <AdmFieldCol label="Full description (markdown)" full>
              <textarea defaultValue={"Monzo runs on a Python and Go microservices stack…\n\n## What you'll do\n- Design Python services\n- Mentor mid-level engineers\n- On call ~1 week / 6"} style={adminTextarea(9, true)} />
            </AdmFieldCol>
          </AdminFieldSet>

          <AdminFieldSet title="Pay" open>
            <AdmRow>
              <AdmFieldCol label="Display"><AdmFieldInput value="£90,000 – £120,000" /></AdmFieldCol>
              <AdmFieldCol label="Min"><AdmFieldInput value="90000" /></AdmFieldCol>
              <AdmFieldCol label="Max"><AdmFieldInput value="120000" /></AdmFieldCol>
            </AdmRow>
          </AdminFieldSet>

          <AdminFieldSet title="Ranking" open>
            <AdmRow>
              <AdmFieldCol label="Tier">
                <select defaultValue="standard" style={adminSelect()}>
                  <option>standard</option><option>featured</option><option>sponsored</option>
                </select>
              </AdmFieldCol>
              <AdmFieldCol label="Manual boost"><AdmFieldInput value="0" /></AdmFieldCol>
              <AdmFieldCol label="Ranking score"><AdmFieldInput value="0.91" /></AdmFieldCol>
            </AdmRow>
          </AdminFieldSet>

          {/* Sticky footer */}
          <div style={{
            position: 'sticky', bottom: 0, marginTop: 12,
            background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rMd, padding: 14,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            boxShadow: V2.shadowLg,
          }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 12, fontSize: 12.5, color: V2.muted }}>
              <V2Badge tone="success" size="md" icon="check">Autosaved 3s ago</V2Badge>
              14 revisions
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <V2Button variant="destructive" size="sm">Delete</V2Button>
              <V2Button variant="secondary" size="sm">Save & continue</V2Button>
              <V2Button variant="primary" size="sm">Save</V2Button>
            </div>
          </div>
        </div>

        {/* Sidebar: metadata + history */}
        <aside style={{ position: 'sticky', top: 80, display: 'grid', gap: 14 }}>
          <SidePanel title="At a glance">
            {[
              ['ID', '#14821'],
              ['Status', <V2Badge tone="warn" size="sm">pending</V2Badge>],
              ['Tier', 'Standard'],
              ['Ranking score', '0.91'],
              ['Submitted', '2 hours ago'],
              ['Reviewer', '— (unassigned)'],
            ].map(([k, v]) => (
              <div key={k} style={{
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                padding: '8px 0', borderBottom: `1px solid ${V2.lineSoft}`, fontSize: 13,
              }}>
                <span style={{ color: V2.muted }}>{k}</span>
                <span style={{ color: V2.ink, fontWeight: 600, textAlign: 'right' }}>{v}</span>
              </div>
            ))}
          </SidePanel>

          <SidePanel title="Modify history">
            {[
              { who: 'auto',                when: '2h ago', what: 'Slug generated on create' },
              { who: 'hiring@monzo.com',    when: '2h ago', what: 'Submitted job posting' },
              { who: 'Olha D.',             when: '38m ago', what: 'Edited salary: £90–110k → £90–120k' },
              { who: 'auto',                when: '12m ago', what: 'Ranking recomputed: 0.84 → 0.91' },
            ].map((r, i, arr) => (
              <div key={i} style={{
                padding: '9px 0', display: 'flex', gap: 10, alignItems: 'flex-start',
                borderBottom: i < arr.length - 1 ? `1px solid ${V2.lineSoft}` : 'none',
                fontSize: 13, color: V2.text,
              }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: r.who === 'auto' ? V2.faint : V2.primary, marginTop: 6, flexShrink: 0 }} />
                <div style={{ flex: 1 }}>
                  <div>{r.what}</div>
                  <div style={{ fontSize: 11, color: V2.muted, marginTop: 2 }}>{r.who} · {r.when}</div>
                </div>
              </div>
            ))}
          </SidePanel>

          <SidePanel title="Linked records">
            {[
              'Place: London (5128581)',
              'JobV2 mirror — synced',
              'JobText — 12 fragments',
              'JobUrl — 3 URLs',
            ].map((t) => (
              <a key={t} style={{
                display: 'block', padding: '8px 0', borderBottom: `1px solid ${V2.lineSoft}`,
                color: V2.primary, fontSize: 13, fontWeight: 500, textDecoration: 'none',
              }}>{t} →</a>
            ))}
          </SidePanel>
        </aside>
      </div>
    </AdminFrame>
  );
}

function AdminFieldSet({ title, open, children }) {
  return (
    <div style={{
      background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rMd,
      marginBottom: 12, overflow: 'hidden',
    }}>
      <div style={{
        padding: '12px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        borderBottom: open ? `1px solid ${V2.line}` : 'none', cursor: 'pointer',
      }}>
        <h3 style={{ margin: 0, fontSize: 13.5, fontWeight: 700, color: V2.ink }}>{title}</h3>
        <Icon name={open ? 'chevron-down' : 'chevron-right'} size={16} color={V2.muted} />
      </div>
      {open && <div style={{ padding: 16 }}>{children}</div>}
    </div>
  );
}

function adminSelect() {
  return {
    width: '100%', padding: '8px 11px',
    border: `1px solid ${V2.line}`, borderRadius: 7,
    fontSize: 13, color: V2.ink, background: '#fff',
    fontFamily: V2.font, outline: 'none', boxSizing: 'border-box',
  };
}

function adminTextarea(rows = 3, mono = false) {
  return {
    width: '100%', padding: '8px 11px',
    border: `1px solid ${V2.line}`, borderRadius: 7,
    fontSize: 12.5, color: V2.ink, background: '#fff',
    fontFamily: mono ? V2.fontMono : V2.font,
    outline: 'none', boxSizing: 'border-box',
    minHeight: rows * 20, resize: 'vertical', lineHeight: 1.55,
  };
}

function SidePanel({ title, children }) {
  return (
    <div style={{ background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rMd, padding: 16 }}>
      <h3 style={{ margin: '0 0 10px', fontSize: 11, fontWeight: 700, color: V2.muted, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{title}</h3>
      {children}
    </div>
  );
}

// ─── 5) MODERATION QUEUE ─────────────────────────────────────────────────
function V2AdminModQueueScreen() {
  const items = [
    {
      id: 14821, t: 'Senior Python Engineer', co: 'Monzo Bank', cat: 'Tech', loc: 'London, UK',
      submitter: 'hiring@monzo.com', age: '12 min', risk: 0.08, riskTone: 'success',
      raw: 'Senior Python Engineer\nMonzo Bank\nLondon, UK\n£90k–£120k\n\nJoin the Platform team building rails for a digital bank with 8m+ customers. Async-first Python services...',
      cleaned: { title: 'Senior Python Engineer', co: 'Monzo Bank', loc: 'London, UK', sal: '£90,000 – £120,000', cat: 'Tech', mode: 'Hybrid' },
      flags: ['New employer'],
    },
    {
      id: 14820, t: 'Care Assistant — Residential Home', co: 'Lavender House Care', cat: 'Healthcare', loc: 'Bristol, UK',
      submitter: 'hr@lavenderhouse.co.uk', age: '38 min', risk: 0.06, riskTone: 'success',
      raw: 'Care Assistant\nLavender House\nBristol\n£12.80 / hr\n\nFamily-owned home looking for kind, patient carers...',
      cleaned: { title: 'Care Assistant — Residential Home', co: 'Lavender House Care', loc: 'Bristol, UK', sal: '£12.80 / hour', cat: 'Healthcare', mode: 'On-site' },
      flags: [],
    },
    {
      id: 14819, t: 'Marketing Lead — earn $$$ from home', co: 'Acme Corp', cat: 'Retail', loc: 'London, UK',
      submitter: 'noreply@acme.io', age: '1 hr', risk: 0.91, riskTone: 'danger',
      raw: 'Marketing Lead\nAcme Corp\nLondon\n$$$$\n\nEarn unlimited $$$ from home. No experience needed. Click apply to learn more...',
      cleaned: null,
      flags: ['Salary mentions $$$', 'Disposable email domain', 'Very low word count (84)', '4 duplicate submissions'],
    },
  ];
  return (
    <AdminFrame active="mod" breadcrumbs={['Admin', 'Moderation queue']}>
      <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 22, flexWrap: 'wrap', gap: 12 }}>
        <div>
          <h1 style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 700, color: V2.ink, letterSpacing: '-0.02em' }}>
            Moderation queue
          </h1>
          <p style={{ margin: 0, fontSize: 13.5, color: V2.muted }}>
            18 pending · 4 flagged · oldest waiting 4h 12m · median time-to-decide 6m
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <V2Button variant="secondary" size="sm" icon="sliders">Auto-rules</V2Button>
          <V2Button variant="primary" size="sm" icon="check">Approve 11 low-risk</V2Button>
        </div>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 22 }}>
        <V2Stat label="Pending · low risk" value="11" icon="check" />
        <V2Stat label="Pending · review"   value="3"  icon="eye" />
        <V2Stat label="Flagged · high risk" value="4" icon="shield" />
        <V2Stat label="Decisions today"    value="160" delta="98% within SLA" icon="trending" />
      </div>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 6, borderBottom: `1px solid ${V2.line}`, marginBottom: 14 }}>
        {[['All', 18, true], ['Low risk', 11], ['Needs review', 3], ['Flagged', 4]].map(([t, n, on]) => (
          <a key={t} style={{
            padding: '10px 14px',
            borderBottom: `2px solid ${on ? V2.primary : 'transparent'}`,
            color: on ? V2.primary : V2.muted,
            fontWeight: on ? 700 : 500, fontSize: 13, marginBottom: -1,
            textDecoration: 'none',
          }}>{t} <span style={{ color: V2.faint, fontSize: 11 }}>{n}</span></a>
        ))}
      </div>

      {/* Queue cards (side-by-side raw vs cleaned) */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {items.map((it) => <ModCard key={it.id} it={it} />)}
      </div>
    </AdminFrame>
  );
}

function ModCard({ it }) {
  const risky = it.riskTone === 'danger';
  return (
    <article style={{
      background: '#fff',
      border: `1px solid ${risky ? V2.dangerLine : V2.line}`,
      borderRadius: V2.rLg, padding: 18,
      boxShadow: risky ? `0 0 0 3px ${V2.dangerBg}` : V2.shadowSm,
    }}>
      <header style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
        <input type="checkbox" style={{ accentColor: V2.primary, width: 16, height: 16 }} />
        <V2CompanyAvatar name={it.co} category={it.cat} size={40} radius={10} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: V2.ink }}>{it.t}</h3>
            <span style={{ fontSize: 12, color: V2.muted }}>#{it.id}</span>
            <V2Badge size="sm" tone={it.riskTone}>
              Risk {it.risk.toFixed(2)} · {risky ? 'High' : 'Low'}
            </V2Badge>
            <V2CatPill name={it.cat} size="sm" />
          </div>
          <div style={{ fontSize: 12.5, color: V2.muted, marginTop: 3 }}>
            {it.co} · {it.loc} · submitted {it.age} ago by <span style={{ color: V2.text }}>{it.submitter}</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          <button style={modBtn(V2.success)}>Approve</button>
          <button style={modBtn(V2.danger, true)}>Reject</button>
          <button style={modBtn(V2.muted, true)}>···</button>
        </div>
      </header>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {/* Raw */}
        <div style={{
          background: V2.bgAlt, border: `1px solid ${V2.line}`,
          borderRadius: V2.rMd, padding: 14,
        }}>
          <div style={{
            fontSize: 11, fontWeight: 700, color: V2.muted,
            textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8,
          }}>Raw scrape</div>
          <pre style={{
            margin: 0, fontFamily: V2.fontMono, fontSize: 12,
            color: V2.text, lineHeight: 1.55, whiteSpace: 'pre-wrap',
          }}>{it.raw}</pre>
        </div>
        {/* Cleaned */}
        <div style={{
          background: '#fff', border: `1px solid ${V2.primaryRing}`,
          borderRadius: V2.rMd, padding: 14,
        }}>
          <div style={{
            fontSize: 11, fontWeight: 700, color: V2.primary,
            textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8,
          }}>Proposed cleaned data</div>
          {it.cleaned ? (
            <div style={{ display: 'grid', gap: 6, fontSize: 13 }}>
              {Object.entries(it.cleaned).map(([k, v]) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                  <span style={{ color: V2.muted, textTransform: 'capitalize' }}>{k}</span>
                  <span style={{ color: V2.ink, fontWeight: 600, textAlign: 'right' }}>{v}</span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ fontSize: 13, color: V2.danger, fontStyle: 'italic' }}>
              Auto-cleaner refused — content does not look like a genuine job posting.
            </div>
          )}
        </div>
      </div>

      {it.flags.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 12 }}>
          {it.flags.map((f) => (
            <V2Badge key={f} tone={risky ? 'danger' : 'warn'} size="sm">⚠ {f}</V2Badge>
          ))}
        </div>
      )}
    </article>
  );
}

Object.assign(window, {
  V2AdminLoginScreen, V2AdminDashboardScreen,
  V2AdminJobsListScreen, V2AdminJobsEditScreen, V2AdminModQueueScreen,
});
