// Primary screens for the C prototype.
// All use the C theme; navigation via useRouter, state via useApp.

const t = THEMES.c;

// Wrapper applied to every screen — pads for status bar + FAB nav, scroll if scroll=true.
function ScreenShell({ children, scroll = true, pad = true, fab = true, showSheetBackdrop, onPull }) {
  const ptr = onPull ? usePullToRefresh(onPull) : null;
  const containerProps = ptr ? ptr.bind : {};
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', position: 'relative' }}>
      <div style={{ height: 'calc(20px + env(safe-area-inset-top, 42px))', flexShrink: 0 }}/>
      {ptr && <PullIndicator pull={ptr.pull} refreshing={ptr.refreshing}/>}
      <div {...containerProps} style={{
        flex: 1, overflowY: scroll ? 'auto' : 'hidden', overflowX: 'hidden', position: 'relative',
        paddingBottom: fab ? 'calc(100px + env(safe-area-inset-bottom, 20px))' : 'calc(10px + env(safe-area-inset-bottom, 20px))',
        transform: ptr && ptr.pull > 0 && !ptr.refreshing ? `translateY(${ptr.pull * 40}px)` : undefined,
        transition: ptr && !ptr.refreshing ? 'transform .15s' : undefined,
      }}>
        {children}
      </div>
    </div>
  );
}

