// User-facing screens: Dashboard, MyProducts, MyOrders, Account
const { useState, useEffect, useMemo } = React;

// ----- Top bar (user-facing) -----
function UserTopBar({ nav }) {
  const [open, setOpen] = useState(null);
  const unreadCount = NOTIFICATIONS.filter(n => n.unread).length;
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: 'rgba(250,247,242,0.85)',
      backdropFilter: 'blur(12px) saturate(140%)',
      WebkitBackdropFilter: 'blur(12px) saturate(140%)',
      borderBottom: '1px solid var(--line)',
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 28px', height: 64, display: 'flex', alignItems: 'center', gap: 24 }}>
        <button onClick={() => nav('/dashboard')} style={{ background: 'transparent', border: 'none', padding: 0, cursor: 'pointer' }}>
          <Logo size={20} />
        </button>
        <nav style={{ display: 'flex', gap: 4, marginLeft: 8 }}>
          {[
            { label: 'แดชบอร์ด', path: '/dashboard' },
            { label: 'ร้านค้า', path: '/shop' },
          ].map(it => {
            const active = window.__route?.startsWith(it.path);
            return (
              <button key={it.path} onClick={() => nav(it.path)} style={{
                background: active ? 'var(--bg-2)' : 'transparent',
                border: 'none', padding: '8px 14px', borderRadius: 999,
                cursor: 'pointer', fontSize: 14,
                color: active ? 'var(--ink)' : 'var(--ink-2)',
                fontWeight: active ? 500 : 400,
              }}>{it.label}</button>
            );
          })}
        </nav>
        <div style={{ flex: 1 }} />
        <div style={{ position: 'relative' }}>
          <button onClick={() => setOpen(open === 'notif' ? null : 'notif')} style={{ background: open === 'notif' ? 'var(--bg-2)' : 'transparent', border: 'none', padding: 8, borderRadius: 999, cursor: 'pointer', color: 'var(--ink-2)', position: 'relative' }}>
            <I name="bell" size={20} />
            {unreadCount > 0 && <span style={{ position: 'absolute', top: 4, right: 4, minWidth: 16, height: 16, padding: '0 4px', background: 'var(--accent)', borderRadius: 999, fontSize: 10, fontWeight: 600, color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1 }}>{unreadCount}</span>}
          </button>
          {open === 'notif' && (
            <>
              <div onClick={() => setOpen(null)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
              <div style={{ position: 'absolute', right: 0, top: '110%', width: 360, zIndex: 50, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', boxShadow: 'var(--sh-pop)', overflow: 'hidden' }}>
                <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>การแจ้งเตือน</div>
                  <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 12 }}>อ่านทั้งหมด</button>
                </div>
                <div style={{ maxHeight: 420, overflowY: 'auto' }}>
                  {NOTIFICATIONS.map(n => (
                    <div key={n.id} style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)', display: 'flex', gap: 10, background: n.unread ? 'rgba(217,117,87,0.04)' : 'transparent' }}>
                      <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: n.tone === 'accent' ? 'var(--accent)' : n.tone === 'success' ? 'var(--success)' : n.tone === 'primary' ? 'var(--primary)' : 'var(--ink-2)' }}>
                        <I name={n.icon} size={15} />
                      </div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <div style={{ fontSize: 13.5, fontWeight: n.unread ? 600 : 500, lineHeight: 1.3 }}>{n.title}</div>
                          {n.unread && <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent)', flexShrink: 0 }} />}
                        </div>
                        <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 2, lineHeight: 1.4 }}>{n.body}</div>
                        <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>{n.time}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </>
          )}
        </div>
        <button onClick={() => nav('/admin')} title="Admin Panel" style={{ background: 'var(--bg-2)', border: 'none', padding: '6px 12px', borderRadius: 999, cursor: 'pointer', color: 'var(--ink-2)', fontSize: 12.5, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <I name="shield" size={13} /> Admin
        </button>
        <div style={{ position: 'relative' }}>
          <button onClick={() => setOpen(open === 'user' ? null : 'user')} style={{
            background: 'transparent', border: 'none', padding: 4, borderRadius: 999,
            cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <Avatar name={USER.fullName} size={32} />
            <span style={{ fontSize: 14, fontWeight: 500 }}>{USER.name}</span>
            <I name="chevronDown" size={14} style={{ color: 'var(--ink-3)' }} />
          </button>
          {open === 'user' && (
            <>
              <div onClick={() => setOpen(null)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
              <div style={{
                position: 'absolute', right: 0, top: '110%', minWidth: 220, zIndex: 50,
                background: 'var(--surface)', border: '1px solid var(--line)',
                borderRadius: 'var(--r-md)', boxShadow: 'var(--sh-pop)',
                padding: 6,
              }}>
                <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--line)' }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{USER.fullName}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{USER.email}</div>
                </div>
                {[
                  { label: 'แดชบอร์ด', icon: 'home', path: '/dashboard' },
                  { label: 'บัญชีของฉัน', icon: 'package', path: '/my-products' },
                ].map(it => (
                  <button key={it.path} onClick={() => { nav(it.path); setOpen(null); }} style={{
                    display: 'flex', width: '100%', alignItems: 'center', gap: 10,
                    background: 'transparent', border: 'none', padding: '8px 12px',
                    borderRadius: 8, cursor: 'pointer', fontSize: 13.5, color: 'var(--ink)',
                    textAlign: 'left',
                  }}>
                    <I name={it.icon} size={15} style={{ color: 'var(--ink-3)' }} />
                    {it.label}
                  </button>
                ))}
                <div style={{ height: 1, background: 'var(--line)', margin: '4px 0' }} />
                <button onClick={() => { nav('/'); setOpen(null); }} style={{
                  display: 'flex', width: '100%', alignItems: 'center', gap: 10,
                  background: 'transparent', border: 'none', padding: '8px 12px',
                  borderRadius: 8, cursor: 'pointer', fontSize: 13.5, color: 'var(--ink-2)',
                  textAlign: 'left',
                }}>
                  <I name="logout" size={15} style={{ color: 'var(--ink-3)' }} />
                  ออกจากระบบ
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ----- Dashboard ⭐ (the heart of the system) -----
function Dashboard({ nav }) {
  const { data: userData } = window.useUserData();

  const liveOwned = React.useMemo(() => {
    if (!userData) return null;
    const list = [];
    (userData.courses || []).forEach(c => list.push({
      system: 'Academy', productId: 'p_course_bai_ngarn',
      plan: c.title, status: 'active',
      meta: 'จ่ายแล้ว ฿' + (c.amount_paid || 0).toLocaleString(),
      license: 'ENROLL-' + (c.enrollment_id || '').slice(0, 8).toUpperCase(),
      purchasedAt: c.enrolled_at,
      externalUrl: 'https://kindlestartup.com/courses/' + (c.slug || ''),
    }));
    (userData.products || []).forEach(p => {
      const isEbook = (p.slug || '').includes('keyword') || /keyword/i.test(p.title || '');
      list.push({
        system: 'Academy',
        productId: isEbook ? 'p_keyword_ebook' : 'p_course_bai_ngarn',
        plan: p.title, status: 'active',
        meta: 'จ่ายแล้ว ฿' + (p.amount_paid || 0).toLocaleString(),
        license: 'PROD-' + (p.purchase_id || '').slice(0, 8).toUpperCase(),
        purchasedAt: p.purchased_at,
        externalUrl: isEbook ? 'https://kindlestartup.com/keyword-ebook' : 'https://kindlestartup.com',
      });
    });
    const s = userData.seo_subscription;
    if (s && s.status === 'active') {
      list.push({
        system: 'SEO', productId: 'p_tpt_seo_pro_max_monthly',
        plan: 'TPT SEO ' + (s.plan || ''), status: 'active',
        meta: `${s.monthly_remaining}/${s.monthly_limit} เครดิตคงเหลือเดือนนี้`,
        renewal: s.next_billing_date ? 'ต่ออายุ ' + new Date(s.next_billing_date).toLocaleDateString('th-TH') : null,
        credit: { used: s.monthly_used, total: s.monthly_limit, resetAt: s.credit_reset_date },
        externalUrl: 'https://tptkeywords.com',
      });
    }
    return list;
  }, [userData]);

  // Shadow window.OWNED + window.USER inside this component when logged in
  const OWNED = liveOwned || window.OWNED;
  const USER = userData?.user
    ? { ...window.USER, name: userData.user.full_name, fullName: userData.user.full_name, email: userData.user.email }
    : window.USER;

  const ownedKeys = OWNED.map(o => o.system);
  const total = SYSTEMS.length;
  const activeCount = OWNED.filter(o => o.status === 'active').length;
  const today = new Date().toLocaleDateString('th-TH', { weekday: 'long', day: 'numeric', month: 'long' });

  return (
    <div style={{ maxWidth: 1280, margin: '0 auto', padding: '32px 28px 80px' }}>
      {/* Welcome strip */}
      <div className="fade-up" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, marginBottom: 28, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', textTransform: 'capitalize', marginBottom: 6 }}>
            วันนี้ • {today}
          </div>
          <h1 className="display" style={{ margin: 0, fontSize: 38, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.15 }}>
            สวัสดี, {USER.name} 👋
          </h1>
          <p style={{ margin: '8px 0 0', fontSize: 15.5, color: 'var(--ink-2)', maxWidth: 540 }}>
            คุณมี <strong style={{ color: 'var(--ink)' }}>{activeCount} ระบบ</strong> ที่ใช้งานได้ และมี <strong style={{ color: 'var(--ink)' }}>1 คอร์ส</strong> กำลังเรียน — เลือกอะไรเริ่มต่อได้เลย
          </p>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="secondary" icon="help" onClick={() => alert('ศูนย์ช่วยเหลือ')}>ช่วยเหลือ</Button>
          <Button variant="primary" icon="shop" onClick={() => nav('/shop')}>ดูร้านค้า</Button>
        </div>
      </div>

      {/* My Systems — owned only */}
      {(() => {
        const owned = SYSTEMS.filter(sys => {
          const o = OWNED.find(x => x.system === sys.key);
          return o && o.status === 'active';
        });
        const notOwned = SYSTEMS.filter(sys => {
          const o = OWNED.find(x => x.system === sys.key);
          return !o || o.status !== 'active';
        });
        return (
          <>
            <SectionHeading
              eyebrow="ระบบของฉัน"
              title="คลิกเพื่อเข้าใช้งานระบบ"
              action={<button onClick={() => nav('/my-products')} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-2)', fontSize: 14, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 4 }}>จัดการระบบทั้งหมด <I name="arrowRight" size={14} /></button>}
            />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16, marginBottom: 40 }}>
              {owned.map(sys => {
                const o = OWNED.find(x => x.system === sys.key);
                return <SystemCard key={sys.key} sys={sys} owned={o} nav={nav} />;
              })}
            </div>

            {/* Upsell — wide banner */}
            <UpsellBanner nav={nav} />

            {/* Not owned — preview cards */}
            {notOwned.length > 0 && (
              <>
                <SectionHeading
                  eyebrow="ระบบที่ยังไม่มี"
                  title='ดูรายละเอียดได้ในเมนู "ร้านค้า"'
                  style={{ marginTop: 40 }}
                  action={<button onClick={() => nav('/shop')} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-2)', fontSize: 14, fontWeight: 500, display: 'inline-flex', alignItems: 'center', gap: 4 }}>ไปที่ร้านค้า <I name="arrowRight" size={14} /></button>}
                />
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 16 }}>
                  {notOwned.map(sys => {
                    const o = OWNED.find(x => x.system === sys.key);
                    return <SystemCard key={sys.key} sys={sys} owned={o} nav={nav} />;
                  })}
                </div>
              </>
            )}
          </>
        );
      })()}
    </div>
  );
}

// Wide banner upsell
function UpsellBanner({ nav }) {
  return (
    <Card
      padding={0}
      hover
      onClick={() => nav('/shop/p9')}
      style={{
        background: 'linear-gradient(110deg, #2A2520 0%, #3E3225 55%, #5C4530 100%)',
        color: '#F5EFE2', border: 'none', overflow: 'hidden', position: 'relative', cursor: 'pointer',
        marginBottom: 8,
      }}
    >
      {/* decorative circles */}
      <div style={{ position: 'absolute', right: -60, top: -60, width: 220, height: 220, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,200,140,0.20), transparent 70%)' }} />
      <div style={{ position: 'absolute', right: 160, bottom: -80, width: 180, height: 180, borderRadius: '50%', background: 'radial-gradient(circle, rgba(255,180,120,0.15), transparent 70%)' }} />

      <div style={{ display: 'flex', alignItems: 'center', gap: 24, padding: '22px 28px', position: 'relative' }}>
        {/* glyph stack */}
        <div style={{ display: 'flex', flexShrink: 0 }}>
          {['Academy', 'SEO', 'Lumo', 'Muze'].map((s, i) => (
            <div key={s} style={{ marginLeft: i === 0 ? 0 : -12, boxShadow: '0 2px 8px rgba(0,0,0,0.3)', borderRadius: 12 }}>
              <SystemGlyph system={s} size={48} rounded={12} />
            </div>
          ))}
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <Badge tone="dark" style={{ background: 'rgba(255,217,163,0.18)', color: '#FFD9A3', border: '1px solid rgba(255,217,163,0.30)' }}>คุ้มกว่า 33%</Badge>
            <span style={{ fontSize: 12, color: 'rgba(245,239,226,0.65)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>ข้อเสนอพิเศษ</span>
          </div>
          <h4 className="display" style={{ margin: 0, fontSize: 22, fontWeight: 600, lineHeight: 1.25, letterSpacing: '-0.01em' }}>
            อัปเป็น All-Access Bundle ใช้ได้ทุกระบบ 1 ปีเต็ม
          </h4>
          <p style={{ margin: '6px 0 0', fontSize: 13.5, color: 'rgba(245,239,226,0.75)' }}>
            ครอบคลุม Academy + SEO + Lumo + Muze (เมื่อเปิดตัว) — ประหยัดกว่าซื้อแยก ฿8,400
          </p>
        </div>

        {/* price + cta */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 20, flexShrink: 0 }}>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 12, color: 'rgba(245,239,226,0.55)', textDecoration: 'line-through' }}>฿25,200</div>
            <div className="display" style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1 }}>฿16,800</div>
          </div>
          <Button variant="accent" size="md" iconRight="arrowRight" onClick={(e) => { e.stopPropagation(); nav('/shop/p9'); }}>
            ดูข้อเสนอ
          </Button>
        </div>
      </div>
    </Card>
  );
}

