// ScrollJob v2 — Market stats (Salaries, Trends, Market overview)
// Public marketing/SEO surface. Clean data product feel, no spreadsheet vibes.

function V2StatsShell({ active, title, sub, children }) {
  return (
    <div style={{ background: V2.bg, fontFamily: V2.font, color: V2.ink, minHeight: '100%' }}>
      <V2Header active="Discover" />
      <section style={{
        background: V2.bgAlt, padding: '40px 0 28px',
        borderBottom: `1px solid ${V2.line}`,
      }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 32px' }}>
          <nav style={{ fontSize: 13, color: V2.muted, marginBottom: 12 }}>
            <a style={{ color: V2.muted, textDecoration: 'none' }}>Discover</a>
            <span style={{ margin: '0 8px' }}>·</span>
            <a style={{ color: V2.muted, textDecoration: 'none' }}>Market stats</a>
          </nav>
          <h1 style={{
            margin: '0 0 8px', fontSize: 40, fontWeight: 800,
            color: V2.ink, letterSpacing: '-0.03em',
          }}>{title}</h1>
          <p style={{ margin: '0 0 22px', fontSize: 16.5, color: V2.text, maxWidth: 760, lineHeight: 1.55 }}>{sub}</p>
          {/* Tabs */}
          <div style={{ display: 'flex', gap: 6, borderBottom: `1px solid ${V2.line}` }}>
            {[['salaries', 'Salaries'], ['trends', 'Trends'], ['market', 'Market overview']].map(([k, l]) => (
              <a key={k} style={{
                padding: '12px 18px', borderRadius: '8px 8px 0 0',
                borderBottom: `2px solid ${active === k ? V2.primary : 'transparent'}`,
                color: active === k ? V2.primary : V2.muted,
                fontWeight: active === k ? 700 : 500, fontSize: 14,
                textDecoration: 'none', marginBottom: -1,
              }}>{l}</a>
            ))}
          </div>
        </div>
      </section>
      <main style={{ maxWidth: 1280, margin: '0 auto', padding: '28px 32px 0' }}>{children}</main>
      <V2Footer />
    </div>
  );
}

function StatCard({ children, padding = 22 }) {
  return (
    <div style={{
      background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rLg,
      padding, marginBottom: 18,
    }}>{children}</div>
  );
}

function InsightCard({ headline, body, delta }) {
  return (
    <div style={{
      background: V2.primarySoft, border: `1px solid ${V2.primaryRing}`,
      borderRadius: V2.rLg, padding: 22,
    }}>
      <div style={{
        display: 'inline-flex', alignItems: 'center', gap: 5, marginBottom: 10,
        padding: '3px 9px', background: '#fff', color: V2.primaryInk,
        borderRadius: 999, fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
      }}>
        <Icon name="sparkle" size={12} color={V2.primary} /> Insight
      </div>
      <div style={{ fontSize: 20, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em', lineHeight: 1.3 }}>
        {headline}
      </div>
      <p style={{ margin: '8px 0 0', fontSize: 13.5, color: V2.text, lineHeight: 1.55 }}>{body}</p>
      {delta && (
        <div style={{
          marginTop: 12, fontSize: 12.5, color: V2.success, fontWeight: 700,
          display: 'inline-flex', alignItems: 'center', gap: 5,
        }}>
          <Icon name="trending" size={13} /> {delta}
        </div>
      )}
    </div>
  );
}

// ─── SALARIES ────────────────────────────────────────────────────────────
function V2StatsSalariesScreen() {
  const cats = [
    ['Care assistant',         11.5, 14.0,  9_612,  V2.cats.Healthcare.accent],
    ['Warehouse operative',    12.0, 14.8,  6_218,  V2.cats.Logistics.accent],
    ['Delivery driver',        25_000, 34_000, 4_218, V2.cats.Driving.accent, true],
    ['Hotel receptionist',     22_500, 28_000, 1_218, V2.cats.Hospitality.accent, true],
    ['Office administrator',   24_000, 32_000, 2_812, V2.cats.Office.accent, true],
    ['Electrician (NVQ 3)',    38_000, 52_000, 1_218, V2.cats.Trades.accent, true],
    ['Software engineer',      55_000, 110_000, 2_212, V2.cats.Tech.accent, true],
    ['Graduate trainee',       26_000, 32_000, 612,   V2.cats.Graduate.accent, true],
  ];
  const max = 120_000;
  return (
    <V2StatsShell
      active="salaries"
      title="UK salary statistics"
      sub="Median and range across all live jobs on ScrollJob. Updated nightly. £ GBP."
    >
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <V2Stat label="Median salary, UK"  value="£32,800" delta="+3.4% YoY" icon="money" />
        <V2Stat label="Median hourly, UK"  value="£12.80"  delta="+5.1% YoY" icon="clock" />
        <V2Stat label="Highest-paid sector" value="Tech · £85k" sub="2,212 live jobs" icon="lightning" />
        <V2Stat label="Lowest-paid sector"  value="Hospitality · £22k" sub="8,214 live jobs" icon="cup" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, marginBottom: 22 }}>
        <StatCard>
          <h2 style={{ margin: '0 0 4px', fontSize: 18, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
            Salary range by category
          </h2>
          <p style={{ margin: '0 0 18px', fontSize: 13, color: V2.muted }}>
            Annual unless marked /hour. Bar shows 10th–90th percentile · dot marks median.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {cats.map(([label, mn, mx, count, color, annual]) => (
              <RangeBar key={label} label={label} mn={mn} mx={mx} count={count} color={color} max={max} annual={annual} />
            ))}
          </div>
        </StatCard>
        <InsightCard
          headline="Care wages caught up to retail in 2026"
          body="Median care assistant pay (£12.80/hr) is now level with retail and slightly above hospitality, driven by sustained national living wage rises and chronic staffing shortages in social care."
          delta="Care wages up 8.2% YoY"
        />
      </div>

      <StatCard>
        <h2 style={{ margin: '0 0 14px', fontSize: 18, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
          Salary by region · median across all categories
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {[
            ['London',     42_800, '+18% vs UK avg'],
            ['South East', 36_200, '+10%'],
            ['Manchester', 31_400, '−4%'],
            ['Edinburgh',  32_800, '0%'],
            ['Bristol',    33_200, '+1%'],
            ['Leeds',      30_800, '−6%'],
            ['Birmingham', 30_400, '−7%'],
            ['Cardiff',    29_600, '−10%'],
          ].map(([region, salary, vs]) => (
            <div key={region} style={{
              padding: 14, background: V2.bgAlt, borderRadius: V2.rMd,
            }}>
              <div style={{ fontSize: 12, color: V2.muted, marginBottom: 4 }}>{region}</div>
              <div style={{ fontSize: 20, fontWeight: 800, color: V2.ink, letterSpacing: '-0.02em' }}>£{salary.toLocaleString()}</div>
              <div style={{
                fontSize: 11.5, marginTop: 6, fontWeight: 600,
                color: vs.startsWith('+') ? V2.success : vs.startsWith('−') ? V2.danger : V2.muted,
              }}>{vs}</div>
            </div>
          ))}
        </div>
      </StatCard>
    </V2StatsShell>
  );
}

function RangeBar({ label, mn, mx, count, color, max, annual }) {
  const fmt = annual ? (n) => `£${(n / 1000).toFixed(0)}k` : (n) => `£${n.toFixed(1)}/hr`;
  const scale = annual ? max : 30;
  const left = (mn / scale) * 100, right = (mx / scale) * 100;
  const median = (left + right) / 2;
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13 }}>
        <span style={{ fontWeight: 600, color: V2.ink }}>{label}</span>
        <span style={{ color: V2.muted }}>{count.toLocaleString()} jobs · {fmt(mn)} – {fmt(mx)}</span>
      </div>
      <div style={{ position: 'relative', height: 10, background: V2.bgAlt, borderRadius: 999 }}>
        <div style={{
          position: 'absolute', left: `${left}%`, width: `${right - left}%`, height: '100%',
          background: color + 'AA', borderRadius: 999,
        }} />
        <span style={{
          position: 'absolute', left: `${median}%`, top: -3, width: 16, height: 16, borderRadius: '50%',
          background: color, border: '3px solid #fff', boxShadow: V2.shadowSm,
          transform: 'translateX(-50%)',
        }} />
      </div>
    </div>
  );
}

// ─── TRENDS ───────────────────────────────────────────────────────────────
function V2StatsTrendsScreen() {
  const weeks = [22, 28, 25, 32, 38, 35, 42, 48, 44, 52, 58, 54, 62, 71, 68, 76, 84, 88, 94, 102, 108, 124, 132, 142];
  const max = Math.max(...weeks);
  return (
    <V2StatsShell
      active="trends"
      title="Hiring trends"
      sub="Week-over-week growth, fastest-growing categories, and shifts to watch."
    >
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <V2Stat label="New jobs this week" value="14,218" delta="+18% WoW" icon="trending" />
        <V2Stat label="Fastest-growing"    value="AI / ML" sub="+34% in 30 days" icon="lightning" />
        <V2Stat label="Slowest"            value="Marketing" delta="−4%" deltaTone="danger" icon="briefcase" />
        <V2Stat label="Avg. days to fill"  value="9.6 days" delta="2.4 days faster" icon="clock" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18, marginBottom: 22 }}>
        <StatCard>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
              New listings per week · 6 months
            </h2>
            <div style={{ display: 'flex', gap: 6 }}>
              {['7d', '30d', '90d', '6m', '1y'].map((p, i) => (
                <button key={p} style={{
                  padding: '5px 10px', borderRadius: 6,
                  background: i === 3 ? V2.primary : '#fff',
                  color: i === 3 ? '#fff' : V2.text,
                  border: `1px solid ${i === 3 ? V2.primary : V2.line}`,
                  fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: V2.font,
                }}>{p}</button>
              ))}
            </div>
          </div>
          {/* Sparkline */}
          <svg viewBox="0 0 760 200" style={{ width: '100%', height: 200, display: 'block' }} preserveAspectRatio="none">
            <defs>
              <linearGradient id="trend-grad" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%"   stopColor={V2.primary} stopOpacity="0.32" />
                <stop offset="100%" stopColor={V2.primary} stopOpacity="0" />
              </linearGradient>
            </defs>
            {[0, 0.25, 0.5, 0.75, 1].map((t) => (
              <line key={t} x1="0" x2="760" y1={200 - t * 180 - 10} y2={200 - t * 180 - 10} stroke={V2.lineSoft} strokeWidth="1" />
            ))}
            {(() => {
              const stepX = 760 / (weeks.length - 1);
              const pts = weeks.map((v, i) => `${i * stepX},${190 - (v / max) * 170}`).join(' ');
              const area = `0,200 ${pts} 760,200`;
              return (
                <>
                  <polygon points={area} fill="url(#trend-grad)" />
                  <polyline points={pts} fill="none" stroke={V2.primary} strokeWidth="3" strokeLinejoin="round" strokeLinecap="round" />
                  {weeks.map((v, i) => (
                    <circle key={i} cx={i * stepX} cy={190 - (v / max) * 170} r="3" fill={V2.primary} />
                  ))}
                </>
              );
            })()}
          </svg>
        </StatCard>

        <InsightCard
          headline="Care, logistics and graduate hiring are leading the year"
          body="The strongest week-over-week growth is in care (+18%), logistics (+14%) and graduate roles (+22%). Marketing and traditional office admin remain softer, with mid-single-digit declines."
          delta="3.4× more new postings than this week last year"
        />
      </div>

      <StatCard>
        <h2 style={{ margin: '0 0 4px', fontSize: 18, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
          Categories trending now
        </h2>
        <p style={{ margin: '0 0 18px', fontSize: 13, color: V2.muted }}>30-day change in new postings.</p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            ['AI / ML',                 +34, V2.cats.Tech.accent,         182],
            ['Engineering management',  +22, V2.cats.Tech.accent,         412],
            ['Care assistant',          +18, V2.cats.Healthcare.accent,   4_218],
            ['Logistics — warehouse',   +14, V2.cats.Logistics.accent,    3_218],
            ['Hospitality — chef',      +12, V2.cats.Hospitality.accent,  812],
            ['Customer support remote', +9,  V2.cats.Remote.accent,       612],
            ['Office administrator',    -3,  V2.cats.Office.accent,       2_812],
            ['Marketing',               -4,  V2.cats.Retail.accent,       412],
          ].map(([label, growth, color, n]) => (
            <div key={label} style={{
              display: 'grid', gridTemplateColumns: '200px 1fr 80px 80px', gap: 14, alignItems: 'center',
              padding: '10px 0', borderBottom: `1px solid ${V2.lineSoft}`,
            }}>
              <span style={{ fontSize: 14, fontWeight: 600, color: V2.ink }}>{label}</span>
              <div style={{ height: 8, background: V2.bgAlt, borderRadius: 4, position: 'relative', overflow: 'hidden' }}>
                <div style={{
                  position: 'absolute', left: growth > 0 ? '50%' : `${50 + growth}%`,
                  width: `${Math.abs(growth)}%`, height: '100%',
                  background: growth > 0 ? color : V2.danger,
                }} />
                <span style={{ position: 'absolute', left: '50%', top: -2, width: 2, height: 12, background: V2.muted }} />
              </div>
              <span style={{ fontSize: 13, color: V2.muted, textAlign: 'right' }}>{n.toLocaleString()}</span>
              <span style={{
                fontSize: 14, fontWeight: 700, textAlign: 'right',
                color: growth > 0 ? V2.success : V2.danger,
              }}>{growth > 0 ? '+' : ''}{growth}%</span>
            </div>
          ))}
        </div>
      </StatCard>
    </V2StatsShell>
  );
}

