// Public-facing screens: Landing, Login, Shop, ProductDetail, Checkout, CheckoutSuccess
const { useState: useStateP, useMemo: useMemoP } = React;

// ----- Public top bar (transparent on landing) -----
function PublicTopBar({ nav, transparent }) {
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: transparent ? 'transparent' : 'rgba(250,247,242,0.85)',
      backdropFilter: transparent ? 'none' : 'blur(12px) saturate(140%)',
      borderBottom: transparent ? 'none' : '1px solid var(--line)',
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 28px', height: 72, display: 'flex', alignItems: 'center', gap: 24 }}>
        <button onClick={() => nav('/')} style={{ background: 'transparent', border: 'none', padding: 0, cursor: 'pointer' }}><Logo size={22} /></button>
        <nav style={{ display: 'flex', gap: 4, marginLeft: 12 }}>
          {[
            { label: 'ระบบ', path: '/#systems' },
            { label: 'ร้านค้า', path: '/shop' },
            { label: 'ราคา', path: '/pricing' },
            { label: 'เกี่ยวกับ', path: '/about' },
          ].map(it => (
            <button key={it.path} onClick={() => nav(it.path)} style={{
              background: 'transparent', border: 'none', padding: '8px 14px',
              cursor: 'pointer', fontSize: 14, color: 'var(--ink-2)', borderRadius: 999,
            }}>{it.label}</button>
          ))}
        </nav>
        <div style={{ flex: 1 }} />
        <button onClick={() => nav('/login')} style={{ background: 'transparent', border: 'none', padding: '8px 14px', cursor: 'pointer', fontSize: 14, fontWeight: 500 }}>เข้าสู่ระบบ</button>
        <Button variant="primary" size="md" onClick={() => nav('/login?mode=signup')}>เริ่มฟรี</Button>
      </div>
    </div>
  );
}