function PullIndicator({ pull, refreshing }) {
  const visible = pull > 0 || refreshing;
  return (
    <div style={{ position: 'absolute', top: 70, left: 0, right: 0, height: 0, display: 'flex', justifyContent: 'center', zIndex: 10, pointerEvents: 'none' }}>
      <div style={{ width: 36, height: 36, borderRadius: 18, background: 'rgba(255,255,255,0.08)', backdropFilter: 'blur(20px)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transform: visible ? `translateY(${refreshing ? 30 : pull * 30}px)` : 'translateY(-30px)',
                    opacity: visible ? Math.min(1, pull * 1.5) : 0,
                    transition: 'opacity .2s, transform .2s' }}>
        <div style={{ width: 18, height: 18, borderRadius: 9, border: `2px solid ${t.accent}`, borderRightColor: 'transparent',
                      animation: refreshing ? 'c-spin 0.8s linear infinite' : 'none',
                      transform: refreshing ? 'none' : `rotate(${pull * 360}deg)` }}/>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// HOME
// ─────────────────────────────────────────────────────────────
function HomeScreen() {
  const nav = useRouter();
  const { tw, setTweak } = useApp();
  const L = STRINGS[tw.lang];
  const v = VEHICLES[tw.model];
  const fuelDisplay = useTween(tw.fuel, 700);

  const [showSkeleton, setShowSkeleton] = React.useState(tw.showLoading);
  React.useEffect(() => { setShowSkeleton(tw.showLoading); }, [tw.showLoading]);

  if (showSkeleton) return <HomeSkeleton/>;

  return (
    <ScreenShell onPull={async () => {
      setShowSkeleton(true);
      await new Promise((r) => setTimeout(r, 900));
      setShowSkeleton(false);
    }}>
      <div style={{ padding: '6px 18px 20px', position: 'relative' }} className="c-stagger">
        {tw.offline && <OfflineBanner/>}

        {/* Greeting */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16, animation: 'c-fade-in .4s' }}>
          <div>
            <div style={{ fontSize: 11, color: t.textDim, fontFamily: t.mono, letterSpacing: 1.5, textTransform: 'uppercase' }}>{L[greetKey()]}</div>
            <div style={{ fontSize: 26, fontWeight: 400, letterSpacing: -0.5, marginTop: 2 }}>An Nguyễn</div>
          </div>
          <div onClick={() => nav.go('notifications')} style={{ width: 42, height: 42, borderRadius: 21, background: 'rgba(255,255,255,0.05)',
                        display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(20px)',
                        border: '1px solid rgba(255,255,255,0.06)', position: 'relative', cursor: 'pointer' }}>
            <Icons.bell size={20}/>
            <div style={{ position: 'absolute', top: 9, right: 10, width: 8, height: 8, borderRadius: 4,
                          background: t.accent, border: `2px solid ${t.bg}` }}/>
          </div>
        </div>

        {/* Hero vehicle card */}
        <GlassC padding={18} radius={26} intensity={tw.glass} style={{ marginBottom: 12, cursor: 'pointer' }} accentLine
                onClick={() => nav.tab('drive')}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 10, fontFamily: t.mono, color: t.textDim, letterSpacing: 1.5 }}>{v.trim.toUpperCase()}</div>
              <div style={{ fontSize: 22, fontWeight: 500, marginTop: 4, letterSpacing: -0.4 }}>{v.name}</div>
              <div style={{ fontSize: 11, color: t.textDim, fontFamily: t.mono, marginTop: 2 }}>{v.plate}</div>
            </div>
            <LockPill locked={tw.locked} L={L}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>
            <CarSideModel model={tw.model} width={300} color={v.color}/>
          </div>
        </GlassC>

        {/* Widget grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {/* Fuel wide */}
          <GlassC padding={16} radius={24} intensity={tw.glass}
                  style={{ gridColumn: 'span 2', display: 'flex', alignItems: 'center', gap: 18 }}>
            <Ring pct={fuelDisplay} size={84} color={t.accent} label={Math.round(fuelDisplay) + '%'}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, fontFamily: t.mono, color: t.textDim, letterSpacing: 1 }}>{L.fuel} · RON95</div>
              <div style={{ fontSize: 28, fontWeight: 300, letterSpacing: -0.6, marginTop: 4 }}>
                ≈ <span style={{ fontVariantNumeric: 'tabular-nums' }}>{Math.round(fuelDisplay * 6.4)}</span> <span style={{ fontSize: 13, color: t.textDim }}>km</span>
              </div>
              <div style={{ marginTop: 6, fontSize: 11, color: t.textDim }}>
                {Math.round(fuelDisplay * 0.42)} L · {fmtVND(Math.round(fuelDisplay * 0.42 * 21340))}
              </div>
            </div>
          </GlassC>

          <GlassC padding={14} radius={24} intensity={tw.glass}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ color: t.accent2 }}><Icons.battery size={18}/></div>
              <div style={{ fontSize: 10, color: t.ok, padding: '2px 6px', borderRadius: 4, background: 'rgba(101,212,154,0.12)' }}>OK</div>
            </div>
            <div style={{ fontSize: 11, color: t.textDim, marginTop: 14 }}>{L.battery}</div>
            <div style={{ fontSize: 22, fontWeight: 500, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4 }}>12.6 <span style={{ fontSize: 11, color: t.textDim }}>V</span></div>
          </GlassC>

          <GlassC padding={14} radius={24} intensity={tw.glass}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div style={{ color: t.accent }}><Icons.tire size={18}/></div>
              <div style={{ fontSize: 10, color: t.ok, padding: '2px 6px', borderRadius: 4, background: 'rgba(101,212,154,0.12)' }}>OK</div>
            </div>
            <div style={{ fontSize: 11, color: t.textDim, marginTop: 14 }}>{L.tires}</div>
            <div style={{ fontSize: 22, fontWeight: 500, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4 }}>240 <span style={{ fontSize: 11, color: t.textDim }}>kPa</span></div>
          </GlassC>

          {/* Lock toggle widget — card opens Remote, button opens confirm */}
          <GlassC padding={16} radius={24} intensity={tw.glass}
                  style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', cursor: 'pointer' }}
                  onClick={() => nav.go('remote')}>
            <div style={{ color: tw.locked ? t.ok : t.warn }}>{tw.locked ? <Icons.lock size={22}/> : <Icons.unlock size={22}/>}</div>
            <div onClick={(e) => { e.stopPropagation(); nav.openSheet('lockConfirm'); }}
                 style={{ marginTop: 16, padding: '10px 14px', borderRadius: 14,
                                                                      background: tw.locked ? t.accent : 'rgba(232,184,114,0.18)',
                                                                      color: tw.locked ? t.accentInk : t.warn,
                                                                      textAlign: 'center', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
              {tw.locked ? L.unlock : L.lock}
            </div>
          </GlassC>

          <GlassC padding={16} radius={24} intensity={tw.glass} style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', cursor: 'pointer' }}
                  onClick={() => nav.go('remote')}>
            <div style={{ color: t.accent2 }}><Icons.fan size={22}/></div>
            <div>
              <div style={{ fontSize: 11, color: t.textDim }}>{L.climate}</div>
              <div style={{ fontSize: 26, fontWeight: 300, letterSpacing: -0.6, marginTop: 2 }}>22<span style={{ fontSize: 14, color: t.textDim }}>°C</span></div>
            </div>
          </GlassC>

          {/* Find my car wide */}
          <GlassC padding={14} radius={24} intensity={tw.glass}
                  style={{ gridColumn: 'span 2', height: 120, position: 'relative', overflow: 'hidden', cursor: 'pointer' }}
                  onClick={() => nav.go('find')}>
            <div style={{ position: 'absolute', inset: 0, opacity: 0.5 }}><HanoiMap/></div>
            <div style={{ position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ color: t.accent }}><Icons.pin size={18}/></div>
                <div style={{ fontSize: 11, fontFamily: t.mono, color: t.textDim, letterSpacing: 1 }}>{L.parkedAt.toUpperCase()}</div>
                <div style={{ flex: 1 }}/>
                <div style={{ fontSize: 11, color: t.text, fontFamily: t.mono }}>{T(tw.lang, '0.4 km away →', '0,4 km →')}</div>
              </div>
              <div style={{ fontSize: 18, fontWeight: 500, marginTop: 6, letterSpacing: -0.3 }}>Vincom Bà Triệu</div>
              <div style={{ fontSize: 11, color: t.textDim, marginTop: 2 }}>{T(tw.lang, 'P3 · Slot B-142', 'Tầng 3 · Chỗ B-142')}</div>
            </div>
          </GlassC>

          {/* Trip card */}
          <GlassC padding={14} radius={24} intensity={tw.glass}
                  style={{ gridColumn: 'span 2', cursor: 'pointer' }}
                  onClick={() => nav.go('trip')}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
              <div style={{ fontSize: 11, fontFamily: t.mono, color: t.textDim, letterSpacing: 1 }}>{T(tw.lang, 'THIS WEEK', 'TUẦN NÀY')}</div>
              <div style={{ fontSize: 11, color: t.accent }}>{T(tw.lang, 'View all →', 'Xem tất cả →')}</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 5, height: 42 }}>
              {[28, 42, 18, 51, 38, 22, 64].map((h, i) => (
                <div key={i} style={{ flex: 1, height: h + '%', background: i === 6 ? t.accent : 'rgba(212,165,116,0.3)',
                                      borderRadius: 3, animation: 'c-bar-grow .5s cubic-bezier(.4,0,.2,1) backwards',
                                      animationDelay: (i * 0.05) + 's', transformOrigin: 'bottom' }}/>
              ))}
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 10 }}>
              <div>
                <div style={{ fontSize: 24, fontWeight: 300, letterSpacing: -0.5 }}>263 <span style={{ fontSize: 12, color: t.textDim }}>km</span></div>
                <div style={{ fontSize: 10, fontFamily: t.mono, color: t.textDim, marginTop: 2 }}>{T(tw.lang, 'SCORE 87 · ECO', 'ĐIỂM 87 · TIẾT KIỆM')}</div>
              </div>
              <div style={{ display: 'flex', gap: 14, fontSize: 10, color: t.textDim, fontFamily: t.mono }}>
                {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => <span key={i} style={i === 6 ? { color: t.accent } : {}}>{d}</span>)}
              </div>
            </div>
          </GlassC>

          {/* Weather */}
          {tw.showWeather !== false && (
            <GlassC padding={14} radius={24} intensity={tw.glass}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={t.accent2} strokeWidth="1.5">
                  <circle cx="12" cy="12" r="4"/>
                  <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/>
                </svg>
                <div style={{ fontSize: 11, color: t.textDim, fontFamily: t.mono }}>{T(tw.lang, 'HANOI', 'HÀ NỘI')}</div>
              </div>
              <div style={{ fontSize: 26, fontWeight: 300, letterSpacing: -0.6, marginTop: 8, fontVariantNumeric: 'tabular-nums' }}>24<span style={{ fontSize: 14, color: t.textDim }}>°C</span></div>
              <div style={{ fontSize: 10, color: t.textDim, fontFamily: t.mono, marginTop: 2 }}>{T(tw.lang, 'SUNNY · AQI 82', 'NẮNG · AQI 82')}</div>
            </GlassC>
          )}

          {/* Fuel price */}
          {tw.showFuelPrice !== false && (
            <GlassC padding={14} radius={24} intensity={tw.glass}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ color: t.accent }}><Icons.fuel size={18}/></div>
                <div style={{ fontSize: 11, color: t.textDim, fontFamily: t.mono }}>RON95</div>
                <div style={{ flex: 1 }}/>
                <div style={{ fontSize: 10, color: t.ok }}>↓ 0.8%</div>
              </div>
              <div style={{ fontSize: 22, fontWeight: 500, marginTop: 8, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.4 }}>21,340<span style={{ fontSize: 11, color: t.textDim, fontWeight: 400 }}>/L</span></div>
              <div style={{ fontSize: 10, color: t.textDim, fontFamily: t.mono, marginTop: 2 }}>{T(tw.lang, 'UPDATED 06:00', 'CẬP NHẬT 06:00')}</div>
            </GlassC>
          )}
        </div>
      </div>
    </ScreenShell>
  );
}