function StatCard({ label, value, hint, icon, trend }) {
  return (
    <Card padding={18}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 12 }}>
        <div style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--bg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-2)' }}>
          <I name={icon} size={16} />
        </div>
        {trend && <I name={trend === 'up' ? 'trendUp' : 'trendDown'} size={14} style={{ color: trend === 'up' ? 'var(--success)' : 'var(--danger)' }} />}
      </div>
      <div className="display" style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.1 }}>{value}</div>
      <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>{label}</div>
      {hint && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>{hint}</div>}
    </Card>
  );
}

// System-specific content: shows actual state of usage + main quick action
const SYSTEM_DETAILS = {
  Academy: {
    primaryAction: { label: 'เรียนต่อบทที่ 4', icon: 'play' },
    recent: { label: 'เรียนล่าสุด', value: 'Kindle Mastery — บทที่ 4', sub: 'เลือก niche ที่ขายได้ • 18 นาทีจบบท' },
    stats: [
      { label: 'คอร์ส', value: '3' },
      { label: 'ความคืบหน้า', value: '62%' },
      { label: 'ใบประกาศ', value: '1' },
    ],
    secondary: 'ดูคอร์สทั้งหมด',
  },
  SEO: {
    primaryAction: { label: 'ค้นหา keyword ใหม่', icon: 'search2' },
    recent: { label: 'คำค้นล่าสุด', value: '"reading comprehension grade 3"', sub: 'ค้นหา 14,800/เดือน • คู่แข่งระดับกลาง' },
    stats: [
      { label: 'โควต้าวันนี้', value: '12 / 50' },
      { label: 'รายการบันทึก', value: '24' },
      { label: 'รายงาน', value: '3' },
    ],
    secondary: 'ดูคำที่บันทึกไว้',
  },
  Lumo: {
    primaryAction: { label: 'สร้างใบงานใหม่', icon: 'plus' },
    recent: { label: 'ใบงานล่าสุด', value: 'แบบฝึกบวกลบ ป.2 — ชุดที่ 4', sub: 'สร้างเมื่อวานนี้ • ดาวน์โหลดแล้ว 2 ครั้ง' },
    stats: [
      { label: 'เดือนนี้', value: '28' },
      { label: 'รวมทั้งหมด', value: '142' },
      { label: 'แบบที่ใช้บ่อย', value: '5' },
    ],
    secondary: 'ดูใบงานทั้งหมด',
  },
  Muze: {
    primaryAction: { label: 'จองล่วงหน้า', icon: 'arrowRight' },
    recent: { label: 'เปิดตัว', value: 'พ.ค. 2026', sub: 'จองตอนนี้ลด 35% • รับสิทธิ์ก่อนใคร' },
    stats: [
      { label: 'จองแล้ว', value: '847' },
      { label: 'ส่วนลด', value: '-35%' },
      { label: 'เปิดตัวใน', value: '21 วัน' },
    ],
    secondary: 'ดูตัวอย่าง',
  },
};

