/* admin-views.jsx — JongMe Platform Admin view components.
   Exports to window: AUI (shared primitives), AdminOverview, AdminShops,
   AdminBilling, AdminAnalytics, AdminFlags */

// ── shared primitives ────────────────────────────────────────────────────────
const AUI = {
  Card: ({ title, sub, action, children, style, pad = 20, bodyStyle }) => (
    <div style={{ background: AT.surface, border: `1px solid ${AT.line}`, borderRadius: AT.radius, boxShadow: AT.shadow, display: 'flex', flexDirection: 'column', ...style }}>
      {(title || action) && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: `16px ${pad}px`, borderBottom: `1px solid ${AT.line2}` }}>
          <div>
            <div style={{ font: `600 14.5px/1.2 ${AT.font}`, color: AT.ink }}>{title}</div>
            {sub && <div style={{ font: `400 12px/1.2 ${AT.font}`, color: AT.faint, marginTop: 4 }}>{sub}</div>}
          </div>
          {action}
        </div>
      )}
      <div style={{ padding: pad, flex: 1, ...bodyStyle }}>{children}</div>
    </div>
  ),
  Btn: ({ children, on, kind = 'primary', sm, icon, style }) => {
    const base = { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 7, cursor: 'pointer', border: 'none', borderRadius: 10, font: `600 ${sm ? 12.5 : 13.5}px/1 ${AT.font}`, padding: sm ? '8px 12px' : '10px 16px', whiteSpace: 'nowrap', transition: 'filter .15s, background .15s', ...style };
    const kinds = {
      primary: { background: AT.primaryGrad, color: '#fff', boxShadow: '0 8px 18px -10px rgba(21,115,212,.6)' },
      soft: { background: AT.primarySoft, color: AT.primaryDeep },
      ghost: { background: AT.surface, color: AT.ink, border: `1px solid ${AT.line}` },
      danger: { background: AT.redSoft, color: AT.red },
      success: { background: AT.greenSoft, color: AT.green },
    };
    return <button onClick={on} style={{ ...base, ...kinds[kind] }} onMouseEnter={e => e.currentTarget.style.filter = 'brightness(.97)'} onMouseLeave={e => e.currentTarget.style.filter = 'none'}>{icon}{children}</button>;
  },
  Delta: ({ v, suffix = '%' }) => {
    const up = v >= 0;
    return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2, font: `700 12px/1 ${AT.font}`, color: up ? AT.green : AT.red, background: up ? AT.greenSoft : AT.redSoft, padding: '4px 7px', borderRadius: 6 }}>
      {up ? AIc.up(12) : AIc.down(12)}{Math.abs(v)}{suffix}
    </span>;
  },
};

