// Aux screens: Splash, Onboarding 1-3, Pair vehicle, Trip history,
// Dealer locator, Owner's manual.

const t3 = THEMES.c;

// ─────────────────────────────────────────────────────────────
// SPLASH — brief mark, auto-advances to login
// ─────────────────────────────────────────────────────────────
function SplashScreen() {
  const nav = useRouter();
  const { tw } = useApp();
  const L = STRINGS[tw.lang];
  React.useEffect(() => {
    const tm = setTimeout(() => nav.replace('login'), 1700);
    return () => clearTimeout(tm);
  }, []);
  return (
    <div onClick={() => nav.replace('login')}
         style={{ width: '100%', height: '100%', background: t3.bg, color: t3.text, fontFamily: t3.font, position: 'relative', overflow: 'hidden', cursor: 'pointer' }}>
      <Aurora intensity={Math.max(1, tw.aurora)}/>
      <div style={{ position: 'absolute', top: '38%', left: 0, right: 0, textAlign: 'center', transform: 'translateY(-50%)' }}>
        <div style={{ display: 'flex', justifyContent: 'center', color: '#fff' }}>
          <Logo size={96}/>
        </div>
        <div style={{ fontSize: 32, fontWeight: 300, letterSpacing: -1.2, marginTop: 28 }}>Mazda Connect</div>
        <div style={{ fontSize: 11, color: t3.textDim, marginTop: 12, letterSpacing: 4, fontFamily: t3.mono }}>{T(tw.lang, 'VIETNAM', 'VIỆT NAM')}</div>
      </div>
      <div style={{ position: 'absolute', bottom: 50, left: 0, right: 0, textAlign: 'center', fontSize: 10, color: t3.textMute, fontFamily: t3.mono, letterSpacing: 2 }}>
        © THACO · {T(tw.lang, 'MAZDA VIETNAM', 'MAZDA VIỆT NAM')}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// LOGIN — full sign-in screen
// ─────────────────────────────────────────────────────────────
function LoginScreen() {
  const nav = useRouter();
  const { tw } = useApp();
  const L = STRINGS[tw.lang];
  const [mode, setMode] = React.useState('phone');         // 'phone' | 'email'
  const [phone, setPhone] = React.useState('912 84 02 19');
  const [emailV, setEmailV] = React.useState('an.nguyen@gmail.com');
  const [pwd, setPwd] = React.useState('mazda2026!');
  const [showPwd, setShowPwd] = React.useState(false);
  const [remember, setRemember] = React.useState(true);
  const [loading, setLoading] = React.useState(false);

  const valid = mode === 'phone'
    ? phone.replace(/\s/g, '').length >= 9 && pwd.length >= 6
    : /@/.test(emailV) && pwd.length >= 6;

  const submit = () => {
    if (!valid || loading) return;
    setLoading(true);
    setTimeout(() => { setLoading(false); nav.replace('home', 'home'); }, 900);
  };

  return (
    <div style={{ width: '100%', height: '100%', background: t3.bg, color: t3.text, fontFamily: t3.font, position: 'relative', overflow: 'hidden' }}>
      <Aurora intensity={tw.aurora}/>

      <div style={{ position: 'absolute', top: 80, left: 0, right: 0, textAlign: 'center', animation: 'c-fade-in .5s forwards' }}>
        <div style={{ display: 'flex', justifyContent: 'center', color: '#fff' }}>
          <Logo size={64}/>
        </div>
        <div style={{ fontSize: 22, fontWeight: 400, letterSpacing: -0.4, marginTop: 18 }}>{L.welcomeBack}</div>
        <div style={{ fontSize: 13, color: t3.textDim, marginTop: 4 }}>{L.signInVietnam}</div>
      </div>

      <div style={{ position: 'absolute', top: 240, left: 24, right: 24, animation: 'c-fade-in .5s .1s forwards' }}>
        {/* Phone | Email tab */}
        <div style={{ display: 'flex', padding: 4, borderRadius: 14, background: 'rgba(255,255,255,0.05)', marginBottom: 16 }}>
          {[{ k: 'phone', l: L.loginPhoneTab }, { k: 'email', l: L.loginEmailTab }].map((tab) => (
            <div key={tab.k} onClick={() => setMode(tab.k)}
                 style={{ flex: 1, padding: '10px 0', textAlign: 'center', borderRadius: 10, fontSize: 13, fontWeight: 500, cursor: 'pointer',
                          background: mode === tab.k ? t3.accent : 'transparent',
                          color: mode === tab.k ? t3.accentInk : t3.textDim, transition: 'all .2s' }}>{tab.l}</div>
          ))}
        </div>

        {/* Form */}
        <GlassC padding={0} radius={20} intensity={tw.glass} style={{ overflow: 'visible' }}>
          {mode === 'phone' ? (
            <div style={{ display: 'flex', alignItems: 'center', height: 56, padding: '0 6px' }}>
              <div style={{ display: 'flex', alignItems: 'center', height: 40, padding: '0 12px', borderRadius: 12, background: 'rgba(212,165,116,0.14)', color: t3.accent, fontSize: 13, fontWeight: 600, gap: 6 }}>
                🇻🇳 +84
              </div>
              <input value={phone} onChange={(e) => setPhone(e.target.value)}
                     placeholder="912 345 678"
                     style={{ flex: 1, height: 40, marginLeft: 8, padding: '0 14px', border: 'none',
                              background: 'transparent', color: t3.text, fontSize: 16, fontFamily: t3.font,
                              fontVariantNumeric: 'tabular-nums', outline: 'none' }}/>
            </div>
          ) : (
            <div style={{ display: 'flex', alignItems: 'center', height: 56, padding: '0 6px' }}>
              <div style={{ width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t3.textDim, marginLeft: 6 }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 6 9-6"/></svg>
              </div>
              <input type="email" value={emailV} onChange={(e) => setEmailV(e.target.value)}
                     placeholder="you@example.com"
                     style={{ flex: 1, height: 40, marginLeft: 4, padding: '0 14px', border: 'none',
                              background: 'transparent', color: t3.text, fontSize: 16, fontFamily: t3.font,
                              outline: 'none' }}/>
            </div>
          )}
          <div style={{ height: 1, background: 'rgba(255,255,255,0.05)' }}/>
          <div style={{ display: 'flex', alignItems: 'center', height: 56, padding: '0 6px' }}>
            <div style={{ width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t3.textDim, marginLeft: 6 }}>
              <Icons.lock size={20} stroke={1.6}/>
            </div>
            <input type={showPwd ? 'text' : 'password'} value={pwd} onChange={(e) => setPwd(e.target.value)}
                   placeholder={L.pwd}
                   style={{ flex: 1, height: 40, marginLeft: 4, padding: '0 14px', border: 'none',
                            background: 'transparent', color: t3.text, fontSize: 16, fontFamily: t3.font,
                            letterSpacing: showPwd ? 0 : 3, outline: 'none' }}/>
            <div onClick={() => setShowPwd(!showPwd)}
                 style={{ padding: '8px 14px', fontSize: 11, fontWeight: 600, color: t3.accent, fontFamily: t3.mono, letterSpacing: 1, cursor: 'pointer' }}>
              {showPwd ? L.hidePwd : L.showPwd}
            </div>
          </div>
        </GlassC>

        {/* Remember + Forgot */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14 }}>
          <div onClick={() => setRemember(!remember)} style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
            <div style={{ width: 18, height: 18, borderRadius: 5, border: `1.5px solid ${remember ? t3.accent : 'rgba(255,255,255,0.2)'}`,
                          background: remember ? t3.accent : 'transparent', color: t3.accentInk,
                          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              {remember && <Icons.check size={12} stroke={3}/>}
            </div>
            <div style={{ fontSize: 12, color: t3.textDim }}>{L.rememberMe}</div>
          </div>
          <div onClick={() => nav.openSheet('forgotPwd')} style={{ fontSize: 12, color: t3.accent, cursor: 'pointer' }}>{L.forgot}</div>
        </div>

        {/* Sign in button */}
        <button onClick={submit} disabled={!valid || loading}
                style={{ marginTop: 22, width: '100%', height: 54, border: 'none', borderRadius: 27,
                         background: valid ? t3.accent : 'rgba(255,255,255,0.06)',
                         color: valid ? t3.accentInk : t3.textMute,
                         fontSize: 15, fontWeight: 600, fontFamily: t3.font,
                         cursor: valid && !loading ? 'pointer' : 'not-allowed',
                         display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                         transition: 'all .2s' }}>
          {loading ? (
            <div style={{ width: 18, height: 18, border: `2px solid ${t3.accentInk}`, borderRightColor: 'transparent', borderRadius: 9, animation: 'c-spin .8s linear infinite' }}/>
          ) : (
            <>{L.signIn}<Icons.arrow size={16}/></>
          )}
        </button>

        {/* or — Face ID */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0' }}>
          <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.08)' }}/>
          <div style={{ fontSize: 11, color: t3.textMute, fontFamily: t3.mono, letterSpacing: 1 }}>{L.or.toUpperCase()}</div>
          <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.08)' }}/>
        </div>

        <button onClick={submit}
                style={{ width: '100%', height: 52, border: '1px solid rgba(255,255,255,0.1)', borderRadius: 26,
                         background: 'rgba(255,255,255,0.04)', color: t3.text,
                         fontSize: 14, fontWeight: 500, fontFamily: t3.font,
                         display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, cursor: 'pointer' }}>
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={t3.accent} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <rect x="3" y="3" width="18" height="18" rx="4"/>
            <path d="M8 9v1M16 9v1M8 14s1.5 2 4 2 4-2 4-2"/><path d="M12 9v4"/>
          </svg>
          {L.useFaceId}
        </button>
      </div>

      {/* Bottom: sign up + terms */}
      <div style={{ position: 'absolute', bottom: 28, left: 24, right: 24, textAlign: 'center', animation: 'c-fade-in .5s .2s forwards' }}>
        <div style={{ fontSize: 13, color: t3.textDim, marginBottom: 14 }}>
          {L.noAccount} <span onClick={() => nav.openSheet('signUp')} style={{ color: t3.accent, fontWeight: 600, cursor: 'pointer' }}>{L.signUp}</span>
        </div>
        <div style={{ fontSize: 10, color: t3.textMute, lineHeight: 1.5, padding: '0 20px' }}>{L.byContinuing}</div>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;

// ─────────────────────────────────────────────────────────────
// ONBOARDING — three steps with shared layout
// ─────────────────────────────────────────────────────────────
// Vietnamese for each ONB_DATA entry.
const ONB_VI = [
  {
    kicker: 'một · xe của bạn',
    title: 'Xe của bạn, ngay trong túi.',
    body: 'Khóa, định vị và chăm sóc chiếc Mazda của bạn ở bất kỳ đâu tại Việt Nam.',
  },
  {
    kicker: 'hai · việt nam',
    title: 'Dành riêng cho Việt Nam.',
    body: 'Giá nhiên liệu VND, mạng lưới đại lý Thaco trên toàn quốc, lịch nghỉ Tết, và toàn bộ giao diện tiếng Việt.',
  },
  {
    kicker: 'ba · luôn ở bên bạn',
    title: 'Ngay cả khi bạn ở xa.',
    body: 'Khởi động từ xa, điều hòa, tìm xe, đặt lịch bảo dưỡng, nhận hỗ trợ — Cứu hộ Thaco 24/7 tích hợp sẵn.',
  },
];

function makeOnboarding(step) {
  return function OnbStep() {
    const nav = useRouter();
    const { tw } = useApp();
    const L = STRINGS[tw.lang];
    const en = ONB_DATA[step - 1];
    const vi = ONB_VI[step - 1];
    const data = tw.lang === 'vi'
      ? { ...en, kicker: vi.kicker, title: vi.title, body: vi.body }
      : en;

    const nextRoute = step < 3 ? `onboarding${step + 1}` : 'pair';

    return (
      <div style={{ width: '100%', height: '100%', background: t3.bg, color: t3.text, fontFamily: t3.font, position: 'relative', overflow: 'hidden' }}>
        <Aurora intensity={tw.aurora}/>

        {/* Top bar */}
        <div style={{ position: 'absolute', top: 72, left: 24, right: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', zIndex: 2 }}>
          <div style={{ fontSize: 10, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 2 }}>0{step} / 03</div>
          <div onClick={() => nav.replace('home', 'home')} style={{ fontSize: 13, color: t3.textDim, cursor: 'pointer' }}>{L.skip}</div>
        </div>

        {/* Illustration */}
        <div style={{ position: 'absolute', top: 110, left: 0, right: 0, display: 'flex', justifyContent: 'center', animation: 'c-pop .5s' }}>
          {data.illo({ tw, model: tw.model })}
        </div>

        {/* Copy */}
        <div style={{ position: 'absolute', bottom: 170, left: 28, right: 28, animation: 'c-fade-in .5s .15s backwards' }}>
          <div style={{ fontSize: 11, fontFamily: t3.mono, color: t3.accent, letterSpacing: 2, marginBottom: 10, textTransform: 'uppercase' }}>· {data.kicker} ·</div>
          <div style={{ fontSize: 30, fontWeight: 300, letterSpacing: -1, lineHeight: 1.15, marginBottom: 14 }}>{data.title}</div>
          <div style={{ fontSize: 15, color: t3.textDim, lineHeight: 1.55 }}>{data.body}</div>
        </div>

        {/* Dots */}
        <div style={{ position: 'absolute', bottom: 110, left: 0, right: 0, display: 'flex', justifyContent: 'center', gap: 6 }}>
          {[1, 2, 3].map((n) => (
            <div key={n} style={{ width: n === step ? 24 : 6, height: 6, borderRadius: 3,
                                  background: n === step ? t3.accent : 'rgba(255,255,255,0.2)',
                                  transition: 'all .3s' }}/>
          ))}
        </div>

        <div style={{ position: 'absolute', bottom: 50, left: 28, right: 28, display: 'flex', gap: 12, animation: 'c-slide-up .5s .25s backwards' }}>
          {step > 1 && (
            <button onClick={() => nav.replace(`onboarding${step - 1}`)}
                    style={{ width: 56, height: 56, border: '1px solid rgba(255,255,255,0.1)', borderRadius: 28, background: 'rgba(255,255,255,0.04)', color: t3.text, fontSize: 22, cursor: 'pointer', fontFamily: t3.font }}>←</button>
          )}
          <button onClick={() => nav.replace(nextRoute)}
                  style={{ flex: 1, height: 56, border: 'none', borderRadius: 28,
                           background: t3.accent, color: t3.accentInk, fontSize: 15, fontWeight: 600,
                           fontFamily: t3.font, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
            {step < 3 ? L.onbNext : T(tw.lang, 'Pair my vehicle', 'Ghép nối xe của tôi')}
            <Icons.arrow size={16}/>
          </button>
        </div>
      </div>
    );
  };
}

// We can't call T() here (no tw in scope). Each illo function uses its
// own tw, so we keep the source strings English here and translate them in
// the renderer via the lookup map below.
const ONB_DATA = [
  {
    kicker: 'one · your car',
    title: 'Your car, in your pocket.',
    body: 'Lock, locate, and look after your Mazda from anywhere in Vietnam.',
    illo: ({ tw, model }) => (
      <div style={{ position: 'relative', width: 280, height: 280 }}>
        <div style={{ position: 'absolute', top: 0, left: 30, width: 130, height: 130, background: 'linear-gradient(140deg, rgba(212,165,116,0.3), rgba(212,165,116,0.05))', backdropFilter: 'blur(20px)', borderRadius: 24, border: '1px solid rgba(255,255,255,0.1)', transform: 'rotate(-4deg)', padding: 16, animation: 'c-fall .6s' }}>
          <Icons.lock size={20}/>
          <div style={{ position: 'absolute', bottom: 12, left: 16, fontSize: 11, color: t3.textDim }}>{tw.lang === 'vi' ? 'Đã khóa' : 'Locked'}</div>
          <div style={{ position: 'absolute', bottom: 30, left: 16, fontSize: 13, fontWeight: 600 }}>{tw.lang === 'vi' ? 'Tất cả cửa' : 'All doors'}</div>
        </div>
        <div style={{ position: 'absolute', top: 30, right: 0, width: 130, height: 80, background: 'linear-gradient(140deg, rgba(124,183,255,0.25), rgba(124,183,255,0.05))', backdropFilter: 'blur(20px)', borderRadius: 24, border: '1px solid rgba(255,255,255,0.1)', transform: 'rotate(5deg)', padding: 14, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', animation: 'c-fall .6s .1s backwards' }}>
          <Icons.fuel size={18}/>
          <div style={{ fontSize: 22, fontWeight: 600 }}>72<span style={{ fontSize: 12, color: t3.textDim }}>%</span></div>
        </div>
        <div style={{ position: 'absolute', bottom: 0, left: 50, right: 30, height: 130, background: 'linear-gradient(140deg, rgba(255,255,255,0.08), rgba(255,255,255,0.02))', backdropFilter: 'blur(20px)', borderRadius: 24, border: '1px solid rgba(255,255,255,0.1)', transform: 'rotate(-3deg)', padding: 16, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', animation: 'c-fall .6s .2s backwards' }}>
          <CarSideModel model={model} width={180} color={VEHICLES[model].color}/>
        </div>
      </div>
    ),
  },
  {
    kicker: 'two · vietnam',
    title: 'Made for Vietnam.',
    body: 'VND fuel prices, Thaco dealer network across the country, Tết holiday scheduling, and Vietnamese throughout.',
    illo: ({ tw }) => (
      <div style={{ position: 'relative', width: 280, height: 280 }}>
        <GlassC padding={20} intensity={tw.glass} style={{ position: 'absolute', inset: 0, borderRadius: 24, overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, opacity: 0.7 }}><HanoiMap/></div>
          <div style={{ position: 'absolute', top: 80, left: 70, color: t3.accent }}>
            <Icons.pin size={32}/>
          </div>
          <div style={{ position: 'absolute', top: 130, left: 30, padding: '4px 10px', borderRadius: 999, background: 'rgba(20,25,30,0.85)', fontSize: 10, fontFamily: t3.mono, color: t3.text }}>HÀ NỘI</div>
          <div style={{ position: 'absolute', top: 180, right: 30, padding: '4px 10px', borderRadius: 999, background: 'rgba(20,25,30,0.85)', fontSize: 10, fontFamily: t3.mono, color: t3.text }}>HCMC · 1,720 km</div>
          <div style={{ position: 'absolute', bottom: 14, left: 14, right: 14, padding: '10px 12px', borderRadius: 14, background: 'rgba(20,25,30,0.85)', display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icons.fuel size={16}/>
            <div style={{ flex: 1, fontSize: 11, color: t3.textDim }}>RON95</div>
            <div style={{ fontSize: 13, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>21,340₫/L</div>
          </div>
        </GlassC>
      </div>
    ),
  },
  {
    kicker: 'three · always with you',
    title: 'Even when you\u2019re away.',
    body: 'Remote start, climate control, find your car, book service, get help — 24/7 Thaco roadside assistance built in.',
    illo: ({ tw }) => (
      <div style={{ position: 'relative', width: 280, height: 280 }}>
        <GlassC padding={20} intensity={tw.glass} style={{ position: 'absolute', top: 20, left: 30, right: 50, height: 120, borderRadius: 24, animation: 'c-fall .6s' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ color: t3.accent2 }}><Icons.fan size={20}/></div>
            <div style={{ fontSize: 12, color: t3.textDim, fontFamily: t3.mono }}>{tw.lang === 'vi' ? 'ĐIỀU HÒA' : 'CLIMATE'}</div>
          </div>
          <div style={{ fontSize: 36, fontWeight: 300, letterSpacing: -1, marginTop: 12, fontVariantNumeric: 'tabular-nums' }}>22°C</div>
          <div style={{ fontSize: 11, color: t3.textDim, marginTop: 4 }}>{tw.lang === 'vi' ? 'Đang điều hòa trước' : 'Pre-conditioning'}</div>
        </GlassC>
        <GlassC padding={16} intensity={tw.glass} style={{ position: 'absolute', bottom: 30, right: 20, width: 180, borderRadius: 24, animation: 'c-fall .6s .15s backwards' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ width: 36, height: 36, borderRadius: 18, background: '#E84848', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
              <div style={{ position: 'absolute', inset: 0, borderRadius: 18, border: '1px solid #E84848', animation: 'c-pulse-strong 2s infinite' }}/>
              <Icons.sos size={18}/>
            </div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 600 }}>SOS 24/7</div>
              <div style={{ fontSize: 10, color: t3.textDim }}>{tw.lang === 'vi' ? 'Cứu hộ Thaco' : 'Thaco Roadside'}</div>
            </div>
          </div>
        </GlassC>
        <GlassC padding={14} intensity={tw.glass} style={{ position: 'absolute', top: 130, left: 20, width: 130, borderRadius: 24, animation: 'c-fall .6s .25s backwards' }}>
          <Icons.wrench size={20}/>
          <div style={{ fontSize: 11, color: t3.textDim, marginTop: 8, fontFamily: t3.mono }}>{tw.lang === 'vi' ? 'BẢO DƯỠNG' : 'SERVICE'}</div>
          <div style={{ fontSize: 13, fontWeight: 600, marginTop: 2 }}>{tw.lang === 'vi' ? 'Còn 2,300 km' : 'In 2,300 km'}</div>
        </GlassC>
      </div>
    ),
  },
];

const Onboarding1 = makeOnboarding(1);
const Onboarding2 = makeOnboarding(2);
const Onboarding3 = makeOnboarding(3);

// ─────────────────────────────────────────────────────────────
// PAIR VEHICLE — VIN entry / QR scan
// ─────────────────────────────────────────────────────────────
function PairScreen() {
  const nav = useRouter();
  const { tw } = useApp();
  const L = STRINGS[tw.lang];
  const [mode, setMode] = React.useState('qr');   // 'qr' | 'vin'
  const [vin, setVin] = React.useState('JM3KFB');
  const [phase, setPhase] = React.useState('scan'); // 'scan' | 'detected' | 'success'

  // Simulate QR detection after 2.4s when in qr mode
  React.useEffect(() => {
    if (mode !== 'qr' || phase !== 'scan') return;
    const tm = setTimeout(() => setPhase('detected'), 2400);
    return () => clearTimeout(tm);
  }, [mode, phase]);

  if (phase === 'success') {
    return (
      <div style={{ width: '100%', height: '100%', background: t3.bg, color: t3.text, fontFamily: t3.font, position: 'relative', overflow: 'hidden' }}>
        <Aurora intensity={tw.aurora}/>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 24, animation: 'c-pop .4s' }}>
          <div style={{ position: 'relative', width: 100, height: 100, marginBottom: 28 }}>
            <div style={{ position: 'absolute', inset: 0, borderRadius: 50, border: `1px solid ${t3.ok}`, animation: 'c-pulse-strong 2s infinite' }}/>
            <div style={{ position: 'absolute', inset: 0, borderRadius: 50, background: t3.ok, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t3.bg }}>
              <Icons.check size={48} stroke={2.5}/>
            </div>
          </div>
          <div style={{ fontSize: 26, fontWeight: 400, letterSpacing: -0.6, marginBottom: 8 }}>{T(tw.lang, 'Vehicle paired', 'Đã ghép nối xe')}</div>
          <div style={{ fontSize: 14, color: t3.textDim, textAlign: 'center', maxWidth: 280, lineHeight: 1.5 }}>
            {VEHICLES[tw.model].name} · {VEHICLES[tw.model].plate}<br/>{T(tw.lang, 'connected to your account.', 'đã được kết nối với tài khoản.')}
          </div>
          <button onClick={() => nav.replace('home', 'home')}
                  style={{ marginTop: 36, padding: '14px 28px', borderRadius: 28, border: 'none', background: t3.accent, color: t3.accentInk, fontSize: 14, fontWeight: 600, fontFamily: t3.font, cursor: 'pointer' }}>
            {T(tw.lang, 'Continue to dashboard', 'Tiếp tục vào trang chủ')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ width: '100%', height: '100%', background: t3.bg, color: t3.text, fontFamily: t3.font, position: 'relative', overflow: 'hidden' }}>
      <Aurora intensity={tw.aurora}/>
      <div style={{ height: 62 }}/>
      <div style={{ padding: '6px 18px 18px' }}>
        <BackHeader title={T(tw.lang, 'Pair vehicle', 'Ghép nối xe')} subtitle={T(tw.lang, 'Add to your account', 'Thêm vào tài khoản')}/>

        <div style={{ display: 'flex', padding: 4, borderRadius: 14, background: 'rgba(255,255,255,0.05)', marginBottom: 18 }}>
          {[{ k: 'qr', l: T(tw.lang, 'Scan QR', 'Quét QR') }, { k: 'vin', l: T(tw.lang, 'Enter VIN', 'Nhập VIN') }].map((tab) => (
            <div key={tab.k} onClick={() => { setMode(tab.k); setPhase('scan'); }}
                 style={{ flex: 1, padding: '10px 0', textAlign: 'center', borderRadius: 10, fontSize: 13, fontWeight: 500, cursor: 'pointer',
                          background: mode === tab.k ? t3.accent : 'transparent',
                          color: mode === tab.k ? t3.accentInk : t3.textDim, transition: 'all .2s' }}>{tab.l}</div>
          ))}
        </div>

        {mode === 'qr' && (
          <GlassC padding={0} radius={26} intensity={tw.glass} style={{ aspectRatio: '1', position: 'relative', overflow: 'hidden', marginBottom: 18 }}>
            {/* fake camera feed */}
            <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 40% 40%, #1a2a3a, #0a0f14)' }}/>
            {/* scan frame */}
            <div style={{ position: 'absolute', top: '20%', left: '20%', width: '60%', height: '60%' }}>
              {['nw', 'ne', 'sw', 'se'].map((c) => (
                <div key={c} style={{
                  position: 'absolute',
                  ...(c[0] === 'n' ? { top: 0 } : { bottom: 0 }),
                  ...(c[1] === 'w' ? { left: 0 } : { right: 0 }),
                  width: 30, height: 30,
                  borderTop: c[0] === 'n' ? `3px solid ${t3.accent}` : 'none',
                  borderBottom: c[0] === 's' ? `3px solid ${t3.accent}` : 'none',
                  borderLeft: c[1] === 'w' ? `3px solid ${t3.accent}` : 'none',
                  borderRight: c[1] === 'e' ? `3px solid ${t3.accent}` : 'none',
                  borderTopLeftRadius: c === 'nw' ? 12 : 0,
                  borderTopRightRadius: c === 'ne' ? 12 : 0,
                  borderBottomLeftRadius: c === 'sw' ? 12 : 0,
                  borderBottomRightRadius: c === 'se' ? 12 : 0,
                }}/>
              ))}
              {/* scan line */}
              {phase === 'scan' && (
                <div style={{ position: 'absolute', left: 4, right: 4, top: '50%', height: 2,
                              background: `linear-gradient(90deg, transparent, ${t3.accent}, transparent)`,
                              animation: 'scanline 2s ease-in-out infinite' }}/>
              )}
              {/* detected: QR code preview */}
              {phase === 'detected' && (
                <div style={{ position: 'absolute', inset: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'c-pop .3s' }}>
                  <FakeQR/>
                </div>
              )}
            </div>
            <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16, textAlign: 'center', fontSize: 12, color: t3.textDim, fontFamily: t3.mono, letterSpacing: 1 }}>
              {phase === 'scan' ? T(tw.lang, 'POINT AT QR ON WINDSHIELD…', 'HƯỚNG VÀO MÃ QR TRÊN KÍNH LÁI…') : T(tw.lang, 'DETECTED · VEHICLE 0xJM3KFB', 'ĐÃ NHẬN · XE 0xJM3KFB')}
            </div>
          </GlassC>
        )}

        {mode === 'vin' && (
          <GlassC padding={18} radius={26} intensity={tw.glass} style={{ marginBottom: 18 }}>
            <div style={{ fontSize: 11, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 1, marginBottom: 10 }}>{T(tw.lang, 'VIN · 17 CHARS', 'VIN · 17 KÝ TỰ')}</div>
            <div style={{ fontSize: 22, fontFamily: t3.mono, fontVariantNumeric: 'tabular-nums', letterSpacing: 2, padding: '14px 0' }}>
              {(vin + '_________________').slice(0, 17).split('').map((c, i) => (
                <span key={i} style={{ color: c === '_' ? t3.textMute : t3.text, marginRight: 4 }}>{c}</span>
              ))}
            </div>
            <div style={{ fontSize: 11, color: t3.textDim, marginTop: 8 }}>{T(tw.lang, 'Find your VIN on the dashboard (driver side) or in your registration document.', 'Tìm số VIN trên bảng táp-lô (phía tài) hoặc trong giấy đăng ký xe.')}</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginTop: 18 }}>
              {[1,2,3,4,5,6,7,8,9,'V','0','⌫'].map((k) => (
                <button key={k} onClick={() => {
                  if (k === '⌫') setVin((v) => v.slice(0, -1));
                  else if (vin.length < 17) setVin((v) => v + k);
                }}
                  style={{ height: 44, borderRadius: 14, border: '1px solid rgba(255,255,255,0.06)', background: 'rgba(255,255,255,0.04)', color: t3.text, fontSize: 16, fontFamily: t3.mono, fontWeight: 500, cursor: 'pointer' }}>{k}</button>
              ))}
            </div>
          </GlassC>
        )}

        <button onClick={() => setPhase('success')}
                disabled={phase === 'scan' && mode === 'qr'}
                style={{
          width: '100%', height: 54, border: 'none', borderRadius: 27,
          background: (phase === 'detected' || mode === 'vin') ? t3.accent : 'rgba(255,255,255,0.06)',
          color: (phase === 'detected' || mode === 'vin') ? t3.accentInk : t3.textMute,
          fontSize: 14, fontWeight: 600, fontFamily: t3.font,
          cursor: (phase === 'detected' || mode === 'vin') ? 'pointer' : 'not-allowed',
          transition: 'all .15s',
        }}>
          {phase === 'detected' ? T(tw.lang, 'Confirm & pair', 'Xác nhận & ghép nối') : (mode === 'qr' ? T(tw.lang, 'Scanning…', 'Đang quét…') : T(tw.lang, 'Pair vehicle', 'Ghép nối xe'))}
        </button>
      </div>
    </div>
  );
}

function FakeQR() {
  const cells = React.useMemo(() => {
    // Deterministic pseudo-random 21x21 grid
    const grid = [];
    let s = 12345;
    for (let i = 0; i < 21; i++) {
      const row = [];
      for (let j = 0; j < 21; j++) {
        s = (s * 9301 + 49297) % 233280;
        row.push(s % 100 < 48 ? 1 : 0);
      }
      grid.push(row);
    }
    // Place position markers
    const placeMarker = (r, c) => {
      for (let i = 0; i < 7; i++) for (let j = 0; j < 7; j++) {
        grid[r+i][c+j] = (i === 0 || i === 6 || j === 0 || j === 6 || (i >= 2 && i <= 4 && j >= 2 && j <= 4)) ? 1 : 0;
      }
    };
    placeMarker(0, 0); placeMarker(0, 14); placeMarker(14, 0);
    return grid;
  }, []);
  return (
    <div style={{ width: '100%', maxWidth: 220, aspectRatio: '1', display: 'grid', gridTemplateColumns: 'repeat(21, 1fr)', gap: 0, padding: 8, background: '#fff', borderRadius: 8 }}>
      {cells.flat().map((c, i) => (
        <div key={i} style={{ background: c ? '#000' : '#fff' }}/>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TRIP HISTORY + DRIVING SCORE
// ─────────────────────────────────────────────────────────────
function TripScreen() {
  const nav = useRouter();
  const { tw } = useApp();
  const L = STRINGS[tw.lang];
  const toast = useToast();
  const trips = [
    { d: T(tw.lang, 'Today', 'Hôm nay'),     from: 'Vincom Bà Triệu',          to: 'Cầu Giấy',          km: 8.4,   dur: T(tw.lang, '24 min', '24 phút'),   score: 91, eco: true,  time: '14:08' },
    { d: T(tw.lang, 'Yesterday', 'Hôm qua'), from: T(tw.lang, 'Home', 'Nhà'),  to: T(tw.lang, 'Office', 'Văn phòng'), km: 12.1, dur: T(tw.lang, '38 min', '38 phút'), score: 84, eco: true,  time: '08:12' },
    { d: T(tw.lang, 'Yesterday', 'Hôm qua'), from: T(tw.lang, 'Office', 'Văn phòng'), to: T(tw.lang, 'Phố Cổ restaurant', 'Nhà hàng Phố Cổ'), km: 4.6, dur: T(tw.lang, '18 min', '18 phút'), score: 78, eco: false, time: '19:22' },
    { d: '17/05', from: 'Hà Nội',  to: 'Hải Phòng', km: 102.0, dur: '1h 48m', score: 88, eco: true,  time: '06:30' },
    { d: '17/05', from: 'Hải Phòng', to: 'Hà Nội',  km: 102.4, dur: '1h 52m', score: 86, eco: true,  time: '17:10' },
  ];
  const score = useTween(87, 800);
  return (
    <ScreenShell>
      <div style={{ padding: '6px 18px 20px' }} className="c-stagger">
        <BackHeader title={T(tw.lang, 'Trip history', 'Lịch sử chuyến đi')} subtitle={T(tw.lang, 'Last 30 days', '30 ngày qua')}/>

        {/* Score hero */}
        <GlassC padding={20} radius={26} intensity={tw.glass} style={{ marginBottom: 12 }} accentLine>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <Ring pct={score} size={100} stroke={8} color={t3.accent} label={Math.round(score) + ''}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 1 }}>{T(tw.lang, 'DRIVING SCORE', 'ĐIỂM LÁI XE')}</div>
              <div style={{ fontSize: 24, fontWeight: 400, letterSpacing: -0.5, marginTop: 2 }}>{T(tw.lang, 'Eco · Smooth', 'Tiết kiệm · Êm ái')}</div>
              <div style={{ fontSize: 11, color: t3.textDim, marginTop: 4 }}>{T(tw.lang, 'Top 12% of CX-5 drivers in Vietnam', 'Top 12% tài xế CX-5 tại Việt Nam')}</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginTop: 16 }}>
            <ScoreBit label={T(tw.lang, 'ACCEL', 'TĂNG TỐC')} val={92}/>
            <ScoreBit label={T(tw.lang, 'BRAKE', 'PHANH')}    val={84}/>
            <ScoreBit label={T(tw.lang, 'ECO', 'TIẾT KIỆM')}  val={88}/>
          </div>
        </GlassC>

        {/* Distance breakdown */}
        <GlassC padding={16} radius={24} intensity={tw.glass} style={{ marginBottom: 12 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
            <div>
              <div style={{ fontSize: 10, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 1 }}>{T(tw.lang, 'THIS WEEK', 'TUẦN NÀY')}</div>
              <div style={{ fontSize: 26, fontWeight: 400, letterSpacing: -0.5, marginTop: 2 }}>263 <span style={{ fontSize: 14, color: t3.textDim }}>km</span></div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 1 }}>{T(tw.lang, 'FUEL', 'NHIÊN LIỆU')}</div>
              <div style={{ fontSize: 16, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>{fmtVND(548000)}</div>
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 70 }}>
            {[28, 42, 18, 51, 38, 22, 64].map((h, i) => (
              <div key={i} style={{ flex: 1, height: h + '%', background: i === 6 ? t3.accent : 'rgba(212,165,116,0.3)',
                                    borderRadius: 4, animation: 'c-bar-grow .6s cubic-bezier(.4,0,.2,1) backwards',
                                    animationDelay: (i * 0.06) + 's', transformOrigin: 'bottom' }}/>
            ))}
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 10, color: t3.textDim, fontFamily: t3.mono }}>
            {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => <span key={i}>{d}</span>)}
          </div>
        </GlassC>

        {/* Trip list */}
        <GlassC padding={4} radius={20} intensity={tw.glass}>
          {trips.map((tr, i) => (
            <div key={i} onClick={() => toast.push(`${tr.from} → ${tr.to}`, { icon: 'pin' })}
                 style={{ padding: '14px 14px', display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
                                  borderTop: i ? '1px solid rgba(255,255,255,0.05)' : 'none', animation: 'c-fall .35s backwards',
                                  animationDelay: (i * 0.04) + 's' }}>
              <div style={{ flexShrink: 0, width: 38, textAlign: 'right' }}>
                <div style={{ fontSize: 11, fontFamily: t3.mono, color: t3.textDim }}>{tr.time}</div>
                <div style={{ fontSize: 9, fontFamily: t3.mono, color: t3.textMute, marginTop: 1 }}>{tr.d}</div>
              </div>
              <div style={{ width: 1, alignSelf: 'stretch', background: 'rgba(255,255,255,0.08)', position: 'relative' }}>
                <div style={{ position: 'absolute', top: 2, left: -3, width: 7, height: 7, borderRadius: 4, background: t3.accent }}/>
                <div style={{ position: 'absolute', bottom: 2, left: -3, width: 7, height: 7, borderRadius: 4, background: 'rgba(255,255,255,0.3)' }}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tr.from}</div>
                <div style={{ fontSize: 13, color: t3.textDim, marginTop: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tr.to}</div>
                <div style={{ fontSize: 10, color: t3.textMute, fontFamily: t3.mono, marginTop: 6 }}>{tr.km} km · {tr.dur} · {T(tw.lang, 'score', 'điểm')} {tr.score}{tr.eco && <span style={{ color: t3.ok }}> · {T(tw.lang, 'ECO', 'TIẾT KIỆM')}</span>}</div>
              </div>
            </div>
          ))}
        </GlassC>
      </div>
    </ScreenShell>
  );
}

function ScoreBit({ label, val }) {
  return (
    <div style={{ padding: '10px 12px', borderRadius: 14, background: 'rgba(255,255,255,0.05)' }}>
      <div style={{ fontSize: 9, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 1 }}>{label}</div>
      <div style={{ fontSize: 18, fontWeight: 500, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{val}</div>
      <div style={{ height: 3, marginTop: 6, borderRadius: 2, background: 'rgba(255,255,255,0.08)' }}>
        <div style={{ width: val + '%', height: '100%', borderRadius: 2, background: t3.accent }}/>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// DEALER LOCATOR
// ─────────────────────────────────────────────────────────────
function DealerScreen() {
  const nav = useRouter();
  const { tw } = useApp();
  const dealers = [
    { n: 'Mazda Thaco Long Biên', a: '15 Nguyễn Văn Cừ, Long Biên · Hà Nội', d: 3.2, x: '58%', y: '40%', stars: 4.8, hours: T(tw.lang, 'Open · until 18:00', 'Đang mở · đến 18:00') },
    { n: 'Mazda Thaco Lê Văn Lương', a: 'KĐT Trung Hòa, Cầu Giấy · Hà Nội', d: 5.8, x: '32%', y: '48%', stars: 4.7, hours: T(tw.lang, 'Open · until 18:00', 'Đang mở · đến 18:00') },
    { n: 'Mazda Thaco Phạm Văn Đồng', a: 'Bắc Từ Liêm · Hà Nội', d: 8.1, x: '20%', y: '24%', stars: 4.9, hours: T(tw.lang, 'Open · until 18:00', 'Đang mở · đến 18:00') },
    { n: 'Mazda Thaco Giải Phóng', a: 'Hoàng Mai · Hà Nội', d: 6.4, x: '70%', y: '68%', stars: 4.6, hours: T(tw.lang, 'Open · until 18:00', 'Đang mở · đến 18:00') },
  ];
  const [sel, setSel] = React.useState(0);

  return (
    <div style={{ width: '100%', height: '100%', position: 'relative' }}>
      <HanoiMap/>
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(circle at 50% 40%, rgba(212,165,116,0.12), transparent 60%)', pointerEvents: 'none' }}/>

      <div style={{ position: 'absolute', top: 72, left: 16, right: 16 }}>
        <GlassC padding={0} radius={28} intensity={tw.glass}>
          <div style={{ display: 'flex', alignItems: 'center', padding: '0 14px', height: 44, gap: 12 }}>
            <div onClick={nav.back} style={{ cursor: 'pointer' }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={t3.text} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
            </div>
            <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{T(tw.lang, 'Thaco dealers · Hanoi', 'Đại lý Thaco · Hà Nội')}</div>
            <div style={{ fontSize: 11, color: t3.textDim, fontFamily: t3.mono }}>{dealers.length}</div>
          </div>
        </GlassC>
      </div>

      {/* Pins */}
      {dealers.map((d, i) => (
        <div key={i} onClick={() => setSel(i)} style={{ position: 'absolute', left: d.x, top: d.y, transform: 'translate(-50%,-100%)', cursor: 'pointer', zIndex: i === sel ? 2 : 1 }}>
          {i === sel && (
            <div style={{ position: 'absolute', bottom: -10, left: -22, width: 44, height: 44, borderRadius: 22, background: 'rgba(212,165,116,0.25)', animation: 'c-pulse-strong 2s infinite' }}/>
          )}
          <div style={{ width: i === sel ? 40 : 30, height: i === sel ? 40 : 30, borderRadius: i === sel ? 20 : 15,
                        background: i === sel ? t3.accent : 'rgba(20,25,30,0.85)',
                        border: i === sel ? 'none' : `2px solid ${t3.accent}`,
                        color: i === sel ? t3.accentInk : t3.accent,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        boxShadow: i === sel ? '0 8px 24px rgba(212,165,116,0.5)' : 'none',
                        transition: 'all .25s' }}>
            <Icons.wrench size={i === sel ? 18 : 14} stroke={2}/>
          </div>
        </div>
      ))}

      {/* User dot */}
      <div style={{ position: 'absolute', top: '60%', left: '46%' }}>
        <div style={{ width: 14, height: 14, borderRadius: 7, background: t3.accent2, border: '3px solid #fff', boxShadow: '0 0 0 5px rgba(124,183,255,0.3)' }}/>
      </div>

      {/* Bottom list */}
      <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16 }}>
        <GlassC padding={4} radius={26} intensity={Math.max(1, tw.glass)} style={{ background: 'rgba(20,25,30,0.85)' }}>
          <div style={{ overflowX: 'auto', display: 'flex', gap: 8, padding: 12, scrollSnapType: 'x mandatory' }}>
            {dealers.map((d, i) => (
              <div key={i} onClick={() => setSel(i)} style={{ flex: '0 0 240px', scrollSnapAlign: 'start', padding: 14, borderRadius: 18,
                                                              border: `1px solid ${sel === i ? t3.accent : 'rgba(255,255,255,0.08)'}`,
                                                              background: sel === i ? 'rgba(212,165,116,0.1)' : 'rgba(255,255,255,0.03)',
                                                              cursor: 'pointer', transition: 'all .15s' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: -0.2 }}>{d.n.replace('Mazda Thaco ', 'Thaco ')}</div>
                  <div style={{ fontSize: 10, color: t3.accent }}>★ {d.stars}</div>
                </div>
                <div style={{ fontSize: 11, color: t3.textDim, marginTop: 4, lineHeight: 1.4 }}>{d.a}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 10 }}>
                  <div style={{ fontSize: 11, color: t3.ok }}>● {d.hours}</div>
                  <div style={{ fontSize: 11, color: t3.textDim, fontFamily: t3.mono }}>{d.d} km</div>
                </div>
              </div>
            ))}
          </div>
        </GlassC>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// OWNER'S MANUAL / HOW-TO
// ─────────────────────────────────────────────────────────────
function ManualScreen() {
  const nav = useRouter();
  const { tw } = useApp();
  const toast = useToast();
  const [section, setSection] = React.useState(null);

  const sections = [
    { id: 'getting', title: T(tw.lang, 'Getting started', 'Bắt đầu'),                sub: T(tw.lang, '6 articles', '6 bài viết'), icon: 'car', color: t3.accent },
    { id: 'safety',  title: T(tw.lang, 'Safety features', 'Tính năng an toàn'),       sub: 'i-Activsense · SBS · MRCC', icon: 'signal', color: t3.accent2 },
    { id: 'climate', title: T(tw.lang, 'Climate & comfort', 'Điều hòa & tiện nghi'),  sub: T(tw.lang, 'Dual-zone AC · seat heater', 'Điều hòa 2 vùng · sưởi ghế'), icon: 'fan', color: t3.accent },
    { id: 'media',   title: T(tw.lang, 'Media & connectivity', 'Giải trí & kết nối'), sub: 'CarPlay · Bluetooth · Mazda Connect', icon: 'signal', color: t3.accent2 },
    { id: 'maint',   title: T(tw.lang, 'Maintenance', 'Bảo dưỡng'),                    sub: T(tw.lang, 'Schedules · DIY checks · fluids', 'Lịch · kiểm tra tự làm · dầu nhớt'), icon: 'wrench', color: t3.warn },
    { id: 'emerg',   title: T(tw.lang, 'Emergency', 'Khẩn cấp'),                       sub: T(tw.lang, 'SOS · flat tire · jumping the battery', 'SOS · thủng lốp · câu bình'), icon: 'sos', color: '#E84848' },
  ];

  if (section) {
    return (
      <ScreenShell>
        <div style={{ padding: '6px 18px 20px' }}>
          <BackHeader title={sections.find((s) => s.id === section)?.title} subtitle={T(tw.lang, 'Owner’s manual', 'Sách hướng dẫn')}
                      action={<div onClick={() => setSection(null)} style={{ fontSize: 12, color: t3.accent, cursor: 'pointer' }}>{T(tw.lang, 'All sections', 'Tất cả mục')}</div>}/>

          <GlassC padding={20} radius={24} intensity={tw.glass} style={{ marginBottom: 14 }} accentLine>
            <div style={{ fontSize: 11, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 1, marginBottom: 8 }}>{T(tw.lang, 'CHAPTER 02', 'CHƯƠNG 02')}</div>
            <div style={{ fontSize: 22, fontWeight: 400, letterSpacing: -0.5, marginBottom: 14 }}>{T(tw.lang, 'Using the climate control', 'Sử dụng điều hòa')}</div>
            <div style={{ fontSize: 14, color: t3.textDim, lineHeight: 1.6 }}>
              {T(tw.lang,
                'Your CX-5 features a dual-zone automatic climate system. Each front occupant can independently set temperature, fan speed, and airflow direction using the centre console controls or the touchscreen.',
                'Xe CX-5 được trang bị hệ thống điều hòa tự động 2 vùng. Người ngồi trước có thể tùy chỉnh độc lập nhiệt độ, tốc độ quạt và hướng gió qua bảng điều khiển trung tâm hoặc màn hình cảm ứng.')}
            </div>
            <div style={{ marginTop: 18, paddingTop: 16, borderTop: '1px solid rgba(255,255,255,0.08)',
                          display: 'flex', gap: 12, alignItems: 'flex-start' }}>
              <div style={{ fontSize: 11, fontFamily: t3.mono, color: t3.accent2, letterSpacing: 2, paddingTop: 2, flexShrink: 0, minWidth: 32 }}>
                {T(tw.lang, 'TIP', 'MẸO')}
              </div>
              <div style={{ flex: 1, fontSize: 13, color: t3.text, lineHeight: 1.55 }}>
                {T(tw.lang, 'Use the Mazda Connect app to pre-condition the cabin before you arrive — it works up to 30 minutes ahead.', 'Dùng ứng dụng Mazda Connect để bật điều hòa trước khi vào xe — kích hoạt được trước tối đa 30 phút.')}
              </div>
            </div>
          </GlassC>

          <div style={{ marginBottom: 8, fontSize: 11, fontFamily: t3.mono, color: t3.textDim, letterSpacing: 1, padding: '0 4px' }}>{T(tw.lang, 'RELATED', 'LIÊN QUAN')}</div>
          <GlassC padding={4} radius={20} intensity={tw.glass}>
            {[T(tw.lang, 'Setting temperature presets', 'Cài đặt chế độ nhiệt độ'),
              T(tw.lang, 'Defrosting front and rear glass', 'Xả băng kính trước và sau'),
              T(tw.lang, 'Activating air recirculation',   'Kích hoạt tuần hoàn gió')].map((title, i) => (
              <div key={i} onClick={() => toast.push(title, { icon: 'doc' })}
                   style={{ padding: '14px 14px', display: 'flex', alignItems: 'center', gap: 12,
                                    borderTop: i ? '1px solid rgba(255,255,255,0.05)' : 'none', cursor: 'pointer' }}>
                <div style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(255,255,255,0.05)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, color: t3.textDim, fontFamily: t3.mono }}>{String(i + 1).padStart(2, '0')}</div>
                <div style={{ flex: 1, fontSize: 13 }}>{title}</div>
                <Icons.chev size={14}/>
              </div>
            ))}
          </GlassC>
        </div>
      </ScreenShell>
    );
  }

  return (
    <ScreenShell>
      <div style={{ padding: '6px 18px 20px' }} className="c-stagger">
        <BackHeader title={T(tw.lang, 'Owner’s manual', 'Sách hướng dẫn')} subtitle={VEHICLES[tw.model].name}/>

        <GlassC padding={0} radius={26} intensity={tw.glass} style={{ cursor: 'pointer' }}
                onClick={() => toast.push(T(tw.lang, 'Search across 624 pages', 'Tìm kiếm trong 624 trang'), { icon: 'search' })}>
          <div style={{ display: 'flex', alignItems: 'center', padding: '0 14px', height: 48, gap: 12 }}>
            <Icons.search size={18}/>
            <div style={{ flex: 1, fontSize: 14, color: t3.textDim }}>{T(tw.lang, 'Search "how to use CarPlay"…', 'Tìm kiếm "cách dùng CarPlay"…')}</div>
          </div>
        </GlassC>

        <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {sections.map((s) => {
            const I = Icons[s.icon];
            return (
              <GlassC key={s.id} padding={16} radius={22} intensity={tw.glass} style={{ cursor: 'pointer' }} onClick={() => setSection(s.id)}>
                <div style={{ width: 38, height: 38, borderRadius: 12, background: `${s.color}22`, color: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 14 }}>
                  <I size={20}/>
                </div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{s.title}</div>
                <div style={{ fontSize: 11, color: t3.textDim, marginTop: 4, lineHeight: 1.4 }}>{s.sub}</div>
              </GlassC>
            );
          })}
        </div>

        <GlassC padding={14} radius={22} intensity={tw.glass} style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 38, height: 38, borderRadius: 12, background: 'rgba(124,183,255,0.14)', color: t3.accent2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icons.doc size={18}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{T(tw.lang, 'Full PDF · 624 pages', 'PDF đầy đủ · 624 trang')}</div>
            <div style={{ fontSize: 11, color: t3.textDim, marginTop: 2 }}>{T(tw.lang, 'Vietnamese · 38 MB · offline', 'Tiếng Việt · 38 MB · ngoại tuyến')}</div>
          </div>
          <button onClick={() => nav.openSheet('downloadPDF')}
                  style={{ padding: '8px 12px', borderRadius: 14, border: '1px solid rgba(255,255,255,0.1)', background: 'transparent', color: t3.text, fontSize: 11, fontWeight: 500, fontFamily: t3.font, cursor: 'pointer' }}>{T(tw.lang, 'Download', 'Tải về')}</button>
        </GlassC>
      </div>
    </ScreenShell>
  );
}

// inject scanline animation
if (!document.getElementById('c-scanline')) {
  const s = document.createElement('style');
  s.id = 'c-scanline';
  s.textContent = '@keyframes scanline { 0%,100% { transform: translateY(-60px); opacity: 0.3; } 50% { transform: translateY(60px); opacity: 1; } }';
  document.head.appendChild(s);
}

window.SplashScreen = SplashScreen;
window.Onboarding1 = Onboarding1;
window.Onboarding2 = Onboarding2;
window.Onboarding3 = Onboarding3;
window.PairScreen = PairScreen;
window.TripScreen = TripScreen;
window.DealerScreen = DealerScreen;
window.ManualScreen = ManualScreen;