// ----- Landing -----
function Landing({ nav }) {
  return (
    <div>
      <PublicTopBar nav={nav} />
      {/* HERO */}
      <section style={{ padding: '80px 28px 100px', position: 'relative', overflow: 'hidden' }}>
        <div style={{ maxWidth: 1100, margin: '0 auto', textAlign: 'center', position: 'relative' }}>
          <Badge tone="primary" style={{ marginBottom: 24 }}>
            <span style={{ width: 6, height: 6, background: 'var(--success)', borderRadius: 999, marginRight: 4 }} />
            ใช้งานแล้ว 2,840 ครู/ครีเอเตอร์ทั่วประเทศ
          </Badge>
          <h1 className="display" style={{ margin: 0, fontSize: 'clamp(40px, 6vw, 68px)', fontWeight: 600, letterSpacing: '-0.03em', lineHeight: 1.05 }}>
            เครื่องมือ AI<br />
            <span style={{ color: 'var(--primary)' }}>สำหรับครูและครีเอเตอร์ไทย</span>
          </h1>
          <p style={{ margin: '24px auto 0', fontSize: 18, color: 'var(--ink-2)', maxWidth: 620, lineHeight: 1.6 }}>
            ครบทุกระบบที่จำเป็นสำหรับขายผลงานบน Kindle, TPT และแพลตฟอร์มอื่น — สมัครครั้งเดียว ใช้ได้ทุกระบบ
          </p>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 36 }}>
            <Button variant="primary" size="xl" iconRight="arrowRight" onClick={() => nav('/login?mode=signup')}>เริ่มฟรี</Button>
            <Button variant="secondary" size="xl" onClick={() => nav('/shop')}>ดูสินค้า</Button>
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 24, marginTop: 24, fontSize: 13, color: 'var(--ink-3)' }}>
            <span>✓ ไม่ต้องใช้บัตรเครดิต</span>
            <span>✓ ภาษาไทย 100%</span>
            <span>✓ รองรับ PromptPay</span>
          </div>
        </div>
      </section>

      {/* SYSTEMS */}
      <section id="systems" style={{ padding: '40px 28px 80px', background: 'var(--bg-2)' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: 48 }}>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>4 ระบบหลัก</div>
            <h2 className="display" style={{ margin: 0, fontSize: 40, fontWeight: 600, letterSpacing: '-0.02em' }}>ทุกอย่างที่คุณต้องการ ในที่เดียว</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
            {SYSTEMS.map(sys => (
              <Card key={sys.key} padding={28} hover onClick={() => nav('/shop?cat=' + sys.key)}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, marginBottom: 16 }}>
                  <SystemGlyph system={sys.key} size={56} rounded={14} />
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <h3 className="display" style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>{sys.name}</h3>
                      {sys.status === 'pre-order' && <Badge tone="accent" size="sm">เร็วๆ นี้</Badge>}
                    </div>
                    <div style={{ fontSize: 14, color: 'var(--ink-2)' }}>{sys.tagline}</div>
                  </div>
                </div>
                <p style={{ margin: 0, fontSize: 14.5, color: 'var(--ink-2)', lineHeight: 1.65 }}>{sys.description}</p>
                <div style={{ marginTop: 20, fontSize: 14, fontWeight: 500, color: 'var(--primary-ink)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                  เรียนรู้เพิ่ม <I name="arrowRight" size={14} />
                </div>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* SOCIAL PROOF */}
      <section style={{ padding: '80px 28px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 32, marginBottom: 64, padding: '32px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
            {[
              { v: '2,840+', l: 'สมาชิก' },
              { v: '14.2M฿', l: 'ยอดขายรวมจากผู้ใช้' },
              { v: '380K+', l: 'ใบงานที่สร้างใน Lumo' },
              { v: '4.9/5', l: 'คะแนนรีวิว' },
            ].map(s => (
              <div key={s.l} style={{ textAlign: 'center' }}>
                <div className="display" style={{ fontSize: 38, fontWeight: 600, letterSpacing: '-0.02em' }}>{s.v}</div>
                <div style={{ fontSize: 13.5, color: 'var(--ink-3)', marginTop: 4 }}>{s.l}</div>
              </div>
            ))}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
            {TESTIMONIALS.map(t => (
              <Card key={t.name} padding={24}>
                <div style={{ display: 'flex', gap: 1, marginBottom: 12, color: 'var(--warn)' }}>
                  {[1,2,3,4,5].map(i => <I key={i} name="star" size={14} fill="currentColor" />)}
                </div>
                <p style={{ margin: '0 0 16px', fontSize: 15, lineHeight: 1.6, textWrap: 'pretty' }}>"{t.text}"</p>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Avatar name={t.name} size={36} />
                  <div>
                    <div style={{ fontSize: 13.5, fontWeight: 500 }}>{t.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{t.role}</div>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* HOW */}
      <section style={{ padding: '80px 28px', background: 'var(--bg-2)' }}>
        <div style={{ maxWidth: 1100, margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: 56 }}>
            <h2 className="display" style={{ margin: 0, fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em' }}>เริ่มต้นใน 3 ขั้นตอน</h2>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
            {[
              { n: '01', t: 'สมัครสมาชิก', d: 'ฟรี ไม่ต้องใช้บัตรเครดิต ใช้อีเมลหรือ Google' },
              { n: '02', t: 'เลือกระบบที่ใช้', d: 'Academy, SEO, Lumo หรือซื้อ Bundle ทั้งหมด' },
              { n: '03', t: 'เริ่มสร้างผลงาน', d: 'ใช้ AI ทำใบงาน, หา keyword, เขียน ebook ขาย' },
            ].map(s => (
              <Card key={s.n} padding={24}>
                <div className="display" style={{ fontSize: 36, fontWeight: 600, color: 'var(--primary)', letterSpacing: '-0.02em', marginBottom: 8 }}>{s.n}</div>
                <h4 className="display" style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{s.t}</h4>
                <p style={{ margin: '6px 0 0', fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>{s.d}</p>
              </Card>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: '80px 28px' }}>
        <div style={{ maxWidth: 900, margin: '0 auto', textAlign: 'center' }}>
          <h2 className="display" style={{ margin: 0, fontSize: 44, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
            พร้อมเริ่มสร้างรายได้แล้วหรือยัง?
          </h2>
          <p style={{ margin: '20px auto 32px', fontSize: 17, color: 'var(--ink-2)', maxWidth: 540 }}>เริ่มฟรี ไม่ต้องใช้บัตรเครดิต ยกเลิกได้ตลอด</p>
          <Button variant="accent" size="xl" iconRight="arrowRight" onClick={() => nav('/login?mode=signup')}>เริ่มต้นใช้งาน</Button>
        </div>
      </section>

      {/* FOOTER */}
      <footer style={{ background: 'var(--ink)', color: 'rgba(250,247,242,0.7)', padding: '56px 28px 32px' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 32, marginBottom: 40 }}>
            <div>
              <Logo size={20} color="#FAF7F2" />
              <p style={{ margin: '16px 0 0', fontSize: 14, lineHeight: 1.6, maxWidth: 320 }}>เครื่องมือสำหรับครูและครีเอเตอร์ไทยที่อยากเริ่มขายผลงานออนไลน์</p>
            </div>
            {[
              { h: 'ผลิตภัณฑ์', items: ['Academy', 'SEO Tool', 'Lumo', 'Muze (เร็วๆ นี้)'] },
              { h: 'บริษัท', items: ['เกี่ยวกับเรา', 'บล็อก', 'ติดต่อ', 'ร่วมงาน'] },
              { h: 'กฎหมาย', items: ['เงื่อนไขการใช้งาน', 'ความเป็นส่วนตัว', 'นโยบายคืนเงิน'] },
            ].map(col => (
              <div key={col.h}>
                <div style={{ fontSize: 13, fontWeight: 500, color: '#FAF7F2', marginBottom: 14 }}>{col.h}</div>
                <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {col.items.map(i => <li key={i} style={{ fontSize: 13.5 }}>{i}</li>)}
                </ul>
              </div>
            ))}
          </div>
          <div style={{ paddingTop: 24, borderTop: '1px solid rgba(255,255,255,0.1)', display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
            <span>© 2026 KindleStartup. สงวนลิขสิทธิ์</span>
            <span>kindlestartup.com</span>
          </div>
        </div>
      </footer>
    </div>
  );
}

// ----- Login -----
function Login({ nav, route }) {
  const initSignup = route.includes('signup');
  const [mode, setMode] = useStateP(initSignup ? 'signup' : 'login');
  const [email, setEmail] = useStateP('');
  const [password, setPassword] = useStateP('');
  const [name, setName] = useStateP('');
  const [error, setError] = useStateP('');
  const [message, setMessage] = useStateP('');
  const [loading, setLoading] = useStateP(false);

  return (
    <div style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
      {/* Left visual */}
      <div style={{ background: 'linear-gradient(160deg, #2A2520 0%, #4A3A2A 100%)', color: '#F5EFE2', padding: '48px', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden' }}>
        <Logo size={22} color="#F5EFE2" />
        <div style={{ flex: 1, display: 'flex', alignItems: 'center' }}>
          <div>
            <h1 className="display" style={{ margin: 0, fontSize: 44, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.1 }}>
              สมัครครั้งเดียว<br />
              <span style={{ color: '#D4A373' }}>ใช้ได้ทุกระบบ</span>
            </h1>
            <p style={{ margin: '20px 0 32px', fontSize: 16, color: 'rgba(245,239,226,0.75)', maxWidth: 380, lineHeight: 1.6 }}>
              บัญชีเดียวเข้าถึง Academy, SEO Tool, Lumo และ Muze
            </p>
            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
              {SYSTEMS.map(s => (
                <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', background: 'rgba(255,255,255,0.08)', borderRadius: 999, fontSize: 13 }}>
                  <SystemGlyph system={s.key} size={20} rounded={6} />
                  {s.name}
                </div>
              ))}
            </div>
          </div>
        </div>
        <div style={{ fontSize: 12.5, color: 'rgba(245,239,226,0.5)' }}>© 2026 KindleStartup</div>
      </div>

      {/* Right form */}
      <div style={{ padding: '48px', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', background: 'var(--bg)' }}>
        <div style={{ width: '100%', maxWidth: 380 }}>
          <button onClick={() => nav('/')} style={{ background: 'transparent', border: 'none', cursor: 'pointer', fontSize: 13.5, color: 'var(--ink-3)', padding: 0, marginBottom: 32, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <I name="arrowLeft" size={14} /> กลับหน้าหลัก
          </button>
          <h2 className="display" style={{ margin: 0, fontSize: 30, fontWeight: 600, letterSpacing: '-0.02em' }}>
            {mode === 'login' ? 'ยินดีต้อนรับกลับ' : 'สร้างบัญชีฟรี'}
          </h2>
          <p style={{ margin: '6px 0 28px', fontSize: 14, color: 'var(--ink-2)' }}>
            {mode === 'login' ? 'เข้าสู่ระบบเพื่อใช้งาน' : 'ใช้เวลาแค่ 30 วินาที'}
          </p>

          <Button variant="secondary" full size="lg" icon="google" disabled={loading} onClick={async () => {
            setError(''); setLoading(true);
            try { await Auth.signInWithGoogle(); }
            catch (err) { setError(err.message); setLoading(false); }
          }}>
            ดำเนินการต่อด้วย Google
          </Button>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '20px 0', color: 'var(--ink-3)', fontSize: 12 }}>
            <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
            หรือ
            <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
          </div>

          <form onSubmit={async e => {
            e.preventDefault();
            setError(''); setLoading(true);
            try {
              if (mode === 'login') {
                await Auth.signInWithPassword(email, password);
              } else {
                await Auth.signUp(email, password, name);
              }
              nav('/dashboard');
            } catch (err) {
              setError(err.message || 'เข้าสู่ระบบไม่สำเร็จ');
              setLoading(false);
            }
          }} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {mode === 'signup' && (
              <Input label="ชื่อ" placeholder="ชื่อที่คุณอยากให้แสดง" value={name} onChange={e => setName(e.target.value)} />
            )}
            <Input label="อีเมล" type="email" placeholder="you@example.com" icon="mail" value={email} onChange={e => setEmail(e.target.value)} required />
            <Input label="รหัสผ่าน" type="password" placeholder="••••••••" icon="lock" value={password} onChange={e => setPassword(e.target.value)} required />
            {mode === 'login' && (
              <div style={{ textAlign: 'right' }}>
                <button type="button" onClick={async () => {
                  if (!email) { setError('กรอกอีเมลก่อนค่ะ'); return; }
                  setError('');
                  try {
                    await Auth.resetPassword(email);
                    setMessage('ส่งลิงก์รีเซ็ตรหัสผ่านไปที่ ' + email + ' แล้วค่ะ');
                  } catch (err) { setError(err.message); }
                }} style={{ background: 'transparent', border: 'none', fontSize: 13, color: 'var(--ink-2)', cursor: 'pointer', padding: 0 }}>ลืมรหัสผ่าน?</button>
              </div>
            )}
            {error && <div style={{ padding: '10px 12px', background: 'var(--danger-soft)', color: 'var(--danger)', borderRadius: 8, fontSize: 13 }}>⚠️ {error}</div>}
            {message && <div style={{ padding: '10px 12px', background: 'var(--success-soft)', color: 'var(--success)', borderRadius: 8, fontSize: 13 }}>✓ {message}</div>}
            <Button variant="primary" size="lg" full type="submit" disabled={loading} style={{ marginTop: 4 }}>
              {loading ? 'กำลังประมวลผล…' : (mode === 'login' ? 'เข้าสู่ระบบ' : 'สร้างบัญชี')}
            </Button>
            <button type="button" onClick={async () => {
              if (!email) { setError('กรอกอีเมลก่อนค่ะ'); return; }
              setError('');
              try {
                await Auth.signInWithMagicLink(email);
                setMessage('ส่งลิงก์เข้าระบบไปที่ ' + email + ' แล้วค่ะ');
              } catch (err) { setError(err.message); }
            }} style={{ background: 'transparent', border: 'none', fontSize: 13.5, color: 'var(--ink-2)', cursor: 'pointer', padding: 8 }}>
              ส่ง Magic Link เข้าอีเมลแทน
            </button>
          </form>

          <div style={{ marginTop: 24, textAlign: 'center', fontSize: 14, color: 'var(--ink-2)' }}>
            {mode === 'login' ? 'ยังไม่มีบัญชี?' : 'มีบัญชีอยู่แล้ว?'}{' '}
            <button onClick={() => setMode(mode === 'login' ? 'signup' : 'login')} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink)', fontWeight: 500, padding: 0 }}>
              {mode === 'login' ? 'สมัครฟรี' : 'เข้าสู่ระบบ'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ----- Shop -----
function Shop({ nav, route }) {
  const initCat = decodeURIComponent((route.match(/cat=([^&]+)/) || [])[1] || 'ทั้งหมด');
  const [cat, setCat] = useStateP(initCat);
  const [sort, setSort] = useStateP('แนะนำ');
  // Type-based categories
  const cats = ['ทั้งหมด', 'โปรแกรม', 'คอร์ส', 'อีบุ๊ค', 'อื่นๆ'];
  const catIcons = {
    'ทั้งหมด': 'package',
    'โปรแกรม': 'sparkle',
    'คอร์ส': 'book',
    'อีบุ๊ค': 'feather',
    'อื่นๆ': 'grid',
  };

  const sortFn = (list) => {
    if (sort === 'ราคาต่ำ-สูง') return [...list].sort((a, b) => a.price - b.price);
    if (sort === 'ราคาสูง-ต่ำ') return [...list].sort((a, b) => b.price - a.price);
    return list;
  };

  const programs = useMemoP(() => sortFn(PRODUCTS.filter(p => p.type === 'โปรแกรม')), [sort]);
  const courses = useMemoP(() => sortFn(PRODUCTS.filter(p => p.type === 'คอร์ส')), [sort]);
  const ebooks = useMemoP(() => sortFn(PRODUCTS.filter(p => p.type === 'อีบุ๊ค')), [sort]);
  const others = useMemoP(() => sortFn(PRODUCTS.filter(p => p.type === 'อื่นๆ')), [sort]);

  // Legacy system-based deep-link handling
  const isSystem = ['Academy', 'SEO', 'Lumo', 'Muze', 'Bundle'].includes(cat);
  const filteredAll = useMemoP(() => {
    if (cat === 'ทั้งหมด') return null; // sectioned mode
    return sortFn(isSystem ? PRODUCTS.filter(p => p.system === cat) : PRODUCTS.filter(p => p.type === cat));
  }, [cat, sort]);

  // Section header
  const SectionH = ({ icon, title, sub, count }) => (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 16, marginTop: 8, gap: 12 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--ink)', color: 'var(--bg)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
          <I name={icon} size={17} />
        </div>
        <div>
          <h2 className="display" style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', display: 'flex', alignItems: 'baseline', gap: 10 }}>
            {title}
            <span style={{ fontSize: 13, color: 'var(--ink-3)', fontWeight: 400 }}>{count} รายการ</span>
          </h2>
          {sub && <p style={{ margin: '2px 0 0', fontSize: 13, color: 'var(--ink-3)' }}>{sub}</p>}
        </div>
      </div>
    </div>
  );

  return (
    <div>
      <UserTopBar nav={nav} />
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '32px 28px 80px' }}>
        <div style={{ marginBottom: 28 }}>
          <h1 className="display" style={{ margin: 0, fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em' }}>ร้านค้า</h1>
          <p style={{ margin: '6px 0 0', fontSize: 15, color: 'var(--ink-2)' }}>
            {cat === 'ทั้งหมด' ? `${PRODUCTS.length} รายการ ทุกหมวด` : `${(filteredAll || []).length} รายการในหมวด ${cat}`}
          </p>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginBottom: 32, flexWrap: 'wrap', position: 'sticky', top: 64, zIndex: 5, background: 'var(--bg)', padding: '8px 0', borderBottom: '1px solid var(--line)' }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {cats.map(c => {
              const count = c === 'ทั้งหมด'
                ? PRODUCTS.length
                : PRODUCTS.filter(p => p.type === c).length;
              const active = cat === c;
              return (
                <button key={c} onClick={() => setCat(c)} style={{
                  padding: '8px 14px', borderRadius: 999,
                  background: active ? 'var(--ink)' : 'var(--surface)',
                  color: active ? 'var(--bg)' : 'var(--ink-2)',
                  border: '1px solid ' + (active ? 'var(--ink)' : 'var(--line)'),
                  cursor: 'pointer', fontSize: 13.5, fontWeight: 500,
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  transition: 'all .15s',
                }}>
                  <I name={catIcons[c]} size={14} />
                  {c}
                  <span style={{
                    fontSize: 11, fontWeight: 500,
                    padding: '1px 6px', borderRadius: 999,
                    background: active ? 'rgba(255,255,255,0.18)' : 'var(--bg-2)',
                    color: active ? 'rgba(255,255,255,0.85)' : 'var(--ink-3)',
                    fontVariantNumeric: 'tabular-nums',
                  }}>{count}</span>
                </button>
              );
            })}
          </div>
          <select value={sort} onChange={e => setSort(e.target.value)} style={{
            padding: '8px 14px', borderRadius: 999, border: '1px solid var(--line-2)',
            background: 'var(--surface)', fontSize: 13.5, cursor: 'pointer',
          }}>
            <option>แนะนำ</option><option>ใหม่ล่าสุด</option><option>ราคาต่ำ-สูง</option><option>ราคาสูง-ต่ำ</option>
          </select>
        </div>

        {cat === 'ทั้งหมด' ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 56 }}>
            {/* Programs — same size as Courses (3 cols) */}
            {programs.length > 0 && (
              <section>
                <SectionH icon="sparkle" title="โปรแกรม" sub="ระบบใช้งาน รายเดือน/รายปี — ใจกลางของ KindleStartup" count={programs.length} />
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
                  {programs.map(p => <ProductCard key={p.id} p={p} nav={nav} variant="medium" />)}
                </div>
              </section>
            )}

            {/* Courses — medium (3 cols) */}
            {courses.length > 0 && (
              <section>
                <SectionH icon="book" title="คอร์ส" sub="คอร์สเรียนแบบเป็นระบบ ใช้ได้ตลอดชีพ" count={courses.length} />
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
                  {courses.map(p => <ProductCard key={p.id} p={p} nav={nav} variant="medium" />)}
                </div>
              </section>
            )}

            {/* Ebooks + Others — small (4 cols, list-style mini) */}
            {(ebooks.length > 0 || others.length > 0) && (
              <section>
                <SectionH icon="grid" title="อีบุ๊ค & อื่นๆ" sub="หนังสือ workbook รายงาน และของแถมเสริม" count={ebooks.length + others.length} />
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                  {[...ebooks, ...others].map(p => <ProductCard key={p.id} p={p} nav={nav} variant="mini" />)}
                </div>
              </section>
            )}
          </div>
        ) : (
          // Single-category view: use the natural size of that type
          <div style={{
            display: 'grid',
            gridTemplateColumns: (cat === 'โปรแกรม' || cat === 'คอร์ส') ? 'repeat(3, 1fr)' : 'repeat(4, 1fr)',
            gap: (cat === 'โปรแกรม' || cat === 'คอร์ส') ? 16 : 12,
          }}>
            {(filteredAll || []).map(p => (
              <ProductCard
                key={p.id} p={p} nav={nav}
                variant={(cat === 'โปรแกรม' || cat === 'คอร์ส') ? 'medium' : 'mini'}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function ProductCard({ p, nav, variant = 'medium' }) {
  const sys = SYSTEMS.find(s => s.key === p.system);
  const badgeTone = p.badge ? (p.badge.includes('ส่วนลด') || p.badge.includes('คุ้ม') ? 'accent' : p.badge === 'Pre-order' ? 'primary' : 'success') : null;

  // HERO — large 2-up cards for Programs
  if (variant === 'hero') {
    return (
      <Card padding={0} hover onClick={() => nav('/shop/' + p.id)} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
        <Placeholder ratio="16/9" tone={p.tone} rounded={0} style={{ borderBottom: '1px solid var(--line)', minHeight: 220 }}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
            {sys && <SystemGlyph system={p.system} size={72} rounded={18} />}
            <div style={{ fontSize: 12, opacity: 0.55, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{p.system}</div>
          </div>
        </Placeholder>
        <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
          <div style={{ display: 'flex', gap: 6, minHeight: 22 }}>
            <Badge tone="outline" size="sm">โปรแกรม</Badge>
            {p.badge && <Badge tone={badgeTone} size="sm">{p.badge}</Badge>}
          </div>
          <h3 className="display" style={{ margin: 0, fontSize: 20, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1.3, textWrap: 'pretty' }}>{p.name}</h3>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, marginTop: 'auto', paddingTop: 8 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span className="display" style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em' }}>{p.price ? '฿' + p.price.toLocaleString() : 'Coming Soon'}</span>
              {p.sub && <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>{p.sub}</span>}
              {p.oldPrice && <span style={{ fontSize: 13, color: 'var(--ink-3)', textDecoration: 'line-through' }}>฿{p.oldPrice.toLocaleString()}</span>}
            </div>
            <Button variant="primary" size="sm" iconRight="arrowRight">ดูรายละเอียด</Button>
          </div>
        </div>
      </Card>
    );
  }

  // MINI — small 4-up for ebooks/others (compact horizontal style)
  if (variant === 'mini') {
    return (
      <Card padding={0} hover onClick={() => nav('/shop/' + p.id)} style={{ overflow: 'hidden' }}>
        <Placeholder ratio="3/2" tone={p.tone} rounded={0} style={{ borderBottom: '1px solid var(--line)' }}>
          {sys && <SystemGlyph system={p.system} size={28} rounded={8} />}
        </Placeholder>
        <div style={{ padding: 12 }}>
          <div style={{ fontSize: 10.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 500, marginBottom: 4 }}>
            {p.type}
          </div>
          <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.35, marginBottom: 8, minHeight: 36, textWrap: 'pretty' }}>{p.name}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 6 }}>
            <span className="display" style={{ fontSize: 16, fontWeight: 600 }}>{p.price ? '฿' + p.price.toLocaleString() : 'Coming Soon'}</span>
            {p.badge && <Badge tone={badgeTone} size="sm">{p.badge}</Badge>}
          </div>
        </div>
      </Card>
    );
  }

  // MEDIUM (default) — 3-up for courses
  return (
    <Card padding={0} hover onClick={() => nav('/shop/' + p.id)} style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <Placeholder ratio="4/3" tone={p.tone} rounded={0} style={{ borderBottom: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
          {sys && <SystemGlyph system={p.system} size={44} rounded={12} />}
          <div style={{ fontSize: 11, opacity: 0.6, fontWeight: 500 }}>{p.type || p.system}</div>
        </div>
      </Placeholder>
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', flex: 1 }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 8, minHeight: 22 }}>
          {p.badge && <Badge tone={badgeTone} size="sm">{p.badge}</Badge>}
        </div>
        <div style={{
          fontSize: 14, fontWeight: 500, lineHeight: 1.4, marginBottom: 12,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
          overflow: 'hidden', minHeight: 40,
        }}>{p.name}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 'auto' }}>
          <span className="display" style={{ fontSize: 20, fontWeight: 600 }}>{p.price ? '฿' + p.price.toLocaleString() : 'Coming Soon'}</span>
          {p.sub && <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>{p.sub}</span>}
          {p.oldPrice && <span style={{ fontSize: 12, color: 'var(--ink-3)', textDecoration: 'line-through' }}>฿{p.oldPrice.toLocaleString()}</span>}
        </div>
      </div>
    </Card>
  );
}

// ----- Product Detail -----
function ProductDetail({ nav, route }) {
  const id = route.split('/')[2];
  const p = PRODUCTS.find(x => x.id === id) || PRODUCTS[0];
  const d = PRODUCT_DETAILS[p.id] || {};
  const [tab, setTab] = useStateP('details');
  const sys = SYSTEMS.find(s => s.key === p.system);
  const reviewCount = 218;
  const related = (d.related || []).map(rid => PRODUCTS.find(x => x.id === rid)).filter(Boolean);

  return (
    <div>
      <UserTopBar nav={nav} />
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '24px 28px 80px' }}>
        <div style={{ fontSize: 13.5, color: 'var(--ink-3)', marginBottom: 16 }}>
          <button onClick={() => nav('/shop')} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', padding: 0 }}>ร้านค้า</button>
          <span style={{ margin: '0 8px' }}>/</span>
          <span>{p.system}</span>
          <span style={{ margin: '0 8px' }}>/</span>
          <span style={{ color: 'var(--ink-2)' }}>{p.name}</span>
        </div>

        {/* HERO */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 40, marginBottom: 40 }}>
          <Placeholder ratio="4/3" tone={p.tone} style={{ minHeight: 380 }}>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
              {sys && <SystemGlyph system={p.system} size={72} rounded={18} />}
              <div style={{ fontSize: 13, opacity: 0.6 }}>{p.system}</div>
            </div>
          </Placeholder>
          <div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
              <Badge tone="primary">{p.system}</Badge>
              {p.badge && <Badge tone="accent">{p.badge}</Badge>}
              <Badge tone="outline">{p.type}</Badge>
            </div>
            {d.tagline && (
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--accent)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10 }}>
                ✦ {d.tagline}
              </div>
            )}
            <h1 className="display" style={{ margin: 0, fontSize: 32, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.2 }}>{p.name}</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '14px 0' }}>
              <div style={{ display: 'flex', gap: 1, color: 'var(--warn)' }}>
                {[1,2,3,4,5].map(i => <I key={i} name="star" size={14} fill="currentColor" />)}
              </div>
              <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>4.9 ({reviewCount} รีวิว)</span>
              <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>•</span>
              <span style={{ fontSize: 13, color: 'var(--ink-2)' }}>มีผู้ใช้งาน 2,400+ คน</span>
            </div>
            <p style={{ margin: '20px 0', fontSize: 15.5, color: 'var(--ink-2)', lineHeight: 1.7, textWrap: 'pretty' }}>
              {d.subtitle || `${sys?.description} เหมาะสำหรับครูและครีเอเตอร์ไทยทุกระดับ`}
            </p>

            {/* Highlight stats */}
            {d.highlights && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 20 }}>
                {d.highlights.map((h, i) => (
                  <div key={i} style={{ padding: '10px 12px', background: 'var(--bg-2)', borderRadius: 10, textAlign: 'center' }}>
                    <div className="display" style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1.1 }}>{h.value}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 3 }}>{h.label}</div>
                  </div>
                ))}
              </div>
            )}

            <div style={{ padding: '20px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)', marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, flexWrap: 'wrap' }}>
                <span className="display" style={{ fontSize: 40, fontWeight: 600, letterSpacing: '-0.02em' }}>{p.price ? '฿' + p.price.toLocaleString() : 'Coming Soon'}</span>
                {p.sub && <span style={{ fontSize: 16, color: 'var(--ink-3)' }}>{p.sub}</span>}
                {p.oldPrice && <span style={{ fontSize: 16, color: 'var(--ink-3)', textDecoration: 'line-through' }}>฿{p.oldPrice.toLocaleString()}</span>}
                {p.oldPrice && <Badge tone="accent" size="sm">ประหยัด ฿{(p.oldPrice - p.price).toLocaleString()}</Badge>}
              </div>
              {d.urgency && (
                <div style={{ marginTop: 12, padding: '8px 12px', background: 'rgba(217,117,87,0.10)', border: '1px solid rgba(217,117,87,0.25)', borderRadius: 8, fontSize: 13, color: 'var(--accent)', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <I name="sparkle" size={14} />{d.urgency}
                </div>
              )}
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              {p.comingSoon ? (
                <Button variant="secondary" size="lg" full disabled>เปิดเร็วๆ นี้</Button>
              ) : (
                <>
                  <Button variant="primary" size="lg" full iconRight="arrowRight" onClick={() => nav('/checkout?p=' + p.id)}>ซื้อเลย</Button>
                  <Button variant="secondary" size="lg" icon="cart">เพิ่มในตะกร้า</Button>
                </>
              )}
            </div>
            <div style={{ marginTop: 20, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {[
                { icon: 'check', label: 'ใช้งานได้ทันที' },
                { icon: 'shield', label: d.guarantee || 'คืนเงิน 7 วัน' },
                { icon: 'sparkle', label: 'อัปเดตฟรี 1 ปี' },
              ].map(b => (
                <div key={b.label} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-2)' }}>
                  <I name={b.icon} size={12} style={{ color: 'var(--success)' }} />{b.label}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* BENEFITS — outcome-focused */}
        {d.benefits && (
          <Card padding={28} style={{ marginBottom: 24 }}>
            <h3 className="display" style={{ margin: '0 0 4px', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>สิ่งที่คุณจะทำได้หลังเรียน</h3>
            <p style={{ margin: '0 0 20px', fontSize: 14, color: 'var(--ink-3)' }}>ผลลัพธ์ที่จับต้องได้จริง ไม่ใช่ทฤษฎี</p>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {d.benefits.map((b, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: 12, background: 'var(--bg-2)', borderRadius: 10 }}>
                  <div style={{ width: 22, height: 22, borderRadius: 999, background: 'var(--success)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
                    <I name="check" size={12} />
                  </div>
                  <span style={{ fontSize: 14, lineHeight: 1.5, textWrap: 'pretty' }}>{b}</span>
                </div>
              ))}
            </div>
          </Card>
        )}

        <Tabs items={[
          { value: 'details', label: 'สิ่งที่ได้รับ' },
          ...(d.curriculum ? [{ value: 'curriculum', label: 'หลักสูตร' }] : []),
          { value: 'faq', label: 'คำถามที่พบบ่อย' },
          { value: 'reviews', label: `รีวิว (${reviewCount})` },
        ]} value={tab} onChange={setTab} style={{ marginBottom: 20 }} />

        <Card padding={28} style={{ minHeight: 200, marginBottom: 32 }}>
          {tab === 'details' && d.inside && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
              {d.inside.map((item, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 14, padding: 16, background: 'var(--bg-2)', borderRadius: 12 }}>
                  <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--surface)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: sys?.color || 'var(--primary)' }}>
                    <I name={item.icon} size={18} />
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 14.5, fontWeight: 500, marginBottom: 3 }}>{item.title}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>{item.sub}</div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {tab === 'curriculum' && d.curriculum && (
            <div>
              {d.instructor && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 16, background: 'var(--bg-2)', borderRadius: 12, marginBottom: 20 }}>
                  <Avatar name={d.instructor.name} size={52} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 15, fontWeight: 600 }}>สอนโดย {d.instructor.name}</div>
                    <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>{d.instructor.role}</div>
                    <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginTop: 6, lineHeight: 1.5 }}>{d.instructor.bio}</div>
                  </div>
                  <div style={{ textAlign: 'center', padding: '0 16px', borderLeft: '1px solid var(--line)' }}>
                    <div className="display" style={{ fontSize: 22, fontWeight: 600 }}>{d.instructor.students}</div>
                    <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>นักเรียน</div>
                  </div>
                </div>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                {d.curriculum.map(c => (
                  <div key={c.n} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-2)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 600, color: 'var(--ink-2)', flexShrink: 0 }}>
                      {c.n}
                    </div>
                    <div style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{c.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                      <I name="play" size={11} />{c.duration}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === 'faq' && d.faq && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 0, maxWidth: 760 }}>
              {d.faq.map((f, i) => (
                <details key={i} style={{ borderBottom: '1px solid var(--line)', padding: '16px 0' }}>
                  <summary style={{ fontWeight: 500, fontSize: 15, cursor: 'pointer', listStyle: 'none', display: 'flex', alignItems: 'center', gap: 10 }}>
                    <I name="plus" size={14} style={{ color: 'var(--ink-3)' }} />
                    {f.q}
                  </summary>
                  <p style={{ margin: '12px 0 0 24px', fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.65 }}>{f.a}</p>
                </details>
              ))}
            </div>
          )}

          {tab === 'reviews' && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              {TESTIMONIALS.map(t => (
                <div key={t.name} style={{ paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                    <Avatar name={t.name} size={32} />
                    <div>
                      <div style={{ fontSize: 13.5, fontWeight: 500 }}>{t.name} <span style={{ color: 'var(--ink-3)', fontWeight: 400 }}>• {t.role}</span></div>
                      <div style={{ display: 'flex', gap: 1, color: 'var(--warn)' }}>
                        {[1,2,3,4,5].map(i => <I key={i} name="star" size={11} fill="currentColor" />)}
                      </div>
                    </div>
                  </div>
                  <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>"{t.text}"</p>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* Related */}
        {related.length > 0 && (
          <div>
            <h3 className="display" style={{ margin: '0 0 16px', fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>สินค้าที่เกี่ยวข้อง</h3>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
              {related.map(rp => <ProductCard key={rp.id} p={rp} nav={nav} variant="medium" />)}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ----- Checkout -----
const HUB_API_BASE = 'https://api.kindlestartup.com';

function Checkout({ nav, route }) {
  const id = (route.match(/p=([^&]+)/) || [])[1] || 'p_course_bai_ngarn';
  const p = PRODUCTS.find(x => x.id === id) || PRODUCTS[0];
  const [coupon, setCoupon] = useStateP('');
  const [couponApplied, setCouponApplied] = useStateP(false);
  const [method, setMethod] = useStateP('promptpay');
  const [loading, setLoading] = useStateP(false);
  const [error, setError] = useStateP('');

  // Stripe handles VAT + discounts inside Checkout — show product price as "subtotal"
  const subtotal = p.price || 0;

  async function pay() {
    if (!p.stripePriceId) {
      setError('สินค้านี้ยังไม่พร้อมขาย กรุณาติดต่อทีมงาน');
      return;
    }
    setError('');
    setLoading(true);
    try {
      const r = await window.apiFetch('/functions/v1/create-hub-checkout', {
        method: 'POST',
        body: JSON.stringify({
          items: [{ stripe_price_id: p.stripePriceId, quantity: 1 }],
          coupon_code: couponApplied ? coupon : null,
        }),
      });
      const data = await r.json();
      if (!r.ok || !data.url) throw new Error(data.detail || data.error || 'สร้างหน้าชำระเงินไม่สำเร็จ');
      window.location.href = data.url;
    } catch (e) {
      setError(e.message);
      setLoading(false);
    }
  }

  return (
    <div>
      <UserTopBar nav={nav} />
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: '32px 28px 80px' }}>
        <h1 className="display" style={{ margin: '0 0 28px', fontSize: 32, fontWeight: 600, letterSpacing: '-0.02em' }}>ชำระเงิน</h1>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 28 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* Customer */}
            <Card>
              <h3 className="display" style={{ margin: '0 0 14px', fontSize: 17, fontWeight: 600 }}>ข้อมูลผู้ซื้อ</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Input label="ชื่อ-สกุล" defaultValue={USER.fullName} />
                <Input label="อีเมล" defaultValue={USER.email} icon="mail" />
              </div>
              <div style={{ marginTop: 12, display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-3)' }}>
                <I name="check" size={13} style={{ color: 'var(--success)' }} /> ใช้ข้อมูลจากบัญชีของคุณแล้ว
              </div>
            </Card>

            {/* Payment */}
            <Card>
              <h3 className="display" style={{ margin: '0 0 14px', fontSize: 17, fontWeight: 600 }}>วิธีชำระเงิน</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[
                  { v: 'promptpay', label: 'PromptPay', sub: 'สแกน QR Code ผ่านแอปธนาคาร', icon: 'qr', recommended: true },
                  { v: 'card', label: 'บัตรเครดิต/เดบิต', sub: 'Visa, Mastercard, JCB ผ่าน Stripe', icon: 'card' },
                ].map(m => (
                  <button key={m.v} onClick={() => setMethod(m.v)} style={{
                    display: 'flex', alignItems: 'center', gap: 14,
                    padding: 14, borderRadius: 12,
                    border: '1px solid ' + (method === m.v ? 'var(--ink)' : 'var(--line-2)'),
                    background: method === m.v ? 'var(--bg-2)' : 'var(--surface)',
                    cursor: 'pointer', textAlign: 'left',
                  }}>
                    <div style={{ width: 40, height: 40, borderRadius: 10, background: 'var(--bg-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink)' }}>
                      <I name={m.icon} size={18} />
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span style={{ fontSize: 14.5, fontWeight: 500 }}>{m.label}</span>
                        {m.recommended && <Badge tone="success" size="sm">แนะนำ</Badge>}
                      </div>
                      <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{m.sub}</div>
                    </div>
                    <div style={{
                      width: 18, height: 18, borderRadius: 999,
                      border: '2px solid ' + (method === m.v ? 'var(--ink)' : 'var(--line-2)'),
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      {method === m.v && <div style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--ink)' }} />}
                    </div>
                  </button>
                ))}
              </div>

              {method === 'promptpay' && (
                <div style={{ marginTop: 16, padding: 20, background: 'var(--bg-2)', borderRadius: 12, display: 'flex', alignItems: 'center', gap: 20 }}>
                  <div style={{ width: 110, height: 110, background: '#fff', borderRadius: 8, padding: 8, border: '1px solid var(--line)' }}>
                    <FakeQR />
                  </div>
                  <div>
                    <div style={{ fontSize: 13.5, color: 'var(--ink-2)', marginBottom: 4 }}>สแกน QR เพื่อชำระเงิน</div>
                    <div className="display" style={{ fontSize: 22, fontWeight: 600 }}>฿{total.toLocaleString()}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>QR หมดอายุใน 14:59</div>
                  </div>
                </div>
              )}
            </Card>
          </div>

          {/* Summary */}
          <div>
            <Card style={{ position: 'sticky', top: 88 }}>
              <h3 className="display" style={{ margin: '0 0 16px', fontSize: 17, fontWeight: 600 }}>สรุปคำสั่งซื้อ</h3>
              <div style={{ display: 'flex', gap: 12, marginBottom: 16, paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
                <Placeholder ratio="1/1" tone={p.tone} style={{ width: 64, height: 64, flexShrink: 0 }}>
                  <SystemGlyph system={p.system} size={28} rounded={8} />
                </Placeholder>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 500, lineHeight: 1.4, marginBottom: 4 }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{p.system}</div>
                </div>
                <div style={{ fontSize: 14, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{p.price ? '฿' + p.price.toLocaleString() : 'Coming Soon'}</div>
              </div>

              <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
                <Input full placeholder="รหัสส่วนลด" value={coupon} onChange={e => setCoupon(e.target.value)} style={{ flex: 1 }} />
                <Button variant="secondary" onClick={() => coupon.trim() && setCouponApplied(true)}>ใช้</Button>
              </div>
              {couponApplied && <div style={{ fontSize: 12.5, color: 'var(--success)', marginBottom: 12, marginTop: -8 }}>✓ ใช้รหัส "{coupon}" แล้ว — ลด 10%</div>}

              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
                <Row k="ราคา" v={`฿${subtotal.toLocaleString()}`} />
                <Row k="ภาษีและส่วนลด" v="คำนวณในหน้าชำระเงิน" />
              </div>
              <div style={{ paddingTop: 16, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 20 }}>
                <span style={{ fontSize: 14, fontWeight: 500 }}>เริ่มต้น</span>
                <span className="display" style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em' }}>฿{subtotal.toLocaleString()}</span>
              </div>
              {error && (
                <div style={{ marginBottom: 12, padding: '10px 12px', background: 'var(--danger-soft)', color: 'var(--danger)', borderRadius: 8, fontSize: 13 }}>
                  ⚠️ {error}
                </div>
              )}
              <Button variant="accent" size="lg" full iconRight="arrowRight" onClick={pay} disabled={loading}>
                {loading ? 'กำลังเปิดหน้าชำระเงิน…' : `ดำเนินการชำระเงิน — ฿${subtotal.toLocaleString()}`}
              </Button>
              <div style={{ marginTop: 16, fontSize: 12, color: 'var(--ink-3)', textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
                <I name="shield" size={12} /> ชำระเงินปลอดภัยผ่าน Stripe
              </div>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}

function Row({ k, v, accent }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5 }}>
      <span style={{ color: 'var(--ink-2)' }}>{k}</span>
      <span style={{ color: accent ? 'var(--success)' : 'var(--ink)', fontVariantNumeric: 'tabular-nums', fontWeight: accent ? 500 : 400 }}>{v}</span>
    </div>
  );
}

function FakeQR() {
  // generate a fake QR pattern
  const cells = useMemoP(() => {
    const arr = [];
    for (let i = 0; i < 21*21; i++) {
      arr.push(Math.random() > 0.55 ? 1 : 0);
    }
    // corner finder patterns
    const setBlock = (cx, cy) => {
      for (let y = 0; y < 7; y++) for (let x = 0; x < 7; x++) {
        const inner = (x === 0 || x === 6 || y === 0 || y === 6) || (x >= 2 && x <= 4 && y >= 2 && y <= 4);
        arr[(cy + y) * 21 + (cx + x)] = inner ? 1 : 0;
      }
    };
    setBlock(0, 0); setBlock(14, 0); setBlock(0, 14);
    return arr;
  }, []);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(21, 1fr)', gap: 0, width: '100%', height: '100%' }}>
      {cells.map((c, i) => <div key={i} style={{ background: c ? '#000' : '#fff' }} />)}
    </div>
  );
}

// ----- Checkout Success -----
function CheckoutSuccess({ nav }) {
  return (
    <div>
      <UserTopBar nav={nav} />
      <div style={{ maxWidth: 600, margin: '0 auto', padding: '80px 28px', textAlign: 'center' }}>
        <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--success-soft)', color: 'var(--success)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 24 }}>
          <I name="check" size={32} stroke={2.5} />
        </div>
        <h1 className="display" style={{ margin: 0, fontSize: 36, fontWeight: 600, letterSpacing: '-0.02em' }}>ขอบคุณค่ะ! 🎉</h1>
        <p style={{ margin: '12px 0 32px', fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.6 }}>
          คำสั่งซื้อของคุณสำเร็จเรียบร้อย ระบบได้ส่งใบเสร็จและรายละเอียดเข้าอีเมล <strong>{USER.email}</strong> แล้ว
        </p>
        <Card padding={20} style={{ textAlign: 'left', marginBottom: 24 }}>
          <Row k="หมายเลขคำสั่งซื้อ" v="KS-2026-1109" />
          <div style={{ height: 8 }} />
          <Row k="วันที่" v="5 พ.ค. 2026 10:42" />
          <div style={{ height: 8 }} />
          <Row k="วิธีชำระ" v="PromptPay" />
        </Card>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
          <Button variant="primary" size="lg" iconRight="arrowRight" onClick={() => nav('/dashboard')}>ไปที่แดชบอร์ด</Button>
          <Button variant="secondary" size="lg" icon="receipt">ดูใบเสร็จ</Button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  PublicTopBar, Landing, Login, Shop, ProductCard, ProductDetail, Checkout, CheckoutSuccess,
});