// ── OVERVIEW ──────────────────────────────────────────────────────────────────
function AdminOverview({ shops, go, openShop }) {
  const k = ADMIN.kpis;
  const kpiCards = [
    { label: 'ร้านค้าทั้งหมด', value: fmt(k.shops.value), delta: k.shops.delta, dSuf: '', trend: k.shops.trend, icon: AIc.store, sub: 'ร้าน' },
    { label: 'Subscription ที่ active', value: fmt(k.active.value), delta: k.active.delta, dSuf: '', trend: k.active.trend, icon: AIc.check, sub: 'ราย' },
    { label: 'MRR (รายได้ต่อเดือน)', value: '฿' + fmt(k.mrr.value), delta: k.mrr.delta, dSuf: '%', trend: k.mrr.trend, icon: AIc.card, sub: '' },
    { label: 'การจองเดือนนี้', value: fmt(k.bookings.value), delta: k.bookings.delta, dSuf: '%', trend: k.bookings.trend, icon: AIc.bolt, sub: 'ครั้ง' },
  ];
  const pending = shops.filter(s => s.status === 'pending');
  const segs = ADMIN.plans.map(p => ({ value: p.count, color: p.color, label: p.name }));
  const actIcon = { pending: [AIc.clock, AT.amber, AT.amberSoft], up: [AIc.up, AT.primary, AT.primarySoft], fail: [AIc.x, AT.red, AT.redSoft], paid: [AIc.check, AT.green, AT.greenSoft], susp: [AIc.pause, AT.muted, AT.surface2] };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* KPI row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16 }}>
        {kpiCards.map((c, i) => (
          <div key={i} style={{ background: AT.surface, border: `1px solid ${AT.line}`, borderRadius: AT.radius, boxShadow: AT.shadow, padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ width: 36, height: 36, borderRadius: 10, background: AT.primarySoft, color: AT.primary, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{c.icon(19)}</span>
              <AUI.Delta v={c.delta} suffix={c.dSuf} />
            </div>
            <div style={{ font: `400 12.5px/1 ${AT.font}`, color: AT.muted, marginTop: 16 }}>{c.label}</div>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginTop: 7 }}>
              <span style={{ font: `700 25px/1 ${AT.font}`, color: AT.ink, letterSpacing: -0.5 }}>{c.value}<span style={{ font: `500 12px/1 ${AT.font}`, color: AT.faint, marginLeft: 4 }}>{c.sub}</span></span>
              <Sparkline data={c.trend} w={84} h={32} />
            </div>
          </div>
        ))}
      </div>

      {/* revenue + plan distribution */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.62fr 1fr', gap: 16 }}>
        <AUI.Card title="แนวโน้มรายได้ · MRR" sub="หน่วยพันบาท · 8 เดือนล่าสุด" action={<AUI.Delta v={8.4} />}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 6 }}>
            <span style={{ font: `700 26px/1 ${AT.font}`, color: AT.ink }}>฿412,800</span>
            <span style={{ font: `400 12.5px/1 ${AT.font}`, color: AT.muted }}>เดือนนี้</span>
          </div>
          <AreaChart data={ADMIN.revenue} />
        </AUI.Card>

        <AUI.Card title="การกระจาย Plan" sub={`${fmt(ADMIN.plans.reduce((a,p)=>a+p.count,0))} ร้าน`}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
            <Donut segments={segs} size={132} thick={20} center={{ top: '248', sub: 'ร้าน' }} />
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 11 }}>
              {ADMIN.plans.map(p => (
                <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 3, background: p.color }} />
                  <span style={{ flex: 1, font: `500 13px/1 ${AT.font}`, color: AT.ink }}>{p.name}</span>
                  <span style={{ font: `700 13px/1 ${AT.font}`, color: AT.ink }}>{p.count}</span>
                </div>
              ))}
            </div>
          </div>
        </AUI.Card>
      </div>

      {/* pending + activity */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <AUI.Card title="รออนุมัติ" sub={`${pending.length} ร้านสมัครใหม่`} action={<AUI.Btn kind="soft" sm on={() => go('shops')}>ดูทั้งหมด</AUI.Btn>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {pending.map(s => (
              <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 12px', border: `1px solid ${AT.line2}`, borderRadius: 12, background: AT.surface2 }}>
                <span style={{ width: 38, height: 38, borderRadius: 10, background: '#fff', border: `1px solid ${AT.line}`, color: AT.primary, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{AIc.store(18)}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ font: `600 13.5px/1.2 ${AT.font}`, color: AT.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</div>
                  <div style={{ font: `400 11.5px/1 ${AT.font}`, color: AT.muted, marginTop: 4 }}>{s.area} · {s.owner} · <PlanBadge plan={s.plan} /></div>
                </div>
                <AUI.Btn kind="success" sm icon={AIc.check(14)} on={() => openShop(s.id)}>ตรวจ</AUI.Btn>
              </div>
            ))}
          </div>
        </AUI.Card>

        <AUI.Card title="กิจกรรมล่าสุด" sub="ทั้ง platform">
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {ADMIN.activity.map((a, i) => {
              const [ic, c, b] = actIcon[a.kind];
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderBottom: i < ADMIN.activity.length - 1 ? `1px solid ${AT.line2}` : 'none' }}>
                  <span style={{ width: 32, height: 32, borderRadius: 9, background: b, color: c, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{ic(16)}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ font: `600 13px/1.2 ${AT.font}`, color: AT.ink }}>{a.who}</div>
                    <div style={{ font: `400 11.5px/1 ${AT.font}`, color: AT.muted, marginTop: 3 }}>{a.what}</div>
                  </div>
                  <span style={{ font: `400 11px/1 ${AT.font}`, color: AT.faint, whiteSpace: 'nowrap' }}>{a.when}</span>
                </div>
              );
            })}
          </div>
        </AUI.Card>
      </div>
    </div>
  );
}

