// Local form helpers (Babel scripts don't share scope across <script> tags)
function CabFieldCol({ 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 CabFieldInput({ value }) {
  return (
    <input defaultValue={value} style={{
      width: '100%', padding: '10px 12px', border: `1px solid ${V2.line}`,
      borderRadius: 10, fontSize: 13.5, outline: 'none', fontFamily: V2.font,
      color: V2.ink, boxSizing: 'border-box',
    }} />
  );
}

// ScrollJob v2 — Job-seeker cabinet (authenticated)
// Dashboard, Applications, Browse history, Settings — sidebar layout.

function CabShell({ active, title, sub, children }) {
  const nav = [
    ['dashboard',    'Dashboard',     'home'],
    ['saved',        'Saved jobs',    'bookmark', 8],
    ['applications', 'Applications',  'check',   12],
    ['history',      'Browse history','clock'],
    ['resume',       'Resume',        'document'],
    ['alerts',       'Job alerts',    'bell',    3],
    ['settings',     'Settings',      'sliders'],
  ];
  return (
    <div style={{ background: V2.bg, fontFamily: V2.font, color: V2.ink, minHeight: '100%' }}>
      <V2Header active="" variant="seeker" />
      <main style={{ maxWidth: 1280, margin: '0 auto', padding: '32px 32px 0' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '260px minmax(0, 1fr)', gap: 32, alignItems: 'start' }}>
          <V2SeekerSidebar items={nav} active={active} />
          <div>
            <header style={{ marginBottom: 22 }}>
              <h1 style={{ margin: '0 0 4px', fontSize: 28, fontWeight: 700, color: V2.ink, letterSpacing: '-0.02em' }}>
                {title}
              </h1>
              <p style={{ margin: 0, fontSize: 15, color: V2.muted }}>{sub}</p>
            </header>
            {children}
          </div>
        </div>
      </main>
      <V2Footer />
    </div>
  );
}

// ─── DASHBOARD ──────────────────────────────────────────────────────────
function V2CabDashboardScreen() {
  return (
    <CabShell active="dashboard" title="Welcome back, Emma" sub="3 new matches today · last sign-in yesterday at 18:22">
      {/* Next best actions — at top, large */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 22 }}>
        {[
          { icon: 'sparkle',  bg: V2.primarySoft, color: V2.primary,
            label: 'Next up',     title: '3 new matches today', sub: 'Care assistant in Bristol · within 10mi',
            cta: 'Review matches' },
          { icon: 'document', bg: '#FEF6E6', color: '#B45309',
            label: 'In progress', title: 'Resume is 72% complete', sub: '3 sections to fill · adds ~38% more profile views',
            cta: 'Continue resume' },
          { icon: 'bookmark', bg: V2.bgAlt, color: V2.ink,
            label: 'Shortlist',   title: '5 saved jobs to review', sub: 'All still active · oldest saved 6 days ago',
            cta: 'Open saved' },
        ].map((c) => (
          <div key={c.title} style={{
            background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rLg, padding: 22,
          }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 12,
              padding: '3px 9px', borderRadius: 999, background: c.bg, color: c.color,
              fontSize: 11, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>
              <Icon name={c.icon} size={11} /> {c.label}
            </div>
            <div style={{ fontSize: 17, fontWeight: 700, color: V2.ink, marginBottom: 6, letterSpacing: '-0.01em' }}>{c.title}</div>
            <p style={{ margin: '0 0 16px', fontSize: 13, color: V2.muted, lineHeight: 1.55 }}>{c.sub}</p>
            <V2Button variant={c.label === 'Next up' ? 'primary' : 'secondary'} size="sm" iconRight="arrow-right">{c.cta}</V2Button>
          </div>
        ))}
      </div>

      {/* Stats strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <V2Stat label="Profile views"     value="186"  delta="+24 this week" icon="eye" />
        <V2Stat label="Saved jobs"         value="8"    delta="2 new this week" icon="bookmark" />
        <V2Stat label="Applications"       value="12"   sub="3 awaiting response" icon="check" />
        <V2Stat label="Match score"        value="High" delta="Top 12% in Healthcare" icon="target" />
      </div>

      {/* Two columns */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18, marginBottom: 22 }}>
        <section 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 }}>Recommended for you</h2>
            <a style={{ color: V2.primary, fontWeight: 600, fontSize: 13, textDecoration: 'none' }}>See all →</a>
          </header>
          <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <V2JobCardCompact job={V2_JOBS[1]} />
            <V2JobCardCompact job={V2_JOBS[9]} />
            <V2JobCardCompact job={V2_JOBS[0]} />
          </div>
        </section>

        <section 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 activity</h2>
          </header>
          <div style={{ padding: '8px 22px 14px' }}>
            {[
              ['Applied to Care Assistant · Lavender House', '2h', 'check'],
              ['Saved Senior Care Assistant · Sunrise', '5h', 'bookmark'],
              ['Viewed Care Assistant · Caremark', 'Yesterday', 'eye'],
              ['Updated resume work history', '2 days', 'edit'],
              ['Subscribed to Care assistant Bristol alert', '3 days', 'bell'],
            ].map(([t, when, icon], i, arr) => (
              <div key={i} style={{
                padding: '12px 0', display: 'flex', alignItems: 'center', gap: 10,
                borderBottom: i < arr.length - 1 ? `1px solid ${V2.lineSoft}` : 'none',
                fontSize: 13.5,
              }}>
                <span style={{
                  width: 30, height: 30, borderRadius: 8, background: V2.bgAlt,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <Icon name={icon} size={15} color={V2.muted} />
                </span>
                <span style={{ flex: 1, color: V2.text }}>{t}</span>
                <span style={{ fontSize: 12, color: V2.muted, whiteSpace: 'nowrap' }}>{when} ago</span>
              </div>
            ))}
          </div>
        </section>
      </div>
    </CabShell>
  );
}

// ─── APPLICATIONS ───────────────────────────────────────────────────────
function V2CabApplicationsScreen() {
  const apps = [
    { co: 'Lavender House Care', cat: 'Healthcare', role: 'Care Assistant',          when: '2 hours ago', status: 'Applied',     statusTone: 'info',    next: 'Awaiting reply' },
    { co: 'Sunrise Senior Living', cat: 'Healthcare', role: 'Senior Care Assistant', when: 'Yesterday',   status: 'Reviewed',    statusTone: 'primary', next: 'CV viewed by recruiter' },
    { co: 'Mercury Couriers', cat: 'Driving', role: 'Delivery Driver',               when: '3 days ago',  status: 'Interview',   statusTone: 'success', next: 'Phone screen · Thu 16 May' },
    { co: 'Wren & Co.', cat: 'Retail', role: 'Retail Assistant',                     when: '5 days ago',  status: 'Not selected',statusTone: 'danger',  next: 'You can ask for feedback' },
    { co: 'The Bramley', cat: 'Hospitality', role: 'Hotel Receptionist',             when: '6 days ago',  status: 'Applied',     statusTone: 'info',    next: 'Awaiting reply' },
    { co: 'Bridgewater Logistics', cat: 'Logistics', role: 'Warehouse Operative',    when: '1 week ago',  status: 'Withdrawn',   statusTone: 'neutral', next: 'You withdrew this application' },
  ];
  return (
    <CabShell active="applications" title="Your applications" sub="12 total · 3 awaiting response · 1 interview scheduled">
      <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
        {[['All', 12, true], ['Active', 8], ['Interview', 1], ['Closed', 3]].map(([t, n, on]) => (
          <button key={t} style={{
            padding: '8px 14px', borderRadius: 999, fontSize: 13, fontWeight: 600,
            border: `1px solid ${on ? V2.ink : V2.line}`,
            background: on ? V2.ink : '#fff', color: on ? '#fff' : V2.text,
            cursor: 'pointer', fontFamily: V2.font,
            display: 'inline-flex', alignItems: 'center', gap: 5,
          }}>{t} <span style={{ fontSize: 11, opacity: 0.7 }}>{n}</span></button>
        ))}
      </div>

      <div style={{
        background: '#fff', border: `1px solid ${V2.line}`, borderRadius: V2.rLg, overflow: 'hidden',
      }}>
        {apps.map((a, i, arr) => (
          <div key={i} style={{
            padding: 18, display: 'grid',
            gridTemplateColumns: '1fr 180px 200px 60px', gap: 16, alignItems: 'center',
            borderBottom: i < arr.length - 1 ? `1px solid ${V2.lineSoft}` : 'none',
          }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', minWidth: 0 }}>
              <V2CompanyAvatar name={a.co} category={a.cat} size={40} radius={10} />
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 14.5, fontWeight: 700, color: V2.ink, lineHeight: 1.3 }}>{a.role}</div>
                <div style={{ fontSize: 12.5, color: V2.muted, marginTop: 3 }}>{a.co} · applied {a.when}</div>
              </div>
            </div>
            <V2Badge tone={a.statusTone} size="md">{a.status}</V2Badge>
            <span style={{ fontSize: 13, color: V2.text }}>{a.next}</span>
            <V2Button variant="ghost" size="sm">···</V2Button>
          </div>
        ))}
      </div>
    </CabShell>
  );
}