function SystemCard({ sys, owned, nav }) {
  const isOwned = !!owned && owned.status === 'active';
  const isPreorder = sys.status === 'pre-order';
  const d = SYSTEM_DETAILS[sys.key];

  return (
    <Card padding={0} hover style={{ overflow: 'hidden' }}>
      <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 16, height: '100%' }}>
        {/* Header: glyph + name + status */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <SystemGlyph system={sys.key} size={48} rounded={12} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
              <h4 className="display" style={{ margin: 0, fontSize: 19, fontWeight: 600, letterSpacing: '-0.01em' }}>{sys.name}</h4>
              {isOwned && <Badge tone="success" size="sm">Active</Badge>}
              {isPreorder && <Badge tone="accent" size="sm">เร็วๆ นี้</Badge>}
              {!isOwned && !isPreorder && <Badge tone="outline" size="sm">ยังไม่ได้ซื้อ</Badge>}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{sys.tagline}</div>
          </div>
          {isOwned && owned.renewal && (
            <div style={{ textAlign: 'right', fontSize: 11.5, color: 'var(--ink-3)' }}>
              <div>ต่ออายุ</div>
              <div style={{ color: 'var(--ink-2)', fontWeight: 500 }}>{owned.renewal.replace('2026', '')}</div>
            </div>
          )}
        </div>

        {/* Recent activity / hero info */}
        {(isOwned || isPreorder) && d && (
          <div style={{
            padding: '12px 14px',
            background: 'var(--bg-2)',
            borderRadius: 12,
            borderLeft: `3px solid ${sys.color}`,
          }}>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>
              {d.recent.label}
            </div>
            <div style={{ fontSize: 14, fontWeight: 500, marginBottom: 2, textWrap: 'pretty' }}>{d.recent.value}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{d.recent.sub}</div>
          </div>
        )}

        {/* Usage stats */}
        {(isOwned || isPreorder) && d && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0, padding: '4px 0' }}>
            {d.stats.map((s, i) => (
              <div key={s.label} style={{
                paddingLeft: i === 0 ? 0 : 14,
                borderLeft: i === 0 ? 'none' : '1px solid var(--line)',
              }}>
                <div className="display" style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em', fontVariantNumeric: 'tabular-nums' }}>{s.value}</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{s.label}</div>
              </div>
            ))}
          </div>
        )}

        {/* Not owned: show description + value props */}
        {!isOwned && !isPreorder && (
          <>
            <p style={{ margin: 0, fontSize: 13.5, color: 'var(--ink-2)', lineHeight: 1.6, textWrap: 'pretty' }}>
              {sys.description}
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {['ใช้งานได้ทันทีหลังซื้อ', 'อัปเดตเนื้อหาตลอด 1 ปี', 'รับประกันคืนเงิน 7 วัน'].map(b => (
                <div key={b} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5, color: 'var(--ink-2)' }}>
                  <I name="check" size={12} style={{ color: 'var(--success)' }} />{b}
                </div>
              ))}
            </div>
          </>
        )}

        {/* Actions */}
        <div style={{ marginTop: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
          {isOwned && d ? (
            <>
              <Button
                variant="primary" full
                icon={d.primaryAction.icon}
                onClick={() => alert(`${sys.name}: ${d.primaryAction.label}`)}
              >
                {d.primaryAction.label}
              </Button>
              <button
                onClick={() => alert(`เปิด ${sys.name}`)}
                title={`เปิด ${sys.name} ในแท็บใหม่`}
                style={{
                  width: 40, height: 40, borderRadius: 999,
                  border: '1px solid var(--line-2)', background: 'var(--surface)',
                  cursor: 'pointer', flexShrink: 0,
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--ink-2)',
                }}
              >
                <I name="external" size={15} />
              </button>
            </>
          ) : isPreorder ? (
            <Button variant="accent" iconRight="arrowRight" full onClick={() => nav('/shop/p8')}>
              จองล่วงหน้า — ลด 35%
            </Button>
          ) : (
            <>
              <Button variant="secondary" full onClick={() => nav('/shop?cat=' + sys.key)}>ดูรายละเอียด</Button>
              <Button variant="primary" full onClick={() => nav('/shop?cat=' + sys.key)}>ซื้อเลย</Button>
            </>
          )}
        </div>
      </div>
    </Card>
  );
}