// ── SHOPS ─────────────────────────────────────────────────────────────────────
function AdminShops({ shops, openShop, query, setQuery, onRegister, onShopAction }) {
  const [tab, setTab] = React.useState('all');
  const [confirm, setConfirm] = React.useState(null); // { action, shop }
  const tabs = [
    { id: 'all', label: 'ทั้งหมด', n: shops.length },
    { id: 'active', label: 'ใช้งานอยู่', n: shops.filter(s => s.status === 'active').length },
    { id: 'pending', label: 'รออนุมัติ', n: shops.filter(s => s.status === 'pending').length },
    { id: 'suspended', label: 'ระงับ', n: shops.filter(s => s.status === 'suspended').length },
  ];
  const filtered = shops.filter(s => (tab === 'all' || s.status === tab) && (!query || (s.name + s.th + s.area + s.owner).toLowerCase().includes(query.toLowerCase())));
  const cols = '1.9fr 1fr 0.75fr 1fr 0.85fr 0.7fr 0.85fr 0.9fr 0.75fr 1.65fr';
  const cell = { font: `400 13px/1.3 ${AT.font}`, color: AT.ink, display: 'flex', alignItems: 'center' };

  const fmtDate = (iso) => {
    if (!iso) return '—';
    const [y, m, d] = String(iso).substring(0,10).split('-');
    return `${d}/${m}/${y}`;
  };

  const askConfirm = (action, shop) => setConfirm({ action, shop });
  const doConfirm  = () => { if (confirm) { onShopAction && onShopAction(confirm.action, confirm.shop); setConfirm(null); } };

  const confirmCfg = confirm ? {
    approve:  { title: 'ยืนยันการอนุมัติ',  body: `อนุมัติร้าน "${confirm.shop.name}" และเปิดใช้งานทันที?`,  okLabel: 'อนุมัติ',  okColor: AT.green,  okBg: AT.greenSoft  },
    suspend:  { title: 'ยืนยันการระงับ',    body: `ระงับการใช้งานร้าน "${confirm.shop.name}"?`,              okLabel: 'ระงับ',    okColor: AT.red,    okBg: AT.redSoft    },
    activate: { title: 'ยืนยันการเปิดใช้',  body: `เปิดใช้งานร้าน "${confirm.shop.name}" อีกครั้ง?`,        okLabel: 'เปิดใช้',  okColor: AT.primary, okBg: AT.primarySoft },
  }[confirm.action] : null;

  // Small action icon button
  const ActBtn = ({ icon, label, color = AT.muted, bg = AT.surface2, onClick }) => (
    <button
      title={label}
      onClick={e => { e.stopPropagation(); onClick(); }}
      style={{ display:'flex', alignItems:'center', gap:5, cursor:'pointer', border:`1px solid ${AT.line}`,
               borderRadius:8, padding:'5px 8px', background:bg, color, whiteSpace:'nowrap',
               font:`500 11.5px/1 ${AT.font}`, transition:'filter .15s' }}
      onMouseEnter={e => e.currentTarget.style.filter = 'brightness(.95)'}
      onMouseLeave={e => e.currentTarget.style.filter = 'none'}>
      {icon}{label}
    </button>
  );

  return (
    <>
    <AUI.Card pad={0} bodyStyle={{ padding: 0 }}>
      {/* toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 20px', borderBottom: `1px solid ${AT.line2}`, gap: 16 }}>
        <div style={{ display: 'flex', gap: 6, background: AT.surface2, padding: 4, borderRadius: 11 }}>
          {tabs.map(tb => (
            <button key={tb.id} onClick={() => setTab(tb.id)} style={{ display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer', border: 'none', borderRadius: 8, padding: '8px 13px', font: `600 13px/1 ${AT.font}`, background: tab === tb.id ? '#fff' : 'transparent', color: tab === tb.id ? AT.ink : AT.muted, boxShadow: tab === tb.id ? '0 1px 4px rgba(16,27,46,.08)' : 'none' }}>
              {tb.label}<span style={{ font: `700 11px/1 ${AT.font}`, color: tab === tb.id ? AT.primary : AT.faint, background: tab === tb.id ? AT.primarySoft : AT.line2, padding: '3px 6px', borderRadius: 20 }}>{tb.n}</span>
            </button>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: AT.surface2, border: `1px solid ${AT.line}`, borderRadius: 10, padding: '0 12px', width: 220, color: AT.faint }}>
            {AIc.search(16)}
            <input value={query} onChange={e => setQuery(e.target.value)} placeholder="ค้นหาร้าน..." style={{ border: 'none', outline: 'none', background: 'transparent', font: `400 13px/1 ${AT.font}`, color: AT.ink, padding: '9px 0', width: '100%' }} />
          </div>
          <AUI.Btn icon={AIc.plus(15)} on={onRegister}>เพิ่มร้าน</AUI.Btn>
        </div>
      </div>
      {/* header */}
      <div style={{ display: 'grid', gridTemplateColumns: cols, gap: 14, padding: '11px 20px', borderBottom: `1px solid ${AT.line2}`, background: AT.surface2 }}>
        {['ร้านค้า', 'เจ้าของ', 'ที่ตั้ง', 'แพ็กเกจ', 'สถานะ', 'Package', 'เริ่ม', 'สิ้นสุด', 'คงเหลือ', ''].map((h, i) => (
          <span key={i} style={{ font: `600 11px/1 ${AT.font}`, color: AT.faint, textTransform: 'uppercase', letterSpacing: 0.4, display: 'flex', alignItems: 'center' }}>{h}</span>
        ))}
      </div>
      {/* rows */}
      <div>
        {filtered.map((s, i) => (
          <div key={s.id} onClick={() => openShop(s.id)} className="adm-row" style={{ display: 'grid', gridTemplateColumns: cols, gap: 10, padding: '12px 20px', borderBottom: i < filtered.length - 1 ? `1px solid ${AT.line2}` : 'none', cursor: 'pointer', alignItems: 'center' }}>
            {/* ร้านค้า */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
              <span style={{ width: 34, height: 34, borderRadius: 9, background: AT.primarySoft, color: AT.primary, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, font: `700 13px/1 ${AT.font}` }}>{s.name[0]}</span>
              <div style={{ minWidth: 0 }}>
                <div style={{ font: `600 13px/1.2 ${AT.font}`, color: AT.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</div>
                <div style={{ font: `400 11px/1 ${AT.font}`, color: AT.faint, marginTop: 3 }}>{s.name_th || s.th}</div>
              </div>
            </div>
            {/* เจ้าของ */}
            <span style={{ ...cell, font: `400 12.5px/1.3 ${AT.font}` }}>{s.owner}</span>
            {/* ที่ตั้ง */}
            <span style={{ ...cell, font: `400 12px/1.3 ${AT.font}`, color: AT.muted }}>{s.area}</span>
            {/* แพ็กเกจ */}
            <span style={cell}><PlanBadge plan={s.plan || s.package_slug} /></span>
            {/* สถานะ */}
            <span style={cell}><StatusPill status={s.status} /></span>
            {/* Package (price) */}
            <span style={{ ...cell, font: `600 12.5px/1 ${AT.font}` }}>{s.mrr ? '฿' + fmt(s.mrr) : '—'}</span>
            {/* เริ่ม */}
            <span style={{ ...cell, font: `400 12px/1 ${AT.font}`, color: AT.muted }}>{fmtDate(s.start_date)}</span>
            {/* สิ้นสุด */}
            <span style={{ ...cell, font: `400 12px/1 ${AT.font}`, color: AT.muted }}>{fmtDate(s.end_date)}</span>
            {/* คงเหลือ */}
            <span style={{ ...cell, font: `600 12px/1 ${AT.font}`,
              color: s.days_left === null || s.days_left === undefined ? AT.faint
                   : Number(s.days_left) <= 0 ? AT.red
                   : Number(s.days_left) <= 7 ? AT.amber : AT.green }}>
              {s.start_date
                ? (Number(s.days_left) <= 0 ? 'หมดอายุ' : s.days_left + ' วัน')
                : '—'}
            </span>
            {/* Actions */}
            <div style={{ display: 'flex', gap: 5, alignItems: 'center' }} onClick={e => e.stopPropagation()}>
              <ActBtn icon={AIc.ext(12)} label="ร้านค้า" color={AT.primaryDeep} bg={AT.primarySoft}
                onClick={() => window.open('#', '_blank')} />
              <ActBtn icon={AIc.pkg(12)} label="แพ็กเกจ" color={AT.violet} bg={AT.violetSoft}
                onClick={() => onShopAction && onShopAction('packages', s)} />
              {s.status === 'active' && (
                <ActBtn icon={AIc.pause(12)} label="ระงับ" color={AT.red} bg={AT.redSoft}
                  onClick={() => askConfirm('suspend', s)} />
              )}
              {s.status === 'suspended' && (
                <ActBtn icon={AIc.refresh(12)} label="เปิดใช้" color={AT.green} bg={AT.greenSoft}
                  onClick={() => askConfirm('activate', s)} />
              )}
              {s.status === 'pending' && (
                <ActBtn icon={AIc.check(12)} label="อนุมัติ" color={AT.green} bg={AT.greenSoft}
                  onClick={() => askConfirm('approve', s)} />
              )}
            </div>
          </div>
        ))}
        {filtered.length === 0 && <div style={{ padding: 40, textAlign: 'center', font: `400 13px/1 ${AT.font}`, color: AT.faint }}>ไม่พบร้านค้า</div>}
      </div>
    </AUI.Card>

    {/* Confirm modal */}
    {confirm && confirmCfg && (
      <div style={{ position:'fixed', inset:0, background:'rgba(11,22,35,.45)', display:'flex',
                    alignItems:'center', justifyContent:'center', zIndex:2000 }}
           onClick={() => setConfirm(null)}>
        <div style={{ background:'#fff', borderRadius:16, padding:'28px 28px 22px', width:380,
                      boxShadow:'0 8px 40px rgba(11,22,35,.18)', display:'flex', flexDirection:'column', gap:14 }}
             onClick={e => e.stopPropagation()}>
          <div style={{ font:`700 16px/1.2 ${AT.font}`, color:AT.ink }}>{confirmCfg.title}</div>
          <div style={{ font:`400 13.5px/1.6 ${AT.font}`, color:AT.muted }}>{confirmCfg.body}</div>
          <div style={{ display:'flex', gap:10, justifyContent:'flex-end', marginTop:4 }}>
            <button onClick={() => setConfirm(null)}
              style={{ font:`500 13px/1 ${AT.font}`, color:AT.muted, background:AT.surface2,
                       border:`1px solid ${AT.line}`, borderRadius:9, padding:'9px 18px', cursor:'pointer' }}>
              ยกเลิก
            </button>
            <button onClick={doConfirm}
              style={{ font:`600 13px/1 ${AT.font}`, color:confirmCfg.okColor, background:confirmCfg.okBg,
                       border:`1px solid ${confirmCfg.okBg}`, borderRadius:9, padding:'9px 20px', cursor:'pointer' }}>
              {confirmCfg.okLabel}
            </button>
          </div>
        </div>
      </div>
    )}
    </>
  );
}

// ── BILLING ───────────────────────────────────────────────────────────────────
function AdminBilling({ invoices, retry }) {
  const failed = invoices.filter(i => i.status === 'failed');
  const failedSum = failed.reduce((a, i) => a + i.amount, 0);
  const stat = [
    { label: 'MRR', value: '฿412,800', c: AT.primary, b: AT.primarySoft, icon: AIc.card },
    { label: 'รายได้เดือนนี้', value: '฿438,210', c: AT.green, b: AT.greenSoft, icon: AIc.up },
    { label: 'ค้างชำระ', value: '฿' + fmt(failedSum), c: AT.red, b: AT.redSoft, icon: AIc.x, note: `${failed.length} ใบแจ้งหนี้` },
    { label: 'Active subscriptions', value: '214', c: AT.violet, b: AT.violetSoft, icon: AIc.check },
  ];
  const istatus = { paid: AT.green, failed: AT.red, pending: AT.amber };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16 }}>
        {stat.map((s, i) => (
          <div key={i} style={{ background: AT.surface, border: `1px solid ${AT.line}`, borderRadius: AT.radius, boxShadow: AT.shadow, padding: 18 }}>
            <span style={{ width: 36, height: 36, borderRadius: 10, background: s.b, color: s.c, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{s.icon(18)}</span>
            <div style={{ font: `400 12.5px/1 ${AT.font}`, color: AT.muted, marginTop: 15 }}>{s.label}</div>
            <div style={{ font: `700 23px/1 ${AT.font}`, color: AT.ink, marginTop: 7, letterSpacing: -0.5 }}>{s.value}</div>
            {s.note && <div style={{ font: `500 11.5px/1 ${AT.font}`, color: AT.red, marginTop: 6 }}>{s.note}</div>}
          </div>
        ))}
      </div>

      {/* plan revenue + invoices */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.7fr', gap: 16, alignItems: 'start' }}>
        <AUI.Card title="รายได้ตาม Plan" sub="ต่อเดือน">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {ADMIN.plans.filter(p => p.price > 0).map(p => {
              const rev = p.price * p.count, max = Math.max(...ADMIN.plans.filter(x => x.price > 0).map(x => x.price * x.count));
              return (
                <div key={p.id}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 7 }}>
                    <span style={{ font: `600 13px/1 ${AT.font}`, color: AT.ink, display: 'flex', alignItems: 'center', gap: 7 }}><span style={{ width: 8, height: 8, borderRadius: 3, background: p.color }} />{p.name} <span style={{ color: AT.faint, fontWeight: 400 }}>· {p.count} ร้าน</span></span>
                    <span style={{ font: `700 13px/1 ${AT.font}`, color: AT.ink }}>฿{fmt(rev)}</span>
                  </div>
                  <div style={{ height: 8, borderRadius: 6, background: AT.line2, overflow: 'hidden' }}><div style={{ width: `${Math.min(100, rev / max * 100)}%`, height: '100%', borderRadius: 6, background: p.color }} /></div>
                </div>
              );
            })}
          </div>
        </AUI.Card>

        <AUI.Card title="ใบแจ้งหนี้ล่าสุด" sub="Invoices" action={<AUI.Btn kind="ghost" sm icon={AIc.ext(14)}>ส่งออก</AUI.Btn>} pad={0} bodyStyle={{ padding: 0 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1.8fr 1fr 1fr 1fr 1.1fr', gap: 12, padding: '11px 18px', background: AT.surface2, borderBottom: `1px solid ${AT.line2}` }}>
            {['เลขที่', 'ร้านค้า', 'แพ็กเกจ', 'ยอด', 'สถานะ', ''].map((h, i) => <span key={i} style={{ font: `600 11px/1 ${AT.font}`, color: AT.faint, textTransform: 'uppercase', letterSpacing: 0.4 }}>{h}</span>)}
          </div>
          {invoices.map((iv, i) => (
            <div key={iv.id} style={{ display: 'grid', gridTemplateColumns: '1.1fr 1.8fr 1fr 1fr 1fr 1.1fr', gap: 12, padding: '13px 18px', borderBottom: i < invoices.length - 1 ? `1px solid ${AT.line2}` : 'none', alignItems: 'center' }}>
              <span style={{ font: `600 12.5px/1 ${AT.font}`, color: AT.primary }}>{iv.id}</span>
              <div><div style={{ font: `500 13px/1.2 ${AT.font}`, color: AT.ink }}>{iv.shop}</div><div style={{ font: `400 11px/1 ${AT.font}`, color: AT.faint, marginTop: 3 }}>{iv.date}</div></div>
              <span style={{ font: `400 12.5px/1 ${AT.font}`, color: AT.muted, alignSelf: 'center' }}>{iv.plan}</span>
              <span style={{ font: `600 13px/1 ${AT.font}`, color: AT.ink, alignSelf: 'center' }}>฿{fmt(iv.amount)}</span>
              <span style={{ alignSelf: 'center' }}><StatusPill status={iv.status} /></span>
              <span style={{ alignSelf: 'center', justifySelf: 'end' }}>{iv.status === 'failed' ? <AUI.Btn kind="soft" sm icon={AIc.refresh(13)} on={() => retry(iv.id)}>เรียกเก็บ</AUI.Btn> : <span style={{ font: `400 12px/1 ${AT.font}`, color: AT.faint }}>—</span>}</span>
            </div>
          ))}
        </AUI.Card>
      </div>
    </div>
  );
}

// ── ANALYTICS ─────────────────────────────────────────────────────────────────
function AdminAnalytics({ shops }) {
  const top = [...shops].filter(s => s.bk > 0).sort((a, b) => b.bk - a.bk).slice(0, 5);
  const maxBk = top[0]?.bk || 1;
  const metrics = [
    { label: 'การจองทั้งหมด', value: '18,430', d: 14.2 },
    { label: 'อัตรามาตามนัด', value: '91.4%', d: 2.1 },
    { label: 'No-show rate', value: '6.2%', d: -1.4 },
    { label: 'มัดจำที่เก็บได้', value: '฿284,500', d: 11.8 },
  ];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16 }}>
        {metrics.map((m, i) => (
          <div key={i} style={{ background: AT.surface, border: `1px solid ${AT.line}`, borderRadius: AT.radius, boxShadow: AT.shadow, padding: 18 }}>
            <div style={{ font: `400 12.5px/1 ${AT.font}`, color: AT.muted }}>{m.label}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 9, marginTop: 9 }}>
              <span style={{ font: `700 24px/1 ${AT.font}`, color: AT.ink, letterSpacing: -0.5 }}>{m.value}</span>
              <AUI.Delta v={m.d} />
            </div>
          </div>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 16, alignItems: 'start' }}>
        <AUI.Card title="ปริมาณการจองทั้ง platform" sub="หน่วยพันครั้ง · 8 เดือนล่าสุด">
          <AreaChart data={ADMIN.revenue.map((r, i) => ({ m: r.m, v: ADMIN.kpis.bookings.trend[i + 4] || r.v / 22 }))} color={AT.violet} />
        </AUI.Card>
        <AUI.Card title="ร้านที่จองสูงสุด" sub="30 วันล่าสุด">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 15 }}>
            {top.map((s, i) => (
              <div key={s.id}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ font: `500 13px/1 ${AT.font}`, color: AT.ink }}><b style={{ color: AT.faint, marginRight: 8 }}>{i + 1}</b>{s.name}</span>
                  <span style={{ font: `700 13px/1 ${AT.font}`, color: AT.ink }}>{fmt(s.bk)}</span>
                </div>
                <div style={{ height: 7, borderRadius: 6, background: AT.line2, overflow: 'hidden' }}><div style={{ width: `${s.bk / maxBk * 100}%`, height: '100%', background: AT.primaryGrad, borderRadius: 6 }} /></div>
              </div>
            ))}
          </div>
        </AUI.Card>
      </div>
    </div>
  );
}