function LockPill({ locked, L }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 999,
                  background: locked ? 'rgba(101,212,154,0.14)' : 'rgba(232,184,114,0.14)',
                  color: locked ? t.ok : t.warn, fontSize: 11, fontWeight: 600, transition: 'all .2s' }}>
      <div style={{ width: 6, height: 6, borderRadius: 3, background: 'currentColor' }}/>
      {locked ? L.locked : L.unlocked}
    </div>
  );
}

function OfflineBanner() {
  const { tw, setTweak } = useApp();
  const toast = useToast();
  return (
    <div style={{ marginBottom: 12, padding: '10px 14px', borderRadius: 14, background: 'rgba(232,72,72,0.14)',
                  border: '1px solid rgba(232,72,72,0.3)', display: 'flex', alignItems: 'center', gap: 10,
                  animation: 'c-fall .35s' }}>
      <div style={{ width: 8, height: 8, borderRadius: 4, background: '#E84848', animation: 'c-pulse-strong 1.4s infinite' }}/>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 12, fontWeight: 600 }}>{T(tw.lang, 'Connection lost', 'Mất kết nối')}</div>
        <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.6)', marginTop: 1 }}>{T(tw.lang, 'Vehicle data may be out of date', 'Dữ liệu xe có thể không cập nhật')}</div>
      </div>
      <div onClick={() => { setTweak('offline', false); toast.push(T(tw.lang, 'Reconnected', 'Đã kết nối lại')); }}
           style={{ fontSize: 11, color: '#E84848', fontWeight: 600, cursor: 'pointer' }}>{T(tw.lang, 'Retry', 'Thử lại')}</div>
    </div>
  );
}