// ─── MARKET OVERVIEW ──────────────────────────────────────────────────────
function V2StatsMarketScreen() {
  return (
    <V2StatsShell
      active="market"
      title="UK job market overview"
      sub="Snapshot of the UK hiring landscape. Live job index, by region, work pattern and pay tier."
    >
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <V2Stat label="Live UK jobs" value="68,420" delta="+18% WoW" icon="briefcase" />
        <V2Stat label="Hires this month" value="14,200" delta="Time-to-hire −38%" icon="check" />
        <V2Stat label="Employers hiring" value="8,612" sub="of all sizes" icon="building" />
        <V2Stat label="Remote share"     value="22%"   delta="+3pp YoY" icon="globe" />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, marginBottom: 22 }}>
        <StatCard>
          <h2 style={{ margin: '0 0 14px', fontSize: 18, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
            Job mix by category
          </h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {V2_CATEGORIES.map((c) => {
              const pct = (c.count / 68_420) * 100;
              const col = V2.cats[c.name].accent;
              return (
                <div key={c.name} style={{ display: 'grid', gridTemplateColumns: '160px 1fr 100px', alignItems: 'center', gap: 14 }}>
                  <span style={{
                    fontSize: 13, fontWeight: 600, color: V2.ink,
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                  }}>
                    <Icon name={c.icon} size={14} color={col} />
                    {c.name}
                  </span>
                  <div style={{ height: 8, background: V2.bgAlt, borderRadius: 4, overflow: 'hidden' }}>
                    <div style={{ width: `${pct * 4}%`, height: '100%', background: col }} />
                  </div>
                  <span style={{ fontSize: 13, color: V2.muted, textAlign: 'right' }}>
                    {c.count.toLocaleString()} <span style={{ color: V2.faint }}>· {pct.toFixed(1)}%</span>
                  </span>
                </div>
              );
            })}
          </div>
        </StatCard>

        <StatCard>
          <h2 style={{ margin: '0 0 14px', fontSize: 18, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
            Work pattern
          </h2>
          <div style={{ display: 'flex', alignItems: 'center', gap: 22 }}>
            {/* Donut */}
            <div style={{ position: 'relative', width: 160, height: 160 }}>
              <svg width="160" height="160" viewBox="0 0 160 160">
                <circle cx="80" cy="80" r="60" stroke={V2.lineSoft} strokeWidth="20" fill="none" />
                <circle cx="80" cy="80" r="60" stroke={V2.primary} strokeWidth="20" fill="none"
                        strokeDasharray={`${377 * 0.22} 377`} strokeLinecap="round"
                        transform="rotate(-90 80 80)" />
                <circle cx="80" cy="80" r="60" stroke="#0EA5E9" strokeWidth="20" fill="none"
                        strokeDasharray={`${377 * 0.21} 377`} strokeDashoffset={-377 * 0.22} strokeLinecap="round"
                        transform="rotate(-90 80 80)" />
              </svg>
              <div style={{
                position: 'absolute', inset: 0,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              }}>
                <div style={{ fontSize: 28, fontWeight: 800, color: V2.ink, lineHeight: 1, letterSpacing: '-0.02em' }}>57%</div>
                <div style={{ fontSize: 11, color: V2.muted, marginTop: 4 }}>On-site</div>
              </div>
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                ['On-site', 57, V2.lineStrong, '39,000 jobs'],
                ['Remote', 22, V2.primary,     '15,050 jobs'],
                ['Hybrid', 21, '#0EA5E9',      '14,370 jobs'],
              ].map(([l, pct, col, sub]) => (
                <div key={l} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ width: 10, height: 10, borderRadius: 2, background: col }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: V2.ink }}>{l} · {pct}%</div>
                    <div style={{ fontSize: 11.5, color: V2.muted }}>{sub}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </StatCard>
      </div>

      <StatCard>
        <h2 style={{ margin: '0 0 14px', fontSize: 18, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>
          Where the jobs are
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10 }}>
          {[
            ['London',      14_218], ['Manchester', 5_218],  ['Birmingham', 4_218],
            ['Leeds',       3_812],  ['Bristol',    2_418],  ['Edinburgh',  2_218],
            ['Glasgow',     1_842],  ['Cardiff',    1_482],  ['Liverpool',  1_842],
            ['Newcastle',   1_218],  ['Sheffield',  1_412],  ['Belfast',    818],
          ].map(([city, count]) => (
            <a key={city} style={{
              padding: 14, background: V2.bgAlt, borderRadius: V2.rMd,
              display: 'block', textDecoration: 'none',
            }}>
              <div style={{ fontSize: 13, color: V2.muted, marginBottom: 4 }}>{city}</div>
              <div style={{ fontSize: 18, fontWeight: 800, color: V2.ink, letterSpacing: '-0.02em' }}>{count.toLocaleString()}</div>
            </a>
          ))}
        </div>
      </StatCard>
    </V2StatsShell>
  );
}

Object.assign(window, { V2StatsSalariesScreen, V2StatsTrendsScreen, V2StatsMarketScreen });