function CourseRow({ c }) {
  const pct = Math.round(c.progress * 100);
  return (
    <Card padding={16} hover onClick={() => alert('เปิดคอร์ส: ' + c.title)}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <Placeholder ratio="4/3" tone={c.tone} style={{ width: 88, height: 64, flexShrink: 0 }}>
          <I name="play" size={20} />
        </Placeholder>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 2 }}>{c.title}</div>
          <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 8 }}>{c.module}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ flex: 1, height: 5, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: pct + '%', height: '100%', background: 'var(--ink)', borderRadius: 999, transition: 'width .6s ease' }} />
            </div>
            <span style={{ fontSize: 12, color: 'var(--ink-2)', fontVariantNumeric: 'tabular-nums', minWidth: 36, textAlign: 'right' }}>{pct}%</span>
          </div>
        </div>
        <Button variant="secondary" size="sm" iconRight="arrowRight">เรียนต่อ</Button>
      </div>
    </Card>
  );
}

// ----- My Products -----
function MyProducts({ nav }) {
  const { data: userData } = window.useUserData();
  const liveOwned = React.useMemo(() => {
    if (!userData) return null;
    const list = [];
    (userData.courses || []).forEach(c => list.push({
      system: 'Academy', plan: c.title, status: 'active',
      meta: 'จ่ายแล้ว ฿' + (c.amount_paid || 0).toLocaleString() + ' • ' + (c.payment_status || 'paid'),
      license: 'ENROLL-' + (c.enrollment_id || '').slice(0, 8).toUpperCase(),
      purchasedAt: c.enrolled_at,
      externalUrl: 'https://kindlestartup.com/courses/' + (c.slug || ''),
    }));
    (userData.products || []).forEach(p => {
      const isEbook = (p.slug || '').includes('keyword') || /keyword/i.test(p.title || '');
      list.push({
        system: 'Academy', plan: p.title, status: 'active',
        meta: 'จ่ายแล้ว ฿' + (p.amount_paid || 0).toLocaleString(),
        license: 'PROD-' + (p.purchase_id || '').slice(0, 8).toUpperCase(),
        purchasedAt: p.purchased_at,
        externalUrl: isEbook ? 'https://kindlestartup.com/keyword-ebook' : 'https://kindlestartup.com',
      });
    });
    const s = userData.seo_subscription;
    if (s && s.status === 'active') {
      list.push({
        system: 'SEO', plan: 'TPT SEO ' + (s.plan || ''), status: 'active',
        meta: `${s.monthly_remaining}/${s.monthly_limit} เครดิตคงเหลือเดือนนี้`,
        renewal: s.next_billing_date ? 'ต่ออายุ ' + new Date(s.next_billing_date).toLocaleDateString('th-TH') : null,
        license: 'SEO-' + (s.plan || '').toUpperCase().slice(0, 8),
        externalUrl: 'https://tptkeywords.com',
      });
    }
    return list;
  }, [userData]);
  const OWNED = liveOwned || window.OWNED;

  return (
    <SidebarLayout active="/my-products" nav={nav} title="บัญชีของฉัน" subtitle="ระบบและคอร์สที่คุณเป็นเจ้าของ">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {OWNED.map(o => {
          const sys = SYSTEMS.find(s => s.key === o.system);
          return (
            <Card key={o.system} padding={20}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <SystemGlyph system={o.system} size={48} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <h4 className="display" style={{ margin: 0, fontSize: 17, fontWeight: 600 }}>{sys.name}</h4>
                    <Badge tone="success" size="sm">Active</Badge>
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>{o.plan} • {o.meta}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  {o.renewal && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 6 }}>ต่ออายุ {o.renewal}</div>}
                  <Button variant="primary" size="sm" iconRight="external" onClick={() => alert('เปิด ' + sys.name)}>เปิดใช้งาน</Button>
                </div>
              </div>
              {o.license && (
                <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 12, fontSize: 13, flexWrap: 'wrap' }}>
                  <I name="lock" size={14} style={{ color: 'var(--ink-3)' }} />
                  <span style={{ color: 'var(--ink-2)' }}>License key:</span>
                  <code className="mono" style={{ background: 'var(--bg-2)', padding: '3px 8px', borderRadius: 6, fontSize: 12 }}>{o.license}</code>
                  <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12 }}>
                    <I name="copy" size={12} /> คัดลอก
                  </button>
                  {o.purchased && <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)' }}>ซื้อเมื่อ {o.purchased}</span>}
                </div>
              )}
            </Card>
          );
        })}
        {SYSTEMS.filter(s => !OWNED.find(o => o.system === s.key)).map(sys => (
          <Card key={sys.key} padding={20} style={{ background: 'var(--bg-2)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, opacity: 0.85 }}>
              <SystemGlyph system={sys.key} size={48} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <h4 className="display" style={{ margin: 0, fontSize: 17, fontWeight: 600 }}>{sys.name}</h4>
                  <Badge tone={sys.status === 'pre-order' ? 'accent' : 'outline'} size="sm">{sys.status === 'pre-order' ? 'เร็วๆ นี้' : 'ยังไม่ได้ซื้อ'}</Badge>
                </div>
                <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>{sys.tagline}</div>
              </div>
              <Button variant="secondary" size="sm" onClick={() => nav('/shop')}>ดูรายละเอียด</Button>
            </div>
          </Card>
        ))}
      </div>
    </SidebarLayout>
  );
}