function HomeSkeleton() {
  return (
    <ScreenShell scroll={false}>
      <div style={{ padding: '6px 18px 20px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <div>
            <Skeleton w={80} h={10}/>
            <div style={{ height: 8 }}/>
            <Skeleton w={140} h={22}/>
          </div>
          <Skeleton w={42} h={42} r={21}/>
        </div>
        <Skeleton w="100%" h={170} r={26}/>
        <div style={{ height: 12 }}/>
        <Skeleton w="100%" h={110} r={24}/>
        <div style={{ height: 12 }}/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Skeleton w="100%" h={90} r={24}/>
          <Skeleton w="100%" h={90} r={24}/>
          <Skeleton w="100%" h={120} r={24}/>
          <Skeleton w="100%" h={120} r={24}/>
        </div>
      </div>
    </ScreenShell>
  );
}

function Skeleton({ w, h, r = 12 }) {
  return (
    <div style={{ width: w, height: h, borderRadius: r,
                  background: 'linear-gradient(110deg, rgba(255,255,255,0.04), rgba(255,255,255,0.07), rgba(255,255,255,0.04))',
                  backgroundSize: '200% 100%', animation: 'shimmer-bg 1.4s ease-in-out infinite' }}/>
  );
}

if (!document.getElementById('c-skel')) {
  const s = document.createElement('style');
  s.id = 'c-skel';
  s.textContent = '@keyframes shimmer-bg { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }';
  document.head.appendChild(s);
}

// ─────────────────────────────────────────────────────────────
// VEHICLE STATUS
// ─────────────────────────────────────────────────────────────
function VehicleScreen() {
  const nav = useRouter();
  const { tw } = useApp();
  const L = STRINGS[tw.lang];
  const v = VEHICLES[tw.model];
  const fuelDisplay = useTween(tw.fuel, 700);

  return (
    <ScreenShell>
      <div style={{ padding: '6px 18px 20px' }} className="c-stagger">
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 11, fontFamily: t.mono, color: t.textDim, letterSpacing: 1 }}>{T(tw.lang, 'HEALTH · LIVE', 'TÌNH TRẠNG · TRỰC TIẾP')}</div>
            <div style={{ fontSize: 26, fontWeight: 400, letterSpacing: -0.5, marginTop: 2 }}>{v.name}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: t.ok, padding: '4px 10px', borderRadius: 999, background: 'rgba(101,212,154,0.14)' }}>
            <div style={{ width: 6, height: 6, borderRadius: 3, background: t.ok, animation: 'c-pulse-strong 2s infinite' }}/>
            {T(tw.lang, '3m ago', '3 phút trước')}
          </div>
        </div>

        {/* Topdown hero */}
        <GlassC padding={20} radius={26} intensity={tw.glass} style={{ marginBottom: 14, display: 'flex', justifyContent: 'center', position: 'relative' }}>
          <CarTopdownModel model={tw.model} width={140} color={v.color}/>
          {[
            { top: 50, left: 36, label: '240', sub: 'FL' },
            { top: 50, right: 36, label: '238', sub: 'FR' },
            { top: 168, left: 36, label: '242', sub: 'RL' },
            { top: 168, right: 36, label: '239', sub: 'RR' },
          ].map((d, i) => (
            <div key={i} style={{ position: 'absolute', top: d.top, left: d.left, right: d.right, textAlign: 'center' }}>
              <div style={{ fontSize: 9, color: t.textDim, fontFamily: t.mono, letterSpacing: 1 }}>{d.sub}</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: t.ok, fontVariantNumeric: 'tabular-nums' }}>{d.label}</div>
            </div>
          ))}
        </GlassC>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <KpiRing label={T(tw.lang, 'FUEL', 'NHIÊN LIỆU')}   val={Math.round(fuelDisplay)} unit="%" pct={fuelDisplay} color={t.accent} intensity={tw.glass}/>
          <KpiRing label={T(tw.lang, 'BATTERY', 'ẮC-QUY')}    val={12.6} unit="V" pct={92} color={t.ok} intensity={tw.glass}/>
          <KpiRing label={T(tw.lang, 'OIL', 'NHỚT')}            val={65} unit="%" pct={65} color={t.warn} intensity={tw.glass}/>
          <KpiRing label={T(tw.lang, 'BRAKE', 'PHÁNH')}          val={88} unit="%" pct={88} color={t.accent2} intensity={tw.glass}/>
        </div>

        <GlassC padding={16} radius={24} intensity={tw.glass} style={{ marginTop: 12, cursor: 'pointer' }} onClick={() => nav.go('trip')}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div style={{ fontSize: 10, fontFamily: t.mono, color: t.textDim, letterSpacing: 1 }}>{T(tw.lang, 'LAST 7 DAYS', '7 NGÀY QUA')}</div>
            <div style={{ fontSize: 11, color: t.accent }}>{T(tw.lang, 'Trip history →', 'Lịch sử →')}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 60 }}>
            {[28, 42, 18, 51, 38, 22, 64].map((h, i) => (
              <div key={i} style={{ flex: 1, height: h + '%', background: i === 6 ? t.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: t.textDim, fontFamily: t.mono }}>
            {['M', 'T', 'W', 'T', 'F', 'S', 'S'].map((d, i) => <span key={i}>{d}</span>)}
          </div>
        </GlassC>

        <GlassC padding={16} radius={24} intensity={tw.glass} style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer' }}
                onClick={() => nav.go('remote')}>
          <div style={{ width: 38, height: 38, borderRadius: 19, background: 'rgba(212,165,116,0.14)', color: t.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icons.signal size={18}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{L.remoteControl}</div>
            <div style={{ fontSize: 11, color: t.textDim, marginTop: 2 }}>{T(tw.lang, 'Lock, climate, engine, horn, lights', 'Khóa, điều hòa, máy, còi, đèn')}</div>
          </div>
          <Icons.chev size={16}/>
        </GlassC>

        <GlassC padding={16} radius={24} intensity={tw.glass} style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 38, height: 38, borderRadius: 19, background: 'rgba(232,184,114,0.14)', color: t.warn, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icons.wrench size={18}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{STRINGS[tw.lang].nextService}</div>
            <div style={{ fontSize: 11, color: t.textDim, marginTop: 2 }}>{T(tw.lang, 'In 2,300 km · ~ 3 weeks', 'Còn 2,300 km · ~ 3 tuần')}</div>
          </div>
          <button onClick={() => nav.tab('service')} style={{ padding: '8px 12px', borderRadius: 14, border: 'none', background: t.accent, color: t.accentInk, fontSize: 11, fontWeight: 600, fontFamily: t.font, cursor: 'pointer' }}>{L.bookService}</button>
        </GlassC>
      </div>
    </ScreenShell>
  );
}

function KpiRing({ label, val, unit, pct, color, intensity }) {
  return (
    <GlassC padding={14} radius={24} intensity={intensity}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <Ring pct={pct} size={56} stroke={5} color={color}/>
        <div>
          <div style={{ fontSize: 10, color: t.textDim, fontFamily: t.mono, letterSpacing: 1 }}>{label}</div>
          <div style={{ fontSize: 20, fontWeight: 500, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>
            {Math.round(val * 10) / 10}<span style={{ fontSize: 12, color: t.textDim }}>{unit}</span>
          </div>
        </div>
      </div>
    </GlassC>
  );
}

// ─────────────────────────────────────────────────────────────
// REMOTE
// ─────────────────────────────────────────────────────────────
function RemoteScreen() {
  const nav = useRouter();
  const { tw, setTweak } = useApp();
  const L = STRINGS[tw.lang];
  const v = VEHICLES[tw.model];
  const [temp, setTemp] = React.useState(22);
  const [climateOn, setClimateOn] = React.useState(false);

  return (
    <ScreenShell>
      <div style={{ padding: '6px 18px 20px' }} className="c-stagger">
        <BackHeader title={L.remoteControl} subtitle={`${v.name} · ${v.plate}`}/>

        {/* Hero lock button */}
        <GlassC padding={0} radius={26} intensity={tw.glass} style={{
          height: 220, marginBottom: 14, position: 'relative', overflow: 'hidden',
          background: tw.locked
            ? 'linear-gradient(135deg, rgba(212,165,116,0.22), rgba(212,165,116,0.04))'
            : 'linear-gradient(135deg, rgba(232,184,114,0.28), rgba(232,184,114,0.06))',
        }}>
          <div onClick={() => nav.openSheet('lockConfirm')}
               style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
            <div style={{ position: 'relative', width: 96, height: 96 }}>
              {/* pulse rings */}
              <div style={{ position: 'absolute', inset: 0, borderRadius: 48, border: `1px solid ${tw.locked ? t.accent : t.warn}`, animation: 'c-pulse-strong 2.4s ease-out infinite' }}/>
              <div style={{ position: 'absolute', inset: 0, borderRadius: 48, border: `1px solid ${tw.locked ? t.accent : t.warn}`, animation: 'c-pulse-strong 2.4s ease-out infinite', animationDelay: '0.8s' }}/>
              <div style={{ position: 'absolute', inset: 0, borderRadius: 48,
                            background: tw.locked ? t.accent : t.warn,
                            display: 'flex', alignItems: 'center', justifyContent: 'center', color: t.accentInk,
                            boxShadow: '0 12px 36px rgba(0,0,0,0.4)' }}>
                {tw.locked ? <Icons.lock size={42} stroke={1.6}/> : <Icons.unlock size={42} stroke={1.6}/>}
              </div>
            </div>
            <div style={{ fontSize: 22, fontWeight: 500, marginTop: 18, letterSpacing: -0.4 }}>{tw.locked ? L.locked : L.unlocked}</div>
            <div style={{ fontSize: 11, color: t.textDim, marginTop: 4, fontFamily: t.mono, letterSpacing: 1 }}>{T(tw.lang, 'TAP TO ', 'NHẤN ĐỂ ')}{tw.locked ? L.unlock.toUpperCase() : L.lock.toUpperCase()}</div>
          </div>
        </GlassC>

        {/* Climate */}
        <GlassC padding={18} radius={24} intensity={tw.glass}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ color: t.accent2 }}><Icons.fan size={20}/></div>
              <div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{L.climate}</div>
                <div style={{ fontSize: 11, color: t.textDim, marginTop: 1 }}>{climateOn ? T(tw.lang, 'Pre-conditioning · 12 min remaining', 'Đang điều hòa · còn 12 phút') : T(tw.lang, 'Off', 'Tắt')}</div>
              </div>
            </div>
            <div onClick={() => setClimateOn(!climateOn)} style={{ width: 52, height: 30, borderRadius: 15, background: climateOn ? t.accent : 'rgba(255,255,255,0.1)', position: 'relative', cursor: 'pointer', transition: 'background .2s' }}>
              <div style={{ position: 'absolute', top: 3, left: climateOn ? 25 : 3, width: 24, height: 24, borderRadius: 12, background: '#fff', transition: 'left .2s' }}/>
            </div>
          </div>
          <div style={{ opacity: climateOn ? 1 : 0.4, transition: 'opacity .2s' }}>
            <div style={{ position: 'relative', height: 130, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="200" height="130" viewBox="0 0 200 130" style={{ position: 'absolute' }}>
                <path d="M 20 100 A 80 80 0 0 1 180 100" stroke="rgba(255,255,255,0.08)" strokeWidth="6" fill="none" strokeLinecap="round"/>
                <path d="M 20 100 A 80 80 0 0 1 180 100" stroke={t.accent} strokeWidth="6" fill="none" strokeLinecap="round"
                      strokeDasharray="251" strokeDashoffset={251 - 251 * ((temp - 16) / 14)}
                      style={{ transition: 'stroke-dashoffset .35s cubic-bezier(.4,0,.2,1)' }}/>
              </svg>
              <div style={{ position: 'relative', textAlign: 'center', marginTop: 10 }}>
                <div style={{ fontSize: 64, fontWeight: 200, lineHeight: 1, letterSpacing: -3, fontVariantNumeric: 'tabular-nums' }}>{temp}<span style={{ fontSize: 22, color: t.textDim }}>°</span></div>
                <div style={{ fontSize: 11, color: t.textDim, fontFamily: t.mono, letterSpacing: 1, marginTop: 4 }}>{L.cabinTemp.toUpperCase()}</div>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, gap: 8 }}>
              <button onClick={() => climateOn && setTemp(Math.max(16, temp - 1))}
                      style={{ width: 48, height: 48, borderRadius: 24, border: '1px solid rgba(255,255,255,0.1)', background: 'rgba(255,255,255,0.04)', color: t.text, fontSize: 22, cursor: 'pointer' }}>−</button>
              <button onClick={() => nav.openSheet('climatePresets')}
                      style={{ flex: 1, height: 48, borderRadius: 24, border: '1px solid rgba(255,255,255,0.1)', background: 'rgba(255,255,255,0.04)', color: t.text, fontSize: 12, fontWeight: 500, fontFamily: t.font, cursor: 'pointer' }}>
                {T(tw.lang, 'Presets · 4', 'Cài đặt · 4')}
              </button>
              <button onClick={() => climateOn && setTemp(Math.min(30, temp + 1))}
                      style={{ width: 48, height: 48, borderRadius: 24, border: '1px solid rgba(255,255,255,0.1)', background: 'rgba(255,255,255,0.04)', color: t.text, fontSize: 22, cursor: 'pointer' }}>+</button>
            </div>
          </div>
        </GlassC>

        {/* Quick actions */}
        <div style={{ marginTop: 12 }}>
          <div style={{ fontSize: 10, fontFamily: t.mono, color: t.textDim, letterSpacing: 1, marginBottom: 10, padding: '0 4px' }}>
            {T(tw.lang, 'QUICK ACTIONS', 'THAO TÁC NHANH')}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
            <ActionTile icon="engine" label={L.engine}              onClick={() => nav.openSheet('engineStart')}/>
            <ActionTile icon="horn"   label={L.horn}                onClick={() => nav.openSheet('hornFeedback')}/>
            <ActionTile icon="flash"  label={L.flash}               onClick={() => nav.openSheet('flashFeedback')}/>
          </div>
        </div>

        {/* Body controls — windows, trunk, hood */}
        <div style={{ marginTop: 18 }}>
          <div style={{ fontSize: 10, fontFamily: t.mono, color: t.textDim, letterSpacing: 1, marginBottom: 10, padding: '0 4px' }}>
            {T(tw.lang, 'BODY', 'THÂN XE')}
          </div>
          <GlassC padding={0} radius={20} intensity={tw.glass}>
            <BodyControlRow icon="windows"   label={T(tw.lang, 'Windows',    'Cửa kính')}
                            sub={T(tw.lang, 'All up', 'Đã đóng')}
                            onAction={() => nav.openSheet('windowsControl')}/>
            <BodyControlRow icon="trunk"     label={T(tw.lang, 'Trunk',      'Cốp sau')}
                            sub={T(tw.lang, 'Closed', 'Đã đóng')}
                            onAction={() => nav.openSheet('trunkControl')}/>
            <BodyControlRow icon="hood"      label={T(tw.lang, 'Hood',       'Nắp ca-pô')}
                            sub={T(tw.lang, 'Closed · safety lock engaged', 'Đã đóng · khóa an toàn')}
                            onAction={() => nav.openSheet('hoodControl')}
                            last/>
          </GlassC>
        </div>
      </div>
    </ScreenShell>
  );
}

function ActionTile({ icon, label, onClick }) {
  const I = Icons[icon];
  const { tw } = useApp();
  return (
    <GlassC padding={14} intensity={tw.glass} radius={24}
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, cursor: 'pointer' }}
            onClick={onClick}>
      <div style={{ width: 40, height: 40, borderRadius: 20, background: 'rgba(212,165,116,0.14)', color: t.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <I size={18}/>
      </div>
      <div style={{ fontSize: 11, fontWeight: 500, textAlign: 'center' }}>{label}</div>
    </GlassC>
  );
}

// Body-control row used in the Remote screen for Windows / Trunk / Hood.
// Tapping the row opens a dedicated sheet to perform the action.
function BodyControlRow({ icon, label, sub, onAction, last }) {
  const I = BodyIcons[icon];
  return (
    <div onClick={onAction}
         style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14, cursor: 'pointer',
                  borderBottom: last ? 'none' : '1px solid rgba(255,255,255,0.05)' }}>
      <div style={{ width: 38, height: 38, borderRadius: 12, background: 'rgba(212,165,116,0.14)', color: t.accent,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <I size={20}/>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{label}</div>
        <div style={{ fontSize: 11, color: t.textDim, marginTop: 2 }}>{sub}</div>
      </div>
      <Icons.chev size={14}/>
    </div>
  );
}

// Body-specific SVG icons (windows / trunk / hood).
const BodyIcons = {
  windows: ({ size = 20 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2"/>
      <path d="M3 12h18"/><path d="M12 5v14"/>
    </svg>
  ),
  trunk: ({ size = 20 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 17V9a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v8"/>
      <path d="M3 17h18v3H3z"/>
      <path d="M9 13h6"/>
    </svg>
  ),
  hood: ({ size = 20 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 16l3-8a2 2 0 0 1 2-1h8a2 2 0 0 1 2 1l3 8"/>
      <path d="M3 16h18v3H3z"/>
      <path d="M12 7v6"/>
    </svg>
  ),
};

window.BodyIcons = BodyIcons;
window.BodyControlRow = BodyControlRow;

function BackHeader({ title, subtitle, action }) {
  const nav = useRouter();
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
      <div onClick={nav.back} style={{ width: 40, height: 40, borderRadius: 20, background: 'rgba(255,255,255,0.05)',
                                       display: 'flex', alignItems: 'center', justifyContent: 'center',
                                       border: '1px solid rgba(255,255,255,0.06)', cursor: 'pointer', flexShrink: 0 }}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={t.text} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 18l-6-6 6-6"/></svg>
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 19, fontWeight: 500, letterSpacing: -0.4 }}>{title}</div>
        {subtitle && <div style={{ fontSize: 11, color: t.textDim, fontFamily: t.mono, marginTop: 1 }}>{subtitle}</div>}
      </div>
      {action}
    </div>
  );
}

window.HomeScreen = HomeScreen;
window.VehicleScreen = VehicleScreen;
window.RemoteScreen = RemoteScreen;
window.BackHeader = BackHeader;
window.ScreenShell = ScreenShell;
window.GlassC_t = t;  // expose theme for other screen files
window.OfflineBanner = OfflineBanner;
