// account-pages.jsx — Onboarding, Settings, Forgot password, Verify email, 404

const { useState: _useStateA } = React;

// ────────────────────────────────────────────
// Onboarding — 3 steps
// ────────────────────────────────────────────
function OnboardingPage({ t, str, dark, lang, setLang, navigate }) {
  const [step, setStep] = React.useState(0);
  const [nick, setNick] = React.useState('');
  const [genres, setGenres] = React.useState([]);
  const [avatar, setAvatar] = React.useState(0);

  const steps = [
    lang === 'ru' ? 'Никнейм' : 'Username',
    lang === 'ru' ? 'Что любишь' : 'Your taste',
    lang === 'ru' ? 'Аватар' : 'Avatar',
  ];
  const total = steps.length;

  const allGenres = [
    { k: 'obby',   ru: 'Obby',    en: 'Obby',    hue: 18 },
    { k: 'sim',    ru: 'Симы',    en: 'Sim',     hue: 120 },
    { k: 'rpg',    ru: 'RPG',     en: 'RPG',     hue: 200 },
    { k: 'racing', ru: 'Гонки',   en: 'Racing',  hue: 285 },
    { k: 'horror', ru: 'Хоррор',  en: 'Horror',  hue: 0 },
    { k: 'tycoon', ru: 'Tycoon',  en: 'Tycoon',  hue: 50 },
  ];

  const toggleGenre = (k) => setGenres(g => g.includes(k) ? g.filter(x => x !== k) : [...g, k]);

  const next = () => step < total - 1 ? setStep(step + 1) : navigate('home');
  const prev = () => step > 0 ? setStep(step - 1) : navigate('home');

  const canNext = step === 0 ? nick.trim().length >= 3 : step === 1 ? genres.length >= 1 : true;

  return (
    <div style={{ background: t.bg, color: t.text, fontFamily: '"Inter", system-ui, sans-serif', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      {/* Top bar */}
      <div style={{ padding: '24px 28px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div onClick={() => navigate('home')} style={{ cursor: 'pointer' }}>
          <Logo dark={dark} />
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              width: i === step ? 32 : 18, height: 4, borderRadius: 2,
              background: i <= step ? t.accent : t.border,
              transition: 'all 0.25s',
            }} />
          ))}
        </div>
        <button onClick={() => navigate('home')} style={{
          background: 'transparent', border: 'none', color: t.muted, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
        }}>{lang === 'ru' ? 'Пропустить' : 'Skip'}</button>
      </div>

      {/* Body */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px 28px' }}>
        <div style={{ width: '100%', maxWidth: 560 }}>
          <div style={{ fontSize: 11, color: t.muted, fontFamily: 'ui-monospace, monospace', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 14 }}>
            {String(step + 1).padStart(2, '0')} / {String(total).padStart(2, '0')} · {steps[step]}
          </div>

          {step === 0 && (
            <React.Fragment>
              <h1 style={{ margin: 0, fontFamily: '"Inter Tight", sans-serif', fontSize: 56, fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1.02 }}>
                {lang === 'ru' ? 'Как тебя называть?' : 'What should we call you?'}
              </h1>
              <p style={{ marginTop: 14, fontSize: 15, color: t.muted, lineHeight: 1.55 }}>
                {lang === 'ru' ? 'Никнейм видят все. Поменять можно один раз — потом навсегда.' : 'Everyone sees this. You get one rename — then it sticks.'}
              </p>
              <div style={{ marginTop: 32, position: 'relative' }}>
                <input
                  value={nick} onChange={(e) => setNick(e.target.value.replace(/[^a-zA-Z0-9_]/g, '').slice(0, 20))}
                  placeholder="craftix_player"
                  style={{
                    width: '100%', height: 64, padding: '0 80px 0 22px',
                    background: t.surface, border: `1px solid ${t.border}`, borderRadius: 14,
                    color: t.text, fontSize: 22, outline: 'none',
                    fontFamily: '"JetBrains Mono", ui-monospace, monospace',
                  }}
                  onFocus={(e) => e.target.style.borderColor = t.text}
                  onBlur={(e) => e.target.style.borderColor = t.border}
                />
                <div style={{
                  position: 'absolute', right: 16, top: 0, height: 64,
                  display: 'flex', alignItems: 'center',
                  fontFamily: 'ui-monospace, monospace', fontSize: 11, color: t.faint,
                }}>{nick.length}/20</div>
              </div>
              <div style={{ marginTop: 12, fontSize: 12, color: t.faint, fontFamily: 'ui-monospace, monospace' }}>
                {lang === 'ru' ? 'a-z, 0-9, _ · от 3 символов' : 'a-z, 0-9, _ · 3+ chars'}
              </div>
            </React.Fragment>
          )}

          {step === 1 && (
            <React.Fragment>
              <h1 style={{ margin: 0, fontFamily: '"Inter Tight", sans-serif', fontSize: 56, fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1.02 }}>
                {lang === 'ru' ? 'Что тебе зайдёт?' : 'What\u2019s your thing?'}
              </h1>
              <p style={{ marginTop: 14, fontSize: 15, color: t.muted, lineHeight: 1.55 }}>
                {lang === 'ru' ? 'Выбери хотя бы один. Подкрутим ленту под тебя.' : 'Pick at least one. We\u2019ll tune your feed.'}
              </p>
              <div style={{ marginTop: 32, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                {allGenres.map(g => {
                  const on = genres.includes(g.k);
                  return (
                    <button key={g.k} onClick={() => toggleGenre(g.k)} style={{
                      position: 'relative', overflow: 'hidden',
                      aspectRatio: '1.2', borderRadius: 14, cursor: 'pointer',
                      border: `2px solid ${on ? t.text : t.border}`,
                      background: t.surface, padding: 0,
                      transition: 'transform 0.1s',
                      transform: on ? 'scale(0.98)' : 'scale(1)',
                    }}>
                      <Placeholder hue={g.hue} pattern={['stripes','grid','dots','noise','stripes','grid'][allGenres.indexOf(g)]} dark={dark} radius={12} />
                      <div style={{
                        position: 'absolute', inset: 0,
                        background: dark ? 'linear-gradient(0deg, rgba(0,0,0,0.7), transparent 60%)' : 'linear-gradient(0deg, rgba(255,255,255,0.85), transparent 60%)',
                        display: 'flex', alignItems: 'flex-end', padding: 14,
                        fontFamily: '"Inter Tight", sans-serif', fontSize: 18, fontWeight: 600, color: t.text,
                      }}>{lang === 'ru' ? g.ru : g.en}</div>
                      {on && (
                        <div style={{
                          position: 'absolute', top: 10, right: 10,
                          width: 24, height: 24, borderRadius: 12, background: t.accent, color: t.accentInk,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontSize: 14, fontWeight: 700,
                        }}>✓</div>
                      )}
                    </button>
                  );
                })}
              </div>
            </React.Fragment>
          )}

          {step === 2 && (
            <React.Fragment>
              <h1 style={{ margin: 0, fontFamily: '"Inter Tight", sans-serif', fontSize: 56, fontWeight: 700, letterSpacing: '-0.035em', lineHeight: 1.02 }}>
                {lang === 'ru' ? 'Выбери лицо.' : 'Pick a face.'}
              </h1>
              <p style={{ marginTop: 14, fontSize: 15, color: t.muted, lineHeight: 1.55 }}>
                {lang === 'ru' ? 'Загрузишь свой позже в настройках.' : 'Upload your own later in settings.'}
              </p>
              <div style={{ marginTop: 32, display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10 }}>
                {[18, 50, 120, 200, 285, 340, 30, 90, 160, 250, 310, 0].map((hue, i) => (
                  <button key={i} onClick={() => setAvatar(i)} style={{
                    aspectRatio: '1', borderRadius: '50%', cursor: 'pointer', padding: 0, overflow: 'hidden',
                    border: `3px solid ${avatar === i ? t.text : 'transparent'}`,
                    background: 'transparent',
                    transform: avatar === i ? 'scale(1)' : 'scale(0.92)',
                    transition: 'all 0.15s',
                  }}>
                    <Placeholder hue={hue} pattern={['dots','stripes','grid','noise','dots','stripes','grid','noise','dots','stripes','grid','noise'][i]} dark={dark} radius={999} />
                  </button>
                ))}
              </div>
              <div style={{ marginTop: 24, padding: 16, background: t.surface, border: `1px dashed ${t.border}`, borderRadius: 12, textAlign: 'center', fontSize: 13, color: t.muted, cursor: 'pointer' }}>
                ↑ {lang === 'ru' ? 'Загрузить своё фото (необязательно)' : 'Upload your own (optional)'}
              </div>
            </React.Fragment>
          )}
        </div>
      </div>

      {/* Footer nav */}
      <div style={{
        padding: '20px 28px', borderTop: `1px solid ${t.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <button onClick={prev} style={{
          padding: '10px 16px', background: 'transparent', border: 'none', color: t.muted,
          fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
        }}>← {step === 0 ? (lang === 'ru' ? 'На главную' : 'Home') : (lang === 'ru' ? 'Назад' : 'Back')}</button>
        <Btn t={t} kind={canNext ? 'primary' : 'outline'} size="lg" onClick={canNext ? next : undefined}>
          {step === total - 1 ? (lang === 'ru' ? 'Поехали →' : 'Let\u2019s go →') : (lang === 'ru' ? 'Дальше →' : 'Continue →')}
        </Btn>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────
// Settings — tabs
// ────────────────────────────────────────────
function SettingsPage({ t, str, dark, lang, setLang, navigate }) {
  const [tab, setTab] = React.useState('profile');
  const tabs = [
    { k: 'profile',  ru: 'Профиль',      en: 'Profile' },
    { k: 'account',  ru: 'Аккаунт',      en: 'Account' },
    { k: 'security', ru: 'Безопасность', en: 'Security' },
    { k: 'notifs',   ru: 'Уведомления',  en: 'Notifications' },
    { k: 'privacy',  ru: 'Приватность',  en: 'Privacy' },
  ];

  return (
    <div style={{ background: t.bg, color: t.text, fontFamily: '"Inter", system-ui, sans-serif', minHeight: '100vh' }}>
      <Nav t={t} str={str} dark={dark} lang={lang} setLang={setLang} active="community" navigate={navigate} />

      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '40px 28px 80px' }}>
        <div style={{ fontSize: 11, color: t.faint, fontFamily: 'ui-monospace, monospace', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8 }}>
          {lang === 'ru' ? 'Аккаунт' : 'Account'}
        </div>
        <h1 style={{ margin: 0, fontFamily: '"Inter Tight", sans-serif', fontSize: 48, fontWeight: 700, letterSpacing: '-0.03em' }}>
          {lang === 'ru' ? 'Настройки' : 'Settings'}
        </h1>

        <div style={{ marginTop: 36, display: 'grid', gridTemplateColumns: '200px 1fr', gap: 40 }}>
          <aside>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
              {tabs.map(x => (
                <button key={x.k} onClick={() => setTab(x.k)} style={{
                  padding: '10px 12px', borderRadius: 8, border: 'none', cursor: 'pointer', textAlign: 'left',
                  background: tab === x.k ? t.surface2 : 'transparent',
                  color: tab === x.k ? t.text : t.muted,
                  fontSize: 14, fontWeight: 500, fontFamily: 'inherit',
                }}>{lang === 'ru' ? x.ru : x.en}</button>
              ))}
            </div>
            <div style={{ marginTop: 24, padding: 14, border: `1px dashed ${t.border}`, borderRadius: 10, fontSize: 12, color: t.muted, lineHeight: 1.55 }}>
              {lang === 'ru' ? 'Смена пароля и удаление — во вкладке Безопасность.' : 'Password & delete are in Security.'}
            </div>
          </aside>

          <div>
            {tab === 'profile' && <ProfileSettings t={t} lang={lang} dark={dark} />}
            {tab === 'account' && <AccountSettings t={t} lang={lang} />}
            {tab === 'security' && <SecuritySettings t={t} lang={lang} />}
            {tab === 'notifs' && <NotifSettings t={t} lang={lang} />}
            {tab === 'privacy' && <PrivacySettings t={t} lang={lang} />}
          </div>
        </div>
      </div>
    </div>
  );
}

function SettingsCard({ t, title, sub, children, danger }) {
  return (
    <div style={{
      padding: 24, marginBottom: 16,
      background: t.surface, border: `1px solid ${danger ? 'oklch(60% 0.18 25)' : t.border}`, borderRadius: 14,
    }}>
      <div style={{ fontFamily: '"Inter Tight", sans-serif', fontSize: 18, fontWeight: 600, color: danger ? 'oklch(60% 0.18 25)' : t.text }}>{title}</div>
      {sub && <div style={{ marginTop: 4, fontSize: 13, color: t.muted, lineHeight: 1.55 }}>{sub}</div>}
      <div style={{ marginTop: 16 }}>{children}</div>
    </div>
  );
}

function Row({ t, label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
      <span style={{ fontSize: 11, color: t.muted, fontFamily: 'ui-monospace, monospace', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</span>
      {children}
    </div>
  );
}
function Inp({ t, value, onChange, placeholder, mono, type = 'text' }) {
  return (
    <input
      type={type} value={value} onChange={(e) => onChange && onChange(e.target.value)} placeholder={placeholder}
      style={{
        height: 40, padding: '0 14px',
        background: t.bg, border: `1px solid ${t.border}`, borderRadius: 10,
        color: t.text, fontSize: 14, outline: 'none',
        fontFamily: mono ? '"JetBrains Mono", ui-monospace, monospace' : 'inherit',
      }}
      onFocus={(e) => e.target.style.borderColor = t.text}
      onBlur={(e) => e.target.style.borderColor = t.border}
    />
  );
}

function ProfileSettings({ t, lang, dark }) {
  const [nick, setNick] = React.useState('craftix_player');
  const [bio, setBio] = React.useState('');
  return (
    <React.Fragment>
      <SettingsCard t={t} title={lang === 'ru' ? 'Аватар' : 'Avatar'}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{ width: 80, height: 80, borderRadius: 16, overflow: 'hidden' }}>
            <Placeholder hue={285} pattern="dots" dark={dark} radius={16} label="me" />
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn t={t} kind="outline" size="md">{lang === 'ru' ? 'Загрузить' : 'Upload'}</Btn>
            <Btn t={t} kind="ghost" size="md">{lang === 'ru' ? 'Удалить' : 'Remove'}</Btn>
          </div>
        </div>
      </SettingsCard>

      <SettingsCard t={t} title={lang === 'ru' ? 'Профиль' : 'Profile'} sub={lang === 'ru' ? 'Эти данные видны другим.' : 'Visible to others.'}>
        <Row t={t} label={lang === 'ru' ? 'Никнейм' : 'Username'}><Inp t={t} value={nick} onChange={setNick} mono /></Row>
        <Row t={t} label={lang === 'ru' ? 'Био' : 'Bio'}>
          <textarea value={bio} onChange={(e) => setBio(e.target.value.slice(0, 160))} placeholder={lang === 'ru' ? 'Пара слов о себе…' : 'A few words about yourself…'} style={{
            minHeight: 80, padding: 12, background: t.bg, border: `1px solid ${t.border}`, borderRadius: 10,
            color: t.text, fontSize: 14, fontFamily: 'inherit', outline: 'none', resize: 'vertical',
          }} />
          <div style={{ marginTop: 4, fontSize: 11, color: t.faint, fontFamily: 'ui-monospace, monospace', textAlign: 'right' }}>{bio.length}/160</div>
        </Row>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <Btn t={t} kind="ghost" size="md">{lang === 'ru' ? 'Отменить' : 'Cancel'}</Btn>
          <Btn t={t} kind="primary" size="md">{lang === 'ru' ? 'Сохранить' : 'Save'}</Btn>
        </div>
      </SettingsCard>
    </React.Fragment>
  );
}

function AccountSettings({ t, lang }) {
  return (
    <React.Fragment>
      <SettingsCard t={t} title="Email" sub={lang === 'ru' ? 'Используется для входа и восстановления.' : 'Used for sign-in and recovery.'}>
        <Row t={t} label="Email"><Inp t={t} value="" placeholder="you@craftix.dev" /></Row>
        <Btn t={t} kind="primary" size="md">{lang === 'ru' ? 'Подтвердить смену' : 'Confirm change'}</Btn>
      </SettingsCard>
      <SettingsCard t={t} title={lang === 'ru' ? 'Язык и регион' : 'Language & region'}>
        <Row t={t} label={lang === 'ru' ? 'Язык интерфейса' : 'Interface language'}>
          <select style={{
            height: 40, padding: '0 14px', background: t.bg, border: `1px solid ${t.border}`, borderRadius: 10,
            color: t.text, fontSize: 14, fontFamily: 'inherit',
          }}>
            <option>English</option><option>Русский</option>
          </select>
        </Row>
      </SettingsCard>
    </React.Fragment>
  );
}

function SecuritySettings({ t, lang }) {
  return (
    <React.Fragment>
      <SettingsCard t={t} title={lang === 'ru' ? 'Пароль' : 'Password'}>
        <Row t={t} label={lang === 'ru' ? 'Текущий пароль' : 'Current password'}><Inp t={t} value="" type="password" placeholder="••••••••" /></Row>
        <Row t={t} label={lang === 'ru' ? 'Новый пароль' : 'New password'}><Inp t={t} value="" type="password" placeholder="••••••••" /></Row>
        <Btn t={t} kind="primary" size="md">{lang === 'ru' ? 'Обновить пароль' : 'Update password'}</Btn>
      </SettingsCard>
      <SettingsCard t={t} title={lang === 'ru' ? 'Двухфакторная аутентификация' : 'Two-factor auth'} sub={lang === 'ru' ? 'Дополнительный код при входе с нового устройства.' : 'Extra code when signing in from a new device.'}>
        <Btn t={t} kind="outline" size="md">{lang === 'ru' ? 'Включить 2FA' : 'Enable 2FA'}</Btn>
      </SettingsCard>
      <SettingsCard t={t} title={lang === 'ru' ? 'Активные сессии' : 'Active sessions'}>
        <EmptyState t={t} height={140}
          title={lang === 'ru' ? 'Только эта сессия' : 'Just this session'}
          sub={lang === 'ru' ? 'Войди с другого устройства, чтобы увидеть его здесь.' : 'Sign in from another device to see it here.'} />
      </SettingsCard>
      <SettingsCard t={t} title={lang === 'ru' ? 'Удалить аккаунт' : 'Delete account'} sub={lang === 'ru' ? 'Безвозвратно. 14 дней grace-периода.' : 'Permanent. 14-day grace period.'} danger>
        <Btn t={t} kind="outline" size="md">{lang === 'ru' ? 'Удалить мой аккаунт' : 'Delete my account'}</Btn>
      </SettingsCard>
    </React.Fragment>
  );
}

function NotifSettings({ t, lang }) {
  const items = [
    [lang === 'ru' ? 'Друзья онлайн' : 'Friend online', true],
    [lang === 'ru' ? 'Сообщения' : 'Direct messages', true],
    [lang === 'ru' ? 'Обновления подписок' : 'Following updates', false],
    [lang === 'ru' ? 'Маркетинг' : 'Marketing emails', false],
  ];
  return (
    <SettingsCard t={t} title={lang === 'ru' ? 'Уведомления' : 'Notifications'}>
      {items.map(([label, def], i) => (
        <NotifRow key={i} t={t} label={label} def={def} last={i === items.length - 1} />
      ))}
    </SettingsCard>
  );
}
function NotifRow({ t, label, def, last }) {
  const [on, setOn] = React.useState(def);
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 0', borderBottom: last ? 'none' : `1px solid ${t.border}` }}>
      <span style={{ fontSize: 14 }}>{label}</span>
      <button onClick={() => setOn(!on)} style={{
        width: 40, height: 22, borderRadius: 12, border: 'none', cursor: 'pointer', position: 'relative',
        background: on ? t.text : t.border, transition: 'background 0.15s',
      }}>
        <div style={{
          position: 'absolute', top: 2, left: on ? 20 : 2,
          width: 18, height: 18, borderRadius: 9, background: t.bg, transition: 'left 0.15s',
        }} />
      </button>
    </div>
  );
}

function PrivacySettings({ t, lang }) {
  return (
    <React.Fragment>
      <SettingsCard t={t} title={lang === 'ru' ? 'Кто видит профиль' : 'Profile visibility'}>
        <Row t={t} label={lang === 'ru' ? 'Видимость' : 'Visibility'}>
          <select style={{
            height: 40, padding: '0 14px', background: t.bg, border: `1px solid ${t.border}`, borderRadius: 10,
            color: t.text, fontSize: 14, fontFamily: 'inherit',
          }}>
            <option>{lang === 'ru' ? 'Все' : 'Everyone'}</option>
            <option>{lang === 'ru' ? 'Только друзья' : 'Friends only'}</option>
            <option>{lang === 'ru' ? 'Никто' : 'No one'}</option>
          </select>
        </Row>
      </SettingsCard>
      <SettingsCard t={t} title={lang === 'ru' ? 'Скачать данные' : 'Download your data'} sub={lang === 'ru' ? 'JSON архив всех твоих данных.' : 'JSON archive of everything we have.'}>
        <Btn t={t} kind="outline" size="md">{lang === 'ru' ? 'Запросить архив' : 'Request archive'}</Btn>
      </SettingsCard>
    </React.Fragment>
  );
}

// ────────────────────────────────────────────
// Forgot password
// ────────────────────────────────────────────
function ForgotPage({ t, str, dark, lang, setLang, navigate }) {
  const [email, setEmail] = React.useState('');
  const [sent, setSent] = React.useState(false);

  return (
    <div style={{ background: t.bg, color: t.text, fontFamily: '"Inter", system-ui, sans-serif', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '24px 28px' }}>
        <div onClick={() => navigate('home')} style={{ cursor: 'pointer', display: 'inline-block' }}>
          <Logo dark={dark} />
        </div>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px 28px 60px' }}>
        <div style={{ width: '100%', maxWidth: 420 }}>
          {!sent ? (
            <React.Fragment>
              <div style={{ fontSize: 11, color: t.muted, fontFamily: 'ui-monospace, monospace', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 14 }}>
                {lang === 'ru' ? 'Восстановление' : 'Recovery'}
              </div>
              <h1 style={{ margin: 0, fontFamily: '"Inter Tight", sans-serif', fontSize: 44, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.05 }}>
                {lang === 'ru' ? 'Забыл пароль.' : 'Forgot password.'}
              </h1>
              <p style={{ marginTop: 10, fontSize: 14, color: t.muted, lineHeight: 1.55 }}>
                {lang === 'ru' ? 'Пришлём ссылку на сброс на твой email.' : 'We\u2019ll email you a reset link.'}
              </p>
              <div style={{ marginTop: 28 }}>
                <Field t={t} label="Email" value={email} onChange={setEmail} placeholder="you@craftix.dev" />
              </div>
              <Btn t={t} kind="primary" size="lg" fullWidth style={{ marginTop: 18 }} onClick={() => setSent(true)}>
                {lang === 'ru' ? 'Отправить ссылку' : 'Send reset link'}
              </Btn>
              <div style={{ marginTop: 20, fontSize: 13, color: t.muted, textAlign: 'center' }}>
                {lang === 'ru' ? 'Вспомнил? ' : 'Remembered? '}
                <span onClick={() => navigate('auth')} style={{ color: t.text, textDecoration: 'underline', cursor: 'pointer', fontWeight: 500 }}>
                  {lang === 'ru' ? 'Войти' : 'Sign in'}
                </span>
              </div>
            </React.Fragment>
          ) : (
            <div style={{ textAlign: 'center' }}>
              <div style={{
                width: 64, height: 64, borderRadius: 16, background: t.accent, color: t.accentInk,
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 28, marginBottom: 24,
              }}>✓</div>
              <h1 style={{ margin: 0, fontFamily: '"Inter Tight", sans-serif', fontSize: 36, fontWeight: 700, letterSpacing: '-0.025em' }}>
                {lang === 'ru' ? 'Проверь почту.' : 'Check your inbox.'}
              </h1>
              <p style={{ marginTop: 12, fontSize: 14, color: t.muted, lineHeight: 1.6 }}>
                {lang === 'ru' ? 'Отправили ссылку на ' : 'We sent a link to '}
                <span style={{ color: t.text, fontFamily: 'ui-monospace, monospace' }}>{email || 'your@email'}</span>.
                {lang === 'ru' ? ' Ссылка работает 1 час.' : ' Link expires in 1 hour.'}
              </p>
              <div style={{ marginTop: 28, display: 'flex', flexDirection: 'column', gap: 8 }}>
                <Btn t={t} kind="outline" size="md" fullWidth onClick={() => setSent(false)}>
                  {lang === 'ru' ? 'Отправить ещё раз' : 'Send again'}
                </Btn>
                <Btn t={t} kind="ghost" size="md" fullWidth onClick={() => navigate('auth')}>
                  {lang === 'ru' ? '← К входу' : '← Back to sign in'}
                </Btn>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────
// Verify email
// ────────────────────────────────────────────
function VerifyPage({ t, str, dark, lang, setLang, navigate }) {
  const [code, setCode] = React.useState(['', '', '', '', '', '']);
  const refs = React.useRef([]);
  const setDigit = (i, v) => {
    const d = v.replace(/\D/g, '').slice(-1);
    setCode(c => { const n = [...c]; n[i] = d; return n; });
    if (d && i < 5) refs.current[i + 1]?.focus();
  };
  const filled = code.every(d => d);

  return (
    <div style={{ background: t.bg, color: t.text, fontFamily: '"Inter", system-ui, sans-serif', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '24px 28px' }}>
        <div onClick={() => navigate('home')} style={{ cursor: 'pointer', display: 'inline-block' }}>
          <Logo dark={dark} />
        </div>
      </div>
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '20px 28px 60px' }}>
        <div style={{ width: '100%', maxWidth: 480, textAlign: 'center' }}>
          <div style={{ fontSize: 11, color: t.muted, fontFamily: 'ui-monospace, monospace', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 14 }}>
            {lang === 'ru' ? 'Подтверждение email' : 'Verify your email'}
          </div>
          <h1 style={{ margin: 0, fontFamily: '"Inter Tight", sans-serif', fontSize: 44, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.05 }}>
            {lang === 'ru' ? 'Мы прислали код.' : 'We sent a code.'}
          </h1>
          <p style={{ marginTop: 10, fontSize: 14, color: t.muted, lineHeight: 1.55 }}>
            {lang === 'ru' ? 'Введи 6-значный код из письма.' : 'Enter the 6-digit code from your inbox.'}
          </p>
          <div style={{ marginTop: 36, display: 'flex', gap: 10, justifyContent: 'center' }}>
            {code.map((d, i) => (
              <input
                key={i}
                ref={(el) => refs.current[i] = el}
                value={d}
                onChange={(e) => setDigit(i, e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Backspace' && !d && i > 0) refs.current[i - 1]?.focus();
                }}
                maxLength={1}
                inputMode="numeric"
                style={{
                  width: 56, height: 64, textAlign: 'center',
                  background: t.surface, border: `2px solid ${d ? t.text : t.border}`, borderRadius: 12,
                  color: t.text, fontSize: 28, fontFamily: '"JetBrains Mono", ui-monospace, monospace',
                  outline: 'none', fontWeight: 600,
                }}
              />
            ))}
          </div>
          <Btn t={t} kind={filled ? 'primary' : 'outline'} size="lg" fullWidth style={{ marginTop: 32 }} onClick={() => filled && navigate('onboarding')}>
            {lang === 'ru' ? 'Подтвердить' : 'Verify'}
          </Btn>
          <div style={{ marginTop: 20, fontSize: 13, color: t.muted }}>
            {lang === 'ru' ? 'Не пришло? ' : 'Didn\u2019t get it? '}
            <span style={{ color: t.text, textDecoration: 'underline', cursor: 'pointer', fontWeight: 500 }}>
              {lang === 'ru' ? 'Отправить ещё раз' : 'Resend'}
            </span>
            <span style={{ color: t.faint, fontFamily: 'ui-monospace, monospace', marginLeft: 8 }}>00:42</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────
// 404 — playful
// ────────────────────────────────────────────
function NotFoundPage({ t, str, dark, lang, setLang, navigate }) {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(x => x + 1), 80);
    return () => clearInterval(id);
  }, []);

  return (
    <div style={{ background: t.bg, color: t.text, fontFamily: '"Inter", system-ui, sans-serif', minHeight: '100vh', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '24px 28px' }}>
        <div onClick={() => navigate('home')} style={{ cursor: 'pointer', display: 'inline-block' }}>
          <Logo dark={dark} />
        </div>
      </div>
      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 40, alignItems: 'center', maxWidth: 1280, margin: '0 auto', padding: '0 28px', width: '100%' }}>
        <div>
          <div style={{ fontSize: 11, color: t.muted, fontFamily: 'ui-monospace, monospace', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 14 }}>
            error · 404
          </div>
          <h1 style={{
            margin: 0, fontFamily: '"Inter Tight", sans-serif',
            fontSize: 'clamp(80px, 14vw, 200px)', lineHeight: 0.85, fontWeight: 700, letterSpacing: '-0.05em',
          }}>
            {lang === 'ru' ? 'Тут' : 'Out of'}<br />
            <span style={{ background: t.accent, color: t.accentInk, padding: '0 12px', borderRadius: 16 }}>
              {lang === 'ru' ? 'пусто.' : 'bounds.'}
            </span>
          </h1>
          <p style={{ marginTop: 24, fontSize: 17, color: t.muted, lineHeight: 1.55, maxWidth: 460 }}>
            {lang === 'ru'
              ? 'Эта страница ещё не существует — или больше не существует. Бывает.'
              : 'This page doesn\u2019t exist — or doesn\u2019t exist anymore. Happens.'}
          </p>
          <div style={{ marginTop: 28, display: 'flex', gap: 10 }}>
            <Btn t={t} kind="primary" size="lg" onClick={() => navigate('home')}>← {lang === 'ru' ? 'На главную' : 'Take me home'}</Btn>
            <Btn t={t} kind="outline" size="lg" onClick={() => navigate('catalog')}>{lang === 'ru' ? 'Каталог' : 'Catalog'} →</Btn>
          </div>
        </div>
        <div style={{ position: 'relative', height: 460 }}>
          {[18, 50, 200, 285].map((hue, i) => {
            const positions = [
              { x: 60,  y: 40,  w: 180, h: 180, r: 4 },
              { x: 240, y: 100, w: 140, h: 140, r: -3 },
              { x: 30,  y: 240, w: 160, h: 160, r: 2 },
              { x: 220, y: 280, w: 150, h: 150, r: -5 },
            ][i];
            return (
              <div key={i} style={{
                position: 'absolute', left: positions.x, top: positions.y,
                width: positions.w, height: positions.h,
                transform: `rotate(${positions.r + Math.sin((tick + i * 50) / 30) * 4}deg) translateY(${Math.sin((tick + i * 30) / 25) * 8}px)`,
                transition: 'transform 0.08s',
                filter: 'blur(0.5px)',
                opacity: 0.6,
              }}>
                <Placeholder hue={hue} pattern={['stripes','grid','dots','noise'][i]} dark={dark} radius={14} label="?" />
              </div>
            );
          })}
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: '"JetBrains Mono", ui-monospace, monospace',
            fontSize: 280, fontWeight: 700, color: t.text, opacity: 0.06, letterSpacing: '-0.05em',
          }}>404</div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OnboardingPage, SettingsPage, ForgotPage, VerifyPage, NotFoundPage });
