// Sheets / overlays for the C prototype.
// Rendered above the screen layer when route.sheet is set.

const t4 = THEMES.c;

function Sheet({ onClose, children, height = 'auto' }) {
  // Slide-up animation handled by CSS animation class.
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  // Drag-to-dismiss: a downward pull on the handle translates the sheet;
  // releasing past ~80px commits the dismiss, otherwise it springs back.
  // Tapping the handle without dragging also dismisses (iOS-style convenience).
  const [dy, setDy] = React.useState(0);
  const dragRef = React.useRef(null);  // { y0, lastDy }

  const onDown = (e) => {
    e.stopPropagation();
    const y = e.touches ? e.touches[0].clientY : e.clientY;
    dragRef.current = { y0: y, lastDy: 0 };
  };
  const onMove = (e) => {
    if (!dragRef.current) return;
    const y = e.touches ? e.touches[0].clientY : e.clientY;
    const d = Math.max(0, y - dragRef.current.y0);
    dragRef.current.lastDy = d;
    setDy(d);
  };
  const onUp = (e) => {
    if (!dragRef.current) return;
    const d = dragRef.current.lastDy;
    dragRef.current = null;
    if (d > 80) onClose();        // drag past threshold — dismiss
    else setDy(0);                // tap or partial drag — spring back
  };

  const dragging = dragRef.current != null;

  return (
    <div onClick={onClose}
         style={{ position: 'absolute', inset: 0, zIndex: 200,
                  background: `rgba(0,0,0,${0.55 - Math.min(0.4, dy / 600)})`,
                  backdropFilter: 'blur(8px)',
                  display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
                  animation: 'c-fade-in .2s', transition: dragging ? 'none' : 'background .2s' }}>
      <div onClick={(e) => e.stopPropagation()}
           style={{ background: 'rgba(20,25,30,0.96)', backdropFilter: 'blur(40px) saturate(180%)',
                    borderTopLeftRadius: 28, borderTopRightRadius: 28,
                    borderTop: '1px solid rgba(255,255,255,0.08)',
                    padding: '0 0 36px', height,
                    transform: dy ? `translateY(${dy}px)` : 'none',
                    transition: dragging ? 'none' : 'transform .25s cubic-bezier(.4,0,.2,1)',
                    animation: dy ? 'none' : 'c-sheet-up .35s cubic-bezier(.4,0,.2,1)' }}>
        {/* Handle — tappable + draggable to dismiss. Wider hit area than
            the visible bar (28px tall) so it's easy to grab on touch. */}
        <div onMouseDown={onDown} onMouseMove={onMove} onMouseUp={onUp} onMouseLeave={onUp}
             onTouchStart={onDown} onTouchMove={onMove} onTouchEnd={onUp}
             style={{ width: '100%', padding: '12px 0', display: 'flex', justifyContent: 'center',
                      cursor: 'grab', touchAction: 'none' }}>
          <div style={{ width: 36, height: 4, borderRadius: 2,
                        background: dragging ? 'rgba(255,255,255,0.45)' : 'rgba(255,255,255,0.22)',
                        transition: 'background .15s' }}/>
        </div>
        {children}
      </div>
    </div>
  );
}

if (!document.getElementById('c-sheet-anim')) {
  const s = document.createElement('style');
  s.id = 'c-sheet-anim';
  s.textContent = '@keyframes c-sheet-up { from { transform: translateY(100%); } to { transform: translateY(0); } }';
  document.head.appendChild(s);
}