// ----- My Orders -----
function MyOrders({ nav }) {
  const { data: userData } = window.useUserData();
  const liveOrders = React.useMemo(() => {
    if (!userData?.orders?.length) return null;
    return userData.orders.map(o => ({
      id: o.id,
      date: o.date ? new Date(o.date).toLocaleDateString('th-TH', { day: 'numeric', month: 'short', year: 'numeric' }) : '-',
      items: o.items || [],
      amount: o.amount || 0,
      status: o.status || 'paid',
      method: o.method || 'Stripe',
    }));
  }, [userData]);
  const ORDERS = liveOrders || window.ORDERS;

  return (
    <SidebarLayout active="/my-orders" nav={nav} title="คำสั่งซื้อ" subtitle="ประวัติการซื้อทั้งหมดของคุณ">
      <Card padding={0} style={{ overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
          <thead>
            <tr style={{ background: 'var(--bg-2)', textAlign: 'left' }}>
              {['Order ID', 'วันที่', 'รายการ', 'จำนวน', 'สถานะ', ''].map(h => (
                <th key={h} style={{ padding: '12px 16px', fontSize: 12.5, fontWeight: 500, color: 'var(--ink-2)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {ORDERS.map((o, i) => (
              <tr key={o.id} style={{ borderTop: '1px solid var(--line)' }}>
                <td style={{ padding: '14px 16px' }}>
                  <span className="mono" style={{ fontSize: 13, color: 'var(--ink-2)' }}>{o.id}</span>
                </td>
                <td style={{ padding: '14px 16px', color: 'var(--ink-2)' }}>{o.date}</td>
                <td style={{ padding: '14px 16px' }}>{o.items.join(', ')}</td>
                <td style={{ padding: '14px 16px', fontVariantNumeric: 'tabular-nums', fontWeight: 500 }}>฿{o.amount.toLocaleString()}</td>
                <td style={{ padding: '14px 16px' }}>
                  <Badge tone={o.status === 'paid' ? 'success' : o.status === 'refunded' ? 'warn' : 'neutral'} size="sm">
                    {o.status === 'paid' ? 'ชำระแล้ว' : o.status === 'refunded' ? 'คืนเงินแล้ว' : o.status}
                  </Badge>
                </td>
                <td style={{ padding: '14px 16px', textAlign: 'right' }}>
                  <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: 'var(--ink-2)', fontSize: 13, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                    <I name="download" size={13} /> ใบเสร็จ
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </SidebarLayout>
  );
}

// ----- Account -----
function Account({ nav }) {
  const { data: userData } = window.useUserData();
  const [name, setName] = useState(userData?.user?.full_name || USER.fullName);
  const [email, setEmail] = useState(userData?.user?.email || USER.email);
  React.useEffect(() => {
    if (userData?.user) {
      setName(userData.user.full_name || '');
      setEmail(userData.user.email || '');
    }
  }, [userData]);
  return (
    <SidebarLayout active="/account" nav={nav} title="ตั้งค่าบัญชี" subtitle="จัดการข้อมูลส่วนตัวและการตั้งค่า">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 640 }}>
        <Card>
          <h4 className="display" style={{ margin: '0 0 4px', fontSize: 17, fontWeight: 600 }}>ข้อมูลส่วนตัว</h4>
          <p style={{ margin: '0 0 18px', fontSize: 13, color: 'var(--ink-3)' }}>ข้อมูลที่ใช้แสดงในระบบและออกใบเสร็จ</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 18, paddingBottom: 18, borderBottom: '1px solid var(--line)' }}>
            <Avatar name={name} size={64} />
            <div>
              <Button variant="secondary" size="sm">เปลี่ยนรูปโปรไฟล์</Button>
              <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 6 }}>JPG หรือ PNG, ไม่เกิน 2MB</div>
            </div>
          </div>
          <div style={{ display: 'grid', gap: 14 }}>
            <Input label="ชื่อ-สกุล" value={name} onChange={e => setName(e.target.value)} />
            <Input label="อีเมล" value={email} onChange={e => setEmail(e.target.value)} />
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
              <Button variant="ghost">ยกเลิก</Button>
              <Button variant="primary">บันทึก</Button>
            </div>
          </div>
        </Card>

        <Card>
          <h4 className="display" style={{ margin: '0 0 4px', fontSize: 17, fontWeight: 600 }}>รหัสผ่าน</h4>
          <p style={{ margin: '0 0 18px', fontSize: 13, color: 'var(--ink-3)' }}>เปลี่ยนรหัสผ่านเป็นประจำเพื่อความปลอดภัย</p>
          <Button variant="secondary" icon="lock">เปลี่ยนรหัสผ่าน</Button>
        </Card>

        <Card>
          <h4 className="display" style={{ margin: '0 0 14px', fontSize: 17, fontWeight: 600 }}>การแจ้งเตือน</h4>
          {[
            { label: 'อีเมลแจ้งเตือนคำสั่งซื้อ', sub: 'ใบเสร็จและการต่ออายุ', on: true },
            { label: 'ข่าวสารผลิตภัณฑ์ใหม่', sub: 'อัปเดตและโปรโมชั่น', on: true },
            { label: 'เคล็ดลับและบทความรายสัปดาห์', sub: 'จากทีม KindleStartup', on: false },
          ].map((it, i, arr) => (
            <ToggleRow key={it.label} {...it} divider={i < arr.length - 1} />
          ))}
        </Card>

        <Card>
          <h4 className="display" style={{ margin: '0 0 4px', fontSize: 17, fontWeight: 600 }}>ภาษา</h4>
          <p style={{ margin: '0 0 14px', fontSize: 13, color: 'var(--ink-3)' }}>เลือกภาษาที่จะใช้แสดงผล</p>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button variant="primary" size="sm">ไทย</Button>
            <Button variant="secondary" size="sm">English</Button>
          </div>
        </Card>

        <Card>
          <h4 className="display" style={{ margin: '0 0 4px', fontSize: 17, fontWeight: 600 }}>ออกจากระบบ</h4>
          <p style={{ margin: '0 0 14px', fontSize: 13, color: 'var(--ink-3)' }}>ออกจากบัญชีนี้บนอุปกรณ์เครื่องนี้</p>
          <Button variant="secondary" size="md" icon="logout" onClick={async () => {
            try { await window.Auth.signOut(); window.location.hash = '/'; }
            catch (e) { alert(e.message); }
          }}>ออกจากระบบ</Button>
        </Card>
      </div>
    </SidebarLayout>
  );
}

function ToggleRow({ label, sub, on, divider }) {
  const [v, setV] = useState(on);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 16, padding: '12px 0', borderBottom: divider ? '1px solid var(--line)' : 'none' }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{label}</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{sub}</div>
      </div>
      <button onClick={() => setV(!v)} style={{
        width: 40, height: 24, borderRadius: 999, border: 'none', cursor: 'pointer',
        background: v ? 'var(--ink)' : 'var(--line-2)',
        position: 'relative', transition: 'background .2s ease',
      }}>
        <span style={{
          position: 'absolute', top: 2, left: v ? 18 : 2, width: 20, height: 20,
          background: '#fff', borderRadius: '50%', transition: 'left .2s ease',
        }} />
      </button>
    </div>
  );
}