// ─── BROWSE HISTORY ─────────────────────────────────────────────────────
function V2CabHistoryScreen() {
  return (
    <CabShell active="history" title="Browse history" sub="Jobs you viewed in the last 30 days · groups by day">
      {[
        ['Today',
          [V2_JOBS[1], V2_JOBS[9], V2_JOBS[10]]],
        ['Yesterday',
          [V2_JOBS[0], V2_JOBS[2], V2_JOBS[4]]],
        ['Earlier this week',
          [V2_JOBS[3], V2_JOBS[6], V2_JOBS[7]]],
      ].map(([day, jobs]) => (
        <div key={day} style={{ marginBottom: 26 }}>
          <h2 style={{
            fontSize: 11, fontWeight: 700, color: V2.muted,
            textTransform: 'uppercase', letterSpacing: '0.08em', margin: '0 0 12px',
          }}>{day}</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {jobs.map((j, i) => (
              <a key={i} style={{
                display: 'block', background: '#fff',
                border: `1px solid ${V2.line}`, borderRadius: V2.rLg, padding: 14,
                textDecoration: 'none', color: 'inherit',
              }}>
                <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <V2CompanyAvatar name={j.company} category={j.category} size={40} radius={10} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 700, color: V2.ink }}>{j.title}</div>
                    <div style={{ fontSize: 13, color: V2.muted, marginTop: 2 }}>{j.company} · {j.location} · {j.salary}</div>
                  </div>
                  <span style={{ fontSize: 11.5, color: V2.muted }}>Viewed 2× · 4h ago</span>
                </div>
              </a>
            ))}
          </div>
        </div>
      ))}
    </CabShell>
  );
}