// ─────────────────────────────────────────────────────────────
// Lock confirm — hold to confirm with PIN fallback
// ─────────────────────────────────────────────────────────────
function LockConfirmSheet() {
  const nav = useRouter();
  const { tw, setTweak } = useApp();
  const L = STRINGS[tw.lang];
  const [progress, setProgress] = React.useState(0);   // 0..100
  const holding = React.useRef(false);
  const raf = React.useRef(null);

  const start = () => {
    holding.current = true;
    const t0 = performance.now();
    const tick = (now) => {
      if (!holding.current) return;
      const p = Math.min(100, ((now - t0) / 1100) * 100);
      setProgress(p);
      if (p >= 100) {
        setTimeout(() => {
          setTweak('locked', !tw.locked);
          nav.closeSheet();
        }, 120);
        return;
      }
      raf.current = requestAnimationFrame(tick);
    };
    raf.current = requestAnimationFrame(tick);
  };
  const stop = () => {
    holding.current = false;
    cancelAnimationFrame(raf.current);
    setProgress(0);
  };

  return (
    <Sheet onClose={nav.closeSheet}>
      <div style={{ padding: '6px 28px 0', textAlign: 'center' }}>
        <div style={{ fontSize: 11, fontFamily: t4.mono, color: t4.textDim, letterSpacing: 2, textTransform: 'uppercase' }}>Confirm</div>
        <div style={{ fontSize: 24, fontWeight: 400, letterSpacing: -0.5, marginTop: 6 }}>
          {tw.locked ? L.confirmUnlockQ : L.confirmLockQ}
        </div>
        <div style={{ fontSize: 13, color: t4.textDim, marginTop: 6, lineHeight: 1.5 }}>
          {tw.locked ? L.confirmUnlockBody : L.confirmLockBody}
        </div>

        <div onMouseDown={start} onMouseUp={stop} onMouseLeave={stop}
             onTouchStart={start} onTouchEnd={stop}
             style={{ position: 'relative', margin: '28px auto 0', width: 200, height: 200, cursor: 'pointer', userSelect: 'none' }}>
          {/* Background circle */}
          <svg width="200" height="200" viewBox="0 0 200 200" style={{ position: 'absolute', inset: 0, transform: 'rotate(-90deg)' }}>
            <circle cx="100" cy="100" r="92" stroke="rgba(255,255,255,0.08)" strokeWidth="6" fill="none"/>
            <circle cx="100" cy="100" r="92" stroke={tw.locked ? t4.warn : t4.accent} strokeWidth="6" fill="none"
                    strokeLinecap="round"
                    strokeDasharray={2 * Math.PI * 92}
                    strokeDashoffset={2 * Math.PI * 92 * (1 - progress / 100)}/>
          </svg>
          <div style={{ position: 'absolute', inset: 24, borderRadius: 76,
                        background: tw.locked ? t4.warn : t4.accent, color: t4.accentInk,
                        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                        boxShadow: '0 12px 36px rgba(0,0,0,0.4)',
                        transform: progress > 0 ? 'scale(0.96)' : 'scale(1)', transition: 'transform .15s' }}>
            {tw.locked ? <Icons.unlock size={42} stroke={1.6}/> : <Icons.lock size={42} stroke={1.6}/>}
            <div style={{ fontSize: 12, fontWeight: 600, marginTop: 8, letterSpacing: 1 }}>{T(tw.lang, 'HOLD', 'GIỮ')}</div>
          </div>
        </div>

        <div style={{ fontSize: 12, color: t4.textDim, marginTop: 18, fontFamily: t4.mono, letterSpacing: 1 }}>{T(tw.lang, 'HOLD TO CONFIRM', 'GIỮ ĐỂ XÁC NHẬN')}</div>

          <button onClick={nav.closeSheet}
                style={{ marginTop: 24, width: '100%', height: 48, border: '1px solid rgba(255,255,255,0.1)', borderRadius: 24, background: 'transparent', color: t4.text, fontSize: 14, fontFamily: t4.font, cursor: 'pointer' }}>
          {T(tw.lang, 'Cancel', 'Hủy')}
        </button>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Climate presets
// ─────────────────────────────────────────────────────────────
function ClimatePresetsSheet() {
  const nav = useRouter();
  const { tw } = useApp();
  const presets = [
    { id: 'eco', name: T(tw.lang, 'Eco', 'Tiết kiệm'), sub: T(tw.lang, 'Quiet · low fan', 'Yên tĩnh · quạt nhẹ'), temp: 25, fan: 1, icon: '🌿', color: t4.ok },
    { id: 'comfort', name: T(tw.lang, 'Comfort', 'Thoải mái'), sub: T(tw.lang, 'Default', 'Mặc định'), temp: 22, fan: 3, icon: '☉', color: t4.accent, sel: true },
    { id: 'cold', name: T(tw.lang, 'Cool', 'Mát lạnh'), sub: T(tw.lang, 'Max cool · high fan', 'Lạnh sâu · quạt mạnh'), temp: 18, fan: 5, icon: '❄', color: t4.accent2 },
    { id: 'defrost', name: T(tw.lang, 'Defrost', 'Xả băng'), sub: T(tw.lang, 'Front + rear glass', 'Kính trước + sau'), temp: 24, fan: 5, icon: '◆', color: t4.warn },
  ];
  return (
    <Sheet onClose={nav.closeSheet}>
      <div style={{ padding: '6px 24px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 11, fontFamily: t4.mono, color: t4.textDim, letterSpacing: 2 }}>{T(tw.lang, 'CLIMATE PRESETS', 'CHẾ ĐỘ ĐIỀU HÒA')}</div>
            <div style={{ fontSize: 22, fontWeight: 400, letterSpacing: -0.4, marginTop: 4 }}>{T(tw.lang, 'Choose a preset', 'Chọn chế độ')}</div>
          </div>
          <button onClick={nav.closeSheet}
                  style={{ width: 36, height: 36, borderRadius: 18, border: 'none', background: 'rgba(255,255,255,0.06)', color: t4.text, fontSize: 18, cursor: 'pointer' }}>×</button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {presets.map((p) => (
            <div key={p.id} onClick={nav.closeSheet}
                 style={{ padding: 16, borderRadius: 20, cursor: 'pointer',
                          border: `1px solid ${p.sel ? p.color : 'rgba(255,255,255,0.08)'}`,
                          background: p.sel ? `${p.color}14` : 'rgba(255,255,255,0.03)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                <div style={{ width: 36, height: 36, borderRadius: 12, background: `${p.color}22`, color: p.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>{p.icon}</div>
                {p.sel && <div style={{ width: 8, height: 8, borderRadius: 4, background: p.color }}/>}
              </div>
              <div style={{ fontSize: 15, fontWeight: 500 }}>{p.name}</div>
              <div style={{ fontSize: 11, color: t4.textDim, marginTop: 2 }}>{p.sub}</div>
              <div style={{ display: 'flex', gap: 10, marginTop: 12, fontSize: 11, color: t4.textDim, fontFamily: t4.mono }}>
                <div style={{ fontSize: 11, color: t4.textDim, fontFamily: t4.mono }}>{p.temp}°C</div>
                <div>·</div>
                <div>{T(tw.lang, `Fan ${p.fan}/7`, `Quạt ${p.fan}/7`)}</div>
              </div>
            </div>
          ))}
        </div>

        <div onClick={nav.closeSheet} style={{ marginTop: 18, padding: '14px 18px', borderRadius: 14, background: 'rgba(255,255,255,0.04)',
                                                display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}>
          <div style={{ width: 36, height: 36, borderRadius: 12, background: 'rgba(212,165,116,0.14)', color: t4.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icons.plus size={20}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{T(tw.lang, 'Save current as preset', 'Lưu cài đặt hiện tại')}</div>
            <div style={{ fontSize: 11, color: t4.textDim, marginTop: 1 }}>22°C · {T(tw.lang, 'Fan 3 · auto', 'Quạt 3 · tự động')}</div>
          </div>
        </div>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Service success
// ─────────────────────────────────────────────────────────────
function ServiceSuccessSheet({ total, dealer, time, date, suggested }) {
  const nav = useRouter();
  const { tw } = useApp();
  return (
    <Sheet onClose={() => { nav.closeSheet(); nav.tab('home'); }}>
      <div style={{ padding: '20px 28px 0', textAlign: 'center' }}>
        <div style={{ position: 'relative', width: 80, height: 80, margin: '0 auto 22px' }}>
          <div style={{ position: 'absolute', inset: 0, borderRadius: 40, border: `1px solid ${t4.ok}`, animation: 'c-pulse-strong 2s infinite' }}/>
          <div style={{ position: 'absolute', inset: 0, borderRadius: 40, background: t4.ok, display: 'flex', alignItems: 'center', justifyContent: 'center', color: t4.bg, animation: 'c-pop .3s' }}>
            <Icons.check size={40} stroke={2.5}/>
          </div>
        </div>
        <div style={{ fontSize: 22, fontWeight: 400, letterSpacing: -0.5, marginBottom: 8 }}>{T(tw.lang, 'Appointment booked', 'Đã đặt lịch')}</div>
        <div style={{ fontSize: 13, color: t4.textDim, lineHeight: 1.5 }}>{T(tw.lang, 'You’ll get a reminder the day before. Cancel anytime up to 24 hours ahead.', 'Bạn sẽ nhận nhắc nhở một ngày trước. Có thể hủy miễn phí trong vòng 24 giờ.')}</div>
      </div>

      <div style={{ padding: '24px 24px 0' }}>
        <GlassC padding={16} radius={20} intensity={1} style={{ background: 'rgba(255,255,255,0.04)' }}>
          {[
            { l: T(tw.lang, 'Dealer', 'Đại lý'),       v: dealer?.n || 'Thaco Long Biên' },
            { l: T(tw.lang, 'Service', 'Dịch vụ'),    v: suggested || T(tw.lang, '10,000 km maintenance', 'Bảo dưỡng 10,000 km') },
            { l: T(tw.lang, 'Date · time', 'Ngày · giờ'), v: `${date || 'T4 21'} · ${time || '09:30'}` },
            { l: T(tw.lang, 'Estimated', 'Dự kiến'),    v: '~ ' + fmtVND(total || 1850000) },
            { l: T(tw.lang, 'Booking ID', 'Mã đặt lịch'), v: '#MZ-26-0184' },
          ].map((r, i) => (
            <div key={i} style={{ padding: '10px 0', display: 'flex', justifyContent: 'space-between', borderTop: i ? '1px solid rgba(255,255,255,0.05)' : 'none' }}>
              <div style={{ fontSize: 12, color: t4.textDim }}>{r.l}</div>
              <div style={{ fontSize: 13, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{r.v}</div>
            </div>
          ))}
        </GlassC>

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <button onClick={nav.closeSheet}
                  style={{ flex: 1, height: 48, border: '1px solid rgba(255,255,255,0.1)', borderRadius: 24, background: 'transparent', color: t4.text, fontSize: 13, fontFamily: t4.font, cursor: 'pointer' }}>
            {T(tw.lang, 'Add to Calendar', 'Thêm vào Lịch')}
          </button>
          <button onClick={() => { nav.closeSheet(); nav.tab('home'); }}
                  style={{ flex: 1, height: 48, border: 'none', borderRadius: 24, background: t4.accent, color: t4.accentInk, fontSize: 13, fontWeight: 600, fontFamily: t4.font, cursor: 'pointer' }}>
            {T(tw.lang, 'Done', 'Xong')}
          </button>
        </div>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Horn feedback — short audio + visual pulse, auto-dismiss
// ─────────────────────────────────────────────────────────────
function HornFeedbackOverlay() {
  const nav = useRouter();
  const { tw } = useApp();
  React.useEffect(() => {
    const tm = setTimeout(() => nav.closeSheet(), 1800);
    return () => clearTimeout(tm);
  }, []);
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 200,
                  background: 'rgba(212,165,116,0.12)', backdropFilter: 'blur(8px)',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 22 }}>
      <div style={{ position: 'relative', width: 140, height: 140 }}>
        {[0, 0.3, 0.6].map((d) => (
          <div key={d} style={{ position: 'absolute', inset: 0, borderRadius: 70, border: `2px solid ${t4.accent}`, animation: `c-pulse-strong 1.4s ease-out infinite ${d}s` }}/>
        ))}
        <div style={{ position: 'absolute', inset: 0, borderRadius: 70, background: t4.accent, color: t4.accentInk, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 0 60px rgba(212,165,116,0.6)' }}>
          <Icons.horn size={56} stroke={1.4}/>
        </div>
      </div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontSize: 22, fontWeight: 500, color: '#fff' }}>{T(tw.lang, 'Horn · sounding', 'Còi · đang kêu')}</div>
        <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>{T(tw.lang, 'Listen for your car', 'Lắng nghe tiếng xe')}</div>
      </div>
      {/* sound bars */}
      <div style={{ display: 'flex', gap: 4, alignItems: 'flex-end', height: 30 }}>
        {[1, 2, 3, 4, 5, 4, 3, 2, 1].map((h, i) => (
          <div key={i} style={{ width: 3, height: h * 6, background: t4.accent, borderRadius: 1.5, animation: `c-sound 1s ease-in-out infinite`, animationDelay: (i * 0.1) + 's' }}/>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Flash feedback — full-screen flash burst
// ─────────────────────────────────────────────────────────────
function FlashFeedbackOverlay() {
  const nav = useRouter();
  const { tw } = useApp();
  React.useEffect(() => {
    const tm = setTimeout(() => nav.closeSheet(), 1600);
    return () => clearTimeout(tm);
  }, []);
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 200, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: '#fff', animation: 'c-flash 0.7s 2' }}/>
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)',
                    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20 }}>
        <div style={{ width: 120, height: 120, borderRadius: 60, background: 'rgba(255,255,255,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
          <Icons.flash size={56} stroke={1.4}/>
        </div>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 22, fontWeight: 500, color: '#fff' }}>{T(tw.lang, 'Headlights flashing', 'Đèn pha đang nháy')}</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>{T(tw.lang, 'Look for the blink', 'Tìm ánh đèn nháy')}</div>
        </div>
      </div>
    </div>
  );
}

// Inject sound bar keyframes
if (!document.getElementById('c-sound')) {
  const s = document.createElement('style');
  s.id = 'c-sound';
  s.textContent = '@keyframes c-sound { 0%, 100% { transform: scaleY(0.3); } 50% { transform: scaleY(1); } }';
  document.head.appendChild(s);
}

// ─────────────────────────────────────────────────────────────
// Logout confirm
// ─────────────────────────────────────────────────────────────
function LogoutConfirmSheet() {
  const nav = useRouter();
  const { tw } = useApp();
  const L = STRINGS[tw.lang];
  return (
    <Sheet onClose={nav.closeSheet}>
      <div style={{ padding: '14px 28px 0', textAlign: 'center' }}>
        <div style={{ width: 64, height: 64, borderRadius: 32, background: 'rgba(232,72,72,0.18)', color: '#E84848',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
          </svg>
        </div>
        <div style={{ fontSize: 22, fontWeight: 400, letterSpacing: -0.4, marginBottom: 8 }}>
          {T(tw.lang, 'Log out of M·Connect?', 'Đăng xuất khỏi M·Connect?')}
        </div>
        <div style={{ fontSize: 13, color: t4.textDim, lineHeight: 1.5, maxWidth: 290, margin: '0 auto' }}>
          {T(tw.lang,
            'You\u2019ll need to sign in again to control your vehicle remotely. Saved trips and history remain on your account.',
            'Bạn sẽ cần đăng nhập lại để điều khiển xe từ xa. Lịch sử và chuyến đi đã lưu vẫn còn trong tài khoản của bạn.')}
        </div>

        <div style={{ display: 'flex', gap: 10, marginTop: 28 }}>
          <button onClick={nav.closeSheet}
                  style={{ flex: 1, height: 52, border: '1px solid rgba(255,255,255,0.12)', borderRadius: 26,
                           background: 'rgba(255,255,255,0.04)', color: t4.text, fontSize: 14, fontWeight: 500, fontFamily: t4.font, cursor: 'pointer' }}>
            {T(tw.lang, 'Cancel', 'Hủy')}
          </button>
          <button onClick={() => { nav.closeSheet(); nav.replace('login'); }}
                  style={{ flex: 1, height: 52, border: 'none', borderRadius: 26,
                           background: '#E84848', color: '#fff', fontSize: 14, fontWeight: 600, fontFamily: t4.font, cursor: 'pointer' }}>
            {T(tw.lang, 'Log out', 'Đăng xuất')}
          </button>
        </div>
      </div>
    </Sheet>
  );
}

window.LogoutConfirmSheet = LogoutConfirmSheet;
window.LockConfirmSheet = LockConfirmSheet;
window.ClimatePresetsSheet = ClimatePresetsSheet;
window.ServiceSuccessSheet = ServiceSuccessSheet;
window.HornFeedbackOverlay = HornFeedbackOverlay;
window.FlashFeedbackOverlay = FlashFeedbackOverlay;