// ----- Sidebar layout (for My Products / Orders / Account) -----
function SidebarLayout({ active, nav, title, subtitle, children }) {
  const items = [
    { label: 'บัญชีของฉัน', path: '/my-products', icon: 'package' },
    { label: 'คำสั่งซื้อ', path: '/my-orders', icon: 'receipt' },
    { label: 'ตั้งค่าบัญชี', path: '/account', icon: 'settings' },
  ];
  return (
    <div style={{ maxWidth: 1280, margin: '0 auto', padding: '32px 28px 80px' }}>
      <div style={{ marginBottom: 28 }}>
        <h1 className="display" style={{ margin: 0, fontSize: 32, fontWeight: 600, letterSpacing: '-0.02em' }}>{title}</h1>
        {subtitle && <p style={{ margin: '6px 0 0', fontSize: 14.5, color: 'var(--ink-2)' }}>{subtitle}</p>}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr', gap: 32 }}>
        <aside>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, position: 'sticky', top: 88 }}>
            {items.map(it => (
              <button key={it.path} onClick={() => nav(it.path)} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                background: active === it.path ? 'var(--bg-2)' : 'transparent',
                border: 'none', padding: '10px 14px', borderRadius: 10,
                cursor: 'pointer', fontSize: 14, textAlign: 'left',
                color: active === it.path ? 'var(--ink)' : 'var(--ink-2)',
                fontWeight: active === it.path ? 500 : 400,
              }}>
                <I name={it.icon} size={15} style={{ color: active === it.path ? 'var(--ink)' : 'var(--ink-3)' }} />
                {it.label}
              </button>
            ))}
          </div>
        </aside>
        <div>{children}</div>
      </div>
    </div>
  );
}

Object.assign(window, {
  UserTopBar, Dashboard, MyProducts, MyOrders, Account, SidebarLayout,
});