// ─── SETTINGS ───────────────────────────────────────────────────────────
function V2CabSettingsScreen() {
  return (
    <CabShell active="settings" title="Account settings" sub="Profile, password, email preferences and data controls">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 18 }}>
        <SettingsBlock title="Profile">
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <CabFieldCol label="First name"><CabFieldInput value="Emma" /></CabFieldCol>
            <CabFieldCol label="Last name"><CabFieldInput value="Carter" /></CabFieldCol>
          </div>
          <CabFieldCol label="Email" full><CabFieldInput value="emma.carter@example.com" /></CabFieldCol>
          <CabFieldCol label="Phone (optional)" full><CabFieldInput value="+44 7700 900 123" /></CabFieldCol>
          <CabFieldCol label="Location" full><CabFieldInput value="Bristol, UK" /></CabFieldCol>
          <div style={{ marginTop: 8 }}>
            <V2Button variant="primary" size="md">Save changes</V2Button>
          </div>
        </SettingsBlock>

        <SettingsBlock title="Email preferences"
          subtitle="Choose which emails you want and how often.">
          {[
            ['New job alert · Care assistant in Bristol', 'Daily', true, 'New jobs that match your saved search.'],
            ['Saved job updates', 'When relevant', true, "When a saved job's status changes or it's about to expire."],
            ['Application updates', 'Always', true, 'Replies and status changes from employers.'],
            ['Marketing & product news', 'Off', false, 'Occasional updates about new features.'],
          ].map(([label, freq, on, hint]) => (
            <div key={label} style={{
              display: 'grid', gridTemplateColumns: '1fr 120px 44px', gap: 16, alignItems: 'center',
              padding: '14px 0', borderBottom: `1px solid ${V2.lineSoft}`,
            }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 600, color: V2.ink }}>{label}</div>
                <div style={{ fontSize: 12.5, color: V2.muted, marginTop: 2 }}>{hint}</div>
              </div>
              <select defaultValue={freq} style={{
                padding: '8px 10px', border: `1px solid ${V2.line}`, borderRadius: 8,
                fontSize: 13, color: V2.ink, background: '#fff', fontFamily: V2.font, outline: 'none',
              }}>
                {['Always', 'Daily', 'Weekly', 'When relevant', 'Off'].map((x) => <option key={x}>{x}</option>)}
              </select>
              <V2Toggle on={on} />
            </div>
          ))}
        </SettingsBlock>

        <SettingsBlock title="Password & security">
          <CabFieldCol label="New password" full><CabFieldInput value="" /></CabFieldCol>
          <CabFieldCol label="Confirm password" full><CabFieldInput value="" /></CabFieldCol>
          <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13.5, color: V2.text, padding: '8px 0' }}>
            <V2Toggle on />
            Sign-in alerts to my email
          </label>
        </SettingsBlock>

        <SettingsBlock title="Privacy & data" danger>
          <div style={{ display: 'grid', gap: 10 }}>
            <SettingRow t="Download my data"  d="Get a copy of everything we have about your account." cta="Request export" />
            <SettingRow t="Pause my profile"   d="Hide your profile and pause all job alerts. Reactivate any time." cta="Pause" />
            <SettingRow t="Delete account"     d="Permanently delete your account and all associated data after 14 days." cta="Delete" danger />
          </div>
        </SettingsBlock>
      </div>
    </CabShell>
  );
}

function SettingsBlock({ title, subtitle, children, danger }) {
  return (
    <section style={{
      background: '#fff', border: `1px solid ${danger ? V2.dangerLine : V2.line}`,
      borderRadius: V2.rLg, padding: 22,
    }}>
      <header style={{ marginBottom: 16 }}>
        <h2 style={{ margin: '0 0 4px', fontSize: 16, fontWeight: 700, color: V2.ink, letterSpacing: '-0.01em' }}>{title}</h2>
        {subtitle && <p style={{ margin: 0, fontSize: 13, color: V2.muted }}>{subtitle}</p>}
      </header>
      {children}
    </section>
  );
}

function SettingRow({ t, d, cta, danger }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '10px 0' }}>
      <div>
        <div style={{ fontSize: 14, fontWeight: 600, color: V2.ink }}>{t}</div>
        <div style={{ fontSize: 12.5, color: V2.muted, marginTop: 2 }}>{d}</div>
      </div>
      <V2Button variant={danger ? 'destructive' : 'secondary'} size="sm">{cta}</V2Button>
    </div>
  );
}

Object.assign(window, {
  V2CabDashboardScreen, V2CabApplicationsScreen, V2CabHistoryScreen, V2CabSettingsScreen,
});