// ── FEATURE FLAGS ─────────────────────────────────────────────────────────────
function AdminFlags({ features, toggle }) {
  const planCols = ADMIN.plans.filter(p => p.id !== 'trial');
  return (
    <AUI.Card title="Feature flags" sub="ควบคุมฟีเจอร์ที่เปิดให้แต่ละแพ็กเกจ" pad={0} bodyStyle={{ padding: 0 }}>
      <div style={{ display: 'grid', gridTemplateColumns: `2.4fr repeat(${planCols.length}, 1fr)`, gap: 12, padding: '13px 22px', background: AT.surface2, borderBottom: `1px solid ${AT.line2}` }}>
        <span style={{ font: `600 11px/1 ${AT.font}`, color: AT.faint, textTransform: 'uppercase', letterSpacing: 0.4 }}>ฟีเจอร์</span>
        {planCols.map(p => <span key={p.id} style={{ font: `600 12px/1 ${AT.font}`, color: AT.ink, textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: 3, background: p.color }} />{p.name}</span>)}
      </div>
      {features.map((f, i) => (
        <div key={f.id} style={{ display: 'grid', gridTemplateColumns: `2.4fr repeat(${planCols.length}, 1fr)`, gap: 12, padding: '16px 22px', borderBottom: i < features.length - 1 ? `1px solid ${AT.line2}` : 'none', alignItems: 'center' }}>
          <div>
            <div style={{ font: `600 13.5px/1.2 ${AT.font}`, color: AT.ink }}>{f.name}</div>
            <div style={{ font: `400 12px/1.3 ${AT.font}`, color: AT.muted, marginTop: 4 }}>{f.desc}</div>
          </div>
          {planCols.map(p => {
            const on = f.plans[p.id];
            return (
              <div key={p.id} style={{ display: 'flex', justifyContent: 'center' }}>
                <button onClick={() => toggle(f.id, p.id)} role="switch" aria-checked={on} style={{ width: 42, height: 25, borderRadius: 20, border: 'none', cursor: 'pointer', background: on ? AT.primary : AT.line, position: 'relative', transition: 'background .2s', padding: 0 }}>
                  <span style={{ position: 'absolute', top: 3, left: on ? 20 : 3, width: 19, height: 19, borderRadius: 19, background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,.25)', transition: 'left .18s' }} />
                </button>
              </div>
            );
          })}
        </div>
      ))}
    </AUI.Card>
  );
}

Object.assign(window, { AUI, AdminOverview, AdminShops, AdminBilling, AdminAnalytics, AdminFlags });
