// EMphasis System — ES tabs (split from emphasis.jsx).
// EsPersonalTab, EsWheel, EsBTTab, EsPacksTab, EsSlidesTab, SLIDE_TEMPLATES.
// Owns window.EmphasisSystemView export.

// ============= Personal — Wheel of Life + Skills + 100 Dreams =============
function EsPersonalTab() {
  return (
    <div className="grid grid-cols-12 gap-4">
      <Card className="col-span-12 lg:col-span-6" title="Wheel of Life" action={<Pill color="#2F5DE5" tint="#EEF4FF">avg 7.0 / 10</Pill>}>
        <div className="grid grid-cols-12 gap-4 items-center">
          <div className="col-span-12 sm:col-span-7 flex justify-center">
            <EsWheel />
          </div>
          <div className="col-span-12 sm:col-span-5 space-y-1.5">
            {WHEEL.map(w => (
              <div key={w.area} className="flex items-center gap-2">
                <span className="text-xs text-ink-700 w-24">{w.area}</span>
                <Bar value={w.score} max={10} color="#2F5DE5" height={4} />
                <span className="text-[11px] num text-ink-500 w-6 text-right">{w.score}</span>
              </div>
            ))}
          </div>
        </div>
      </Card>

      <Card className="col-span-12 lg:col-span-6"
            title={<div className="flex items-center gap-2"><span className="text-sm font-semibold text-ink-800">Personal Skill Checkup</span><span className="text-[11px] text-ink-400">9% · 12% · 21% group</span></div>}
            action={<Pill color="#1B379F" tint="#EEF4FF" icon={<Icon name="bolt" className="w-3 h-3" />}>12% Group</Pill>}>
        <div className="space-y-3">
          {SKILLS.map(s => {
            const pct = s.score / s.max;
            return (
              <div key={s.id}>
                <div className="flex items-center justify-between mb-1.5">
                  <span className="text-xs font-medium text-ink-700">{s.label}</span>
                  <span className="text-[11px] num text-ink-500">{s.score}/{s.max}</span>
                </div>
                <Bar value={s.score} max={s.max} height={6} color={pct >= 0.9 ? '#10B981' : pct >= 0.6 ? '#2F5DE5' : '#F59E0B'} />
              </div>
            );
          })}
        </div>
        <div className="mt-5 pt-4 border-t border-ink-100 grid grid-cols-3 gap-2 text-center">
          {[
            { label: '9%',  color: '#10B981', desc: 'พื้นฐาน' },
            { label: '12%', color: '#2F5DE5', desc: 'กลาง', active: true },
            { label: '21%', color: '#1B379F', desc: 'สูง' },
          ].map(g => (
            <div key={g.label} className={`rounded-lg p-2 ${g.active ? 'ring-2 ring-brand-500 bg-brand-50' : 'bg-ink-50/50'}`}>
              <div className="text-base font-bold num" style={{ color: g.color }}>{g.label}</div>
              <div className="text-[10px] text-ink-500">{g.desc}</div>
            </div>
          ))}
        </div>
      </Card>

      <Card className="col-span-12" title={
        <div className="flex items-center gap-2">
          <span className="text-sm font-semibold text-ink-800">100 Dreamlist</span>
          <span className="text-[11px] text-ink-400">เป้าหมายชีวิตทั้งหมด</span>
        </div>
      } action={<Btn variant="ghost" size="sm" icon={<Icon name="plus" />}>เพิ่ม</Btn>}>
        <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-2">
          {[
            ['🏝️ บ้านที่หัวหิน', true], ['🚗 BMW M3', false], ['✈️ ยุโรป 30 วัน', false],
            ['💎 Diamond Pin', false], ['👨‍👩‍👧 พ่อแม่เลิกทำงาน', true], ['📚 หนังสือ 50 เล่ม', true],
            ['🏋️ น้ำหนัก 58kg', false], ['🎓 จบ MBA', false], ['🏆 รถ Top Achiever', false],
            ['💰 รายได้ 7 หลัก', false], ['🌍 ไป 30 ประเทศ', false], ['🎤 พูด TEDx', false],
          ].map(([dream, done], i) => (
            <div key={i} className={`rounded-lg border p-2.5 text-xs ${done ? 'border-emerald-200 bg-emerald-50/40' : 'border-ink-100 bg-white'}`}>
              <div className="flex items-start gap-1.5">
                <input type="checkbox" defaultChecked={done} className="mt-0.5 accent-emerald-500" />
                <span className={`text-ink-700 ${done ? 'line-through text-ink-400' : ''}`}>{dream}</span>
              </div>
            </div>
          ))}
          <div className="rounded-lg border-2 border-dashed border-ink-200 p-2.5 text-xs text-ink-400 flex items-center justify-center hover:border-brand-300 hover:text-brand-500 cursor-pointer">
            + 88 ที่เหลือ
          </div>
        </div>
      </Card>
    </div>
  );
}

function EsWheel() {
  const size = 220;
  const cx = size / 2, cy = size / 2;
  const segs = WHEEL.length;
  const max = 10;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <defs>
        <radialGradient id="esWheelGrad">
          <stop offset="0%" stopColor="#2F5DE5" stopOpacity="0.5" />
          <stop offset="100%" stopColor="#2F5DE5" stopOpacity="0.15" />
        </radialGradient>
      </defs>
      {[1, 2.5, 5, 7.5, 10].map((r, i) => (
        <circle key={i} cx={cx} cy={cy} r={(r / max) * (size / 2 - 12)} fill="none" stroke="#E6EAF3" strokeWidth="1" />
      ))}
      {WHEEL.map((w, i) => {
        const a = (i / segs) * Math.PI * 2 - Math.PI / 2;
        const r = size / 2 - 12;
        return <line key={i} x1={cx} y1={cy} x2={cx + Math.cos(a) * r} y2={cy + Math.sin(a) * r} stroke="#E6EAF3" strokeWidth="1" />;
      })}
      <polygon
        fill="url(#esWheelGrad)"
        stroke="#2F5DE5"
        strokeWidth="2"
        points={WHEEL.map((w, i) => {
          const a = (i / segs) * Math.PI * 2 - Math.PI / 2;
          const r = (w.score / max) * (size / 2 - 12);
          return `${cx + Math.cos(a) * r},${cy + Math.sin(a) * r}`;
        }).join(' ')}
      />
      {WHEEL.map((w, i) => {
        const a = (i / segs) * Math.PI * 2 - Math.PI / 2;
        const r = size / 2 - 4;
        return (
          <text key={i} x={cx + Math.cos(a) * r} y={cy + Math.sin(a) * r + 3}
                textAnchor="middle" fontSize="9" fill="#445576" fontWeight="600">{w.area}</text>
        );
      })}
    </svg>
  );
}

// ============= BT Qualification — Checklist + 9 Principles =============
function EsBTTab() {
  const done = BT_CHECKLIST.filter(b => b.done).length;
  return (
    <div className="grid grid-cols-12 gap-4">
      <Card className="col-span-12 lg:col-span-7" title="BT Qualification Checklist · 6 ข้อ"
            action={<Pill color="#10B981" tint="#E7F8F1">{done}/6 ผ่าน</Pill>}>
        <div className="space-y-2.5">
          {BT_CHECKLIST.map((b, i) => (
            <div key={b.id} className={`flex items-center gap-3 p-3 rounded-xl border ${b.done ? 'border-emerald-100 bg-emerald-50/30' : 'border-ink-100 bg-white'}`}>
              <div className={`w-6 h-6 rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold ${b.done ? 'bg-emerald-500 text-white' : 'border-2 border-ink-200 text-ink-400'}`}>
                {b.done ? <Icon name="check" className="w-3 h-3" strokeWidth={3} /> : i + 1}
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-sm font-medium text-ink-900">{b.label}</div>
                <div className="text-[11px] text-ink-500 num mt-0.5">{b.detail}</div>
                {!b.done && b.progress !== undefined && (
                  <div className="mt-1.5"><Bar value={b.progress} color="#F59E0B" height={3} /></div>
                )}
              </div>
              {b.done && <Pill color="#10B981" tint="#E7F8F1" size="xs">✓ ผ่าน</Pill>}
            </div>
          ))}
        </div>
      </Card>

      <Card className="col-span-12 lg:col-span-5" title="9 Principles for Success">
        <div className="space-y-2">
          {PRINCIPLES.map(p => (
            <div key={p.id} className="flex items-center gap-2.5">
              <div className={`w-7 h-7 rounded-md flex-shrink-0 flex items-center justify-center text-[11px] font-bold ${p.done ? 'bg-brand-500 text-white' : 'bg-ink-100 text-ink-400'}`}>
                {p.done ? <Icon name="check" className="w-3.5 h-3.5" strokeWidth={3} /> : p.id}
              </div>
              <div className="flex-1 min-w-0">
                <div className="text-xs font-medium text-ink-700">{p.label}</div>
                {!p.done && p.progress !== undefined && (
                  <div className="mt-1"><Bar value={p.progress} color="#2F5DE5" height={2.5} /></div>
                )}
              </div>
              <span className="text-[10px] num text-ink-400">{p.done ? '100%' : `${Math.round((p.progress || 0) * 100)}%`}</span>
            </div>
          ))}
        </div>
        <div className="mt-4 pt-3 border-t border-ink-100 flex items-center justify-between text-[11px] text-ink-500">
          <span>เสร็จ {PRINCIPLES.filter(p => p.done).length} / 9</span>
          <Btn variant="ghost" size="sm" icon={<Icon name="arrowR" className="w-3 h-3" />}>ดูรายละเอียด</Btn>
        </div>
      </Card>
    </div>
  );
}

// ============= 15 EM Pack — YouTube link library =============
// Shows ONLY the packs ticked for the logged-in ABO in their ABO Tracking
// row (fu_state pBoard / p1..p15). No "show all" — a user only ever sees
// their own packs.
function EsPacksTab({ currentUser }) {
  const [copiedNum, setCopiedNum] = useState(null);
  const [selfRow, setSelfRow] = useState(null); // the logged-in user's own ABO row
  const [ready, setReady] = useState(false);

  // The logged-in user's own ABO row (readable via the abo-self RLS policy).
  useEffect(() => {
    let cancelled = false;
    (async () => {
      if (!window.SB_READY || !currentUser?.abo_code || !window.supabase) { setReady(true); return; }
      const { data } = await window.supabase
        .from('prospects')
        .select('id, name, abo_code, fu_state')
        .eq('abo_code', currentUser.abo_code)
        .limit(1)
        .maybeSingle();
      if (cancelled) return;
      if (data) setSelfRow(data);
      setReady(true);
    })();
    return () => { cancelled = true; };
  }, [currentUser?.abo_code]);

  // Super-admin (ABO 7014634134) sees every pack; everyone else sees only
  // the packs ticked for them in ABO Tracking.
  const isSuperAdmin = currentUser?.abo_code === '7014634134';
  // Pack num → fu_state key: 0 → pBoard, N → pN.
  const packKey = (num) => num === 0 ? 'pBoard' : typeof num === 'string' ? `p${num}` : `p${num}`;
  const ticked = selfRow ? (selfRow.fu_state || {}) : {};
  const visiblePacks = isSuperAdmin
    ? EM_PACKS
    : EM_PACKS.filter(p => typeof p.num === 'string' || !!ticked[packKey(p.num)]);

  const copy = async (p) => {
    if (!p.url || p.url === '#') return;
    try {
      await navigator.clipboard.writeText(p.url);
    } catch {
      // Fallback for browsers without clipboard API.
      const ta = document.createElement('textarea');
      ta.value = p.url; document.body.appendChild(ta); ta.select();
      try { document.execCommand('copy'); } catch {}
      document.body.removeChild(ta);
    }
    setCopiedNum(p.num);
    setTimeout(() => setCopiedNum(c => c === p.num ? null : c), 1500);
  };

  return (
    <div className="space-y-4">
      <Card pad={false}>
        <div className="p-4 flex items-center gap-3 bg-gradient-to-r from-rose-50 via-white to-brand-50 flex-wrap">
          <div className="w-11 h-11 rounded-xl bg-rose-500 text-white flex items-center justify-center flex-shrink-0">
            <Icon name="youtube" className="w-6 h-6" strokeWidth={2} />
          </div>
          <div className="flex-1 min-w-0">
            <div className="text-[11px] uppercase tracking-wider text-rose-600 font-semibold">EM Pack · YouTube</div>
            <div className="text-base font-semibold text-ink-900">คลังลิงก์ EM Pack{isSuperAdmin ? '' : ' ของฉัน'}</div>
          </div>
          <span className="hidden sm:inline text-xs num text-ink-400">{visiblePacks.length} packs</span>
        </div>
      </Card>

      {ready && visiblePacks.length === 0 && (
        <Card>
          <div className="py-8 text-center text-sm text-ink-400">
            <div className="text-3xl mb-2">📦</div>
            {selfRow
              ? <>ยังไม่ได้ติ๊ก Pack ใดให้คุณใน ABO Tracking · ติดต่อ upline ได้เลย</>
              : <>ไม่พบข้อมูล ABO ของคุณใน ABO Tracking · ติดต่อ upline เพื่อเพิ่มเข้าระบบ</>}
          </div>
        </Card>
      )}

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2.5">
        {visiblePacks.map(p => {
          const hasLink = p.url && p.url !== '#';
          const copied = copiedNum === p.num;
          return (
            <div key={p.num}
              className="rounded-xl border border-ink-100 bg-white p-2.5 flex flex-col gap-2 hover:shadow-card transition-all">
              <div className="flex items-center gap-2">
                <div className="w-7 h-7 rounded-md bg-ink-900 text-white flex items-center justify-center font-bold text-xs num flex-shrink-0">
                  {p.label || p.num}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-[13px] font-semibold text-ink-900 leading-tight">{typeof p.num === 'string' ? p.title : `Pack ${p.num}`}</div>
                </div>
                <a
                  href={hasLink ? p.url : undefined}
                  target="_blank" rel="noopener noreferrer"
                  title={hasLink ? 'เปิดบน YouTube' : 'ยังไม่มีลิงก์'}
                  className={`w-6 h-6 rounded-md flex items-center justify-center flex-shrink-0 transition-all ${
                    hasLink ? 'text-rose-500 hover:bg-rose-50' : 'text-ink-200 pointer-events-none'
                  }`}>
                  <Icon name="youtube" className="w-3.5 h-3.5" />
                </a>
              </div>
              <button
                onClick={() => copy(p)}
                disabled={!hasLink}
                className={`w-full h-8 rounded-lg text-[12px] font-semibold inline-flex items-center justify-center gap-1.5 transition-all ${
                  !hasLink ? 'bg-ink-50 text-ink-300 cursor-not-allowed'
                  : copied ? 'bg-emerald-500 text-white'
                  : 'bg-brand-500 text-white hover:bg-brand-600'
                }`}>
                {copied ? (
                  <><Icon name="check" className="w-3.5 h-3.5" strokeWidth={3} /> คัดลอกแล้ว</>
                ) : (
                  <>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-3.5 h-3.5">
                      <rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V5a2 2 0 0 1 2-2h10" strokeLinecap="round" />
                    </svg>
                    คัดลอกลิงก์
                  </>
                )}
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ============= Slide / Plan Library =============
// Maps each entry in window.SLIDES to a real template definition that the
// Google Slides API can materialise into a brand-new deck. Each template is
// a list of { title, body[] } slides. Extend the bodies below as content
// matures — the IDs match what's in data.jsx.
const SLIDE_TEMPLATES = {
  // ── 6W Tracking template ─────────────────────────────────────────────
  // Central template for every 6W weight-tracking customer. After
  // creating the deck, the user fills in the [bracketed] placeholders in
  // Google Slides itself. Mirrors the data points the 6W Tracking view
  // already collects (measurements, weekly weight, products, photos).
  s6w: {
    title: '6W Tracking · ลูกค้า [ชื่อลูกค้า]',
    slides: [
      // 1. Cover
      {
        title: '🥤 6W Tracking',
        body: [
          'ชื่อลูกค้า: [ชื่อ-นามสกุล]',
          'ABO Code: [10 หลัก]',
          'เบอร์ติดต่อ: [08x-xxx-xxxx]',
          'วันที่เริ่ม: [DD/MM/YYYY]',
          'Sponsor: [ชื่อ Sponsor]',
        ],
      },
      // 2. Goals & Why
      {
        title: '🎯 เป้าหมาย & WHY',
        body: [
          'น้ำหนักเริ่มต้น: [xx.x] kg',
          'น้ำหนักเป้าหมาย: [xx.x] kg',
          'ลดลง: [x.x] kg ภายใน 6 สัปดาห์',
          'WHY ที่อยากลด: [เหตุผลของลูกค้า]',
          'เป้าหมายรอบเอว: [xx] cm',
        ],
      },
      // 3. Before — measurements
      {
        title: '📏 Before · วัดรอบตัว',
        body: [
          'วันที่วัด: [DD/MM/YYYY]',
          'น้ำหนัก: [xx.x] kg',
          'รอบเอว (Waist): [xx] cm',
          'รอบสะโพก (Hip): [xx] cm',
          'รอบแขน (Arm): [xx] cm',
          'รอบขา (Thigh): [xx] cm',
          'Body Fat %: [xx]%',
          'BMI: [xx.x]',
        ],
      },
      // 4. Before — photos placeholder
      {
        title: '📷 Before · ภาพถ่าย',
        body: [
          'รูปด้านหน้า: [แทรกรูปที่นี่]',
          'รูปด้านข้าง: [แทรกรูปที่นี่]',
          'รูปด้านหลัง: [แทรกรูปที่นี่]',
          'หมายเหตุ: เปลี่ยนชุดเดิมทุกสัปดาห์เพื่อเปรียบเทียบง่ายขึ้น',
        ],
      },
      // 5. Product set
      {
        title: '📦 ชุดผลิตภัณฑ์ที่ใช้',
        body: [
          'BodyKey Shake: [รสชาติ] · [จำนวน]',
          'Meal Bar: [จำนวน]',
          'Nutrilite Double X: [Yes/No]',
          'Phytopowder / Detox: [Yes/No]',
          'อื่นๆ: [ระบุ]',
          'วันส่ง Member Pack: [DD/MM/YYYY]',
        ],
      },
      // 6-11. Weeks 1-6
      ...[1, 2, 3, 4, 5, 6].map(w => ({
        title: `📅 สัปดาห์ที่ ${w}`,
        body: [
          `วันที่ check-in: [DD/MM/YYYY]`,
          `น้ำหนัก: [xx.x] kg`,
          `เปลี่ยนแปลง: [▼ x.x] kg (รวม ▼ [x.x] kg)`,
          `รอบเอว: [xx] cm`,
          `อาหารที่กิน: [สรุป]`,
          `อารมณ์ / พลังงาน: [ระบุ]`,
          `ปัญหาที่เจอ: [ถ้ามี]`,
          `แผนสัปดาห์ถัดไป: [ระบุ]`,
        ],
      })),
      // 12. Summary / After
      {
        title: '🎉 สรุปผล 6 สัปดาห์',
        body: [
          'น้ำหนักก่อน: [xx.x] kg → หลัง: [xx.x] kg',
          'ลดลงรวม: [x.x] kg ([xx]% ของเป้า)',
          'รอบเอวลดลง: [xx] → [xx] cm',
          'Body Fat ลดลง: [xx]% → [xx]%',
          'รูปเปรียบเทียบ Before / After: [แทรก]',
          'ก้าวต่อไป: [ต่อ EM13W / Maintenance / EM Begin]',
        ],
      },
    ],
  },

  s1: {
    title: 'Slide 1 · Why Amway',
    slides: [
      { title: 'Why Amway?', body: ['Track record · 60+ years', 'ตลาดในไทย / Global', 'ผู้ก่อตั้ง · DNA ครอบครัว'] },
      { title: 'Why now', body: ['Megatrends · Wellness · Beauty', 'Direct selling growth'] },
      { title: 'Why us', body: ['Sponsor structure', 'Tools + Coaching', 'Community'] },
    ],
  },
  s2: {
    title: 'Slide 2 · Business Model',
    slides: [
      { title: 'Business Model', body: ['Customer → Member → ABO', 'ระบบรายได้ 3 ขา'] },
      { title: 'Income streams', body: ['Retail Margin', 'Performance Bonus', 'Leadership Bonus'] },
      { title: 'Compounding', body: ['Repeat customers', 'Team growth', 'Bonus stacking'] },
    ],
  },
  s3: {
    title: 'Slide 3 · Income Plan',
    slides: [
      { title: 'Income Plan', body: ['PV / BV mechanics', 'Bracket ladder', 'Bonus % at each level'] },
      { title: 'Sample numbers', body: ['Bronze · 7,500 PV', 'Silver · 15,000 PV', 'Gold · ~50,000 PV'] },
    ],
  },
  s4: {
    title: 'Slide 4 · 9 Slides Overview',
    slides: [
      { title: '9 Slides', body: ['ภาพรวม 9 หัวข้อหลัก'] },
      { title: '1-3', body: ['Why · Business Model · Income'] },
      { title: '4-6', body: ['Products · Compensation · System'] },
      { title: '7-9', body: ['Support · Goals · Action plan'] },
    ],
  },
};

// Default fallback template for any slide row that doesn't have a custom
// definition yet — gives the user a usable starter deck with the right title.
function defaultTemplateFor(s) {
  return {
    title: s.title,
    slides: [
      { title: s.title, body: ['ใส่เนื้อหาที่นี่...'] },
      ...Array.from({ length: Math.max(1, (s.pages || 1) - 1) }, (_, i) => ({
        title: `${s.title} · slide ${i + 2}`,
        body: ['bullet 1', 'bullet 2', 'bullet 3'],
      })),
    ],
  };
}

function EsSlidesTab() {
  const [group, setGroup] = useState('all');
  const [connected, setConnected] = useState(() => !!(window.gSlides?.isConnected?.()));
  const [profile, setProfile] = useState(() => window.gSlides?.profile?.() || null);
  const [busyId, setBusyId] = useState(null);
  const [toast, setToast] = useState(null); // { ok, msg, url? }
  const groups = ['all', ...new Set(SLIDES.map(s => s.group))];
  const list = group === 'all' ? SLIDES : SLIDES.filter(s => s.group === group);
  const configured = !!(window.gSlides?.isConfigured?.());

  const handleConnect = async () => {
    try {
      const r = await window.gSlides.connect();
      setConnected(true);
      setProfile(r.profile || window.gSlides.profile());
      setToast({ ok: true, msg: `เชื่อม Google เรียบร้อย · ${r.profile?.email || ''}` });
      setTimeout(() => setToast(null), 2500);
    } catch (e) {
      setToast({ ok: false, msg: e.message || 'เชื่อม Google ไม่สำเร็จ' });
    }
  };
  const handleDisconnect = () => {
    window.gSlides.disconnect();
    setConnected(false);
    setProfile(null);
  };

  const handleCreate = async (s) => {
    if (!connected) {
      try { await handleConnect(); } catch {}
      if (!window.gSlides.isConnected()) return;
    }
    setBusyId(s.id);
    setToast(null);
    try {
      const tmpl = SLIDE_TEMPLATES[s.id] || defaultTemplateFor(s);
      const r = await window.gSlides.createFromTemplate(tmpl);
      setToast({ ok: true, msg: 'สร้าง Google Slides เรียบร้อย', url: r.url });
      window.open(r.url, '_blank');
    } catch (e) {
      setToast({ ok: false, msg: e.message || 'สร้างไม่สำเร็จ' });
    } finally {
      setBusyId(null);
    }
  };

  return (
    <div className="space-y-4">
      {/* Google connection banner */}
      <div className="rounded-xl border-2 p-3 flex items-center gap-3 flex-wrap"
           style={connected
             ? { borderColor: '#10B98140', background: '#E7F8F140' }
             : { borderColor: '#F59E0B40', background: '#FFF6E040' }}>
        <div className="w-10 h-10 rounded-lg flex items-center justify-center text-white flex-shrink-0"
             style={{ background: connected ? '#10B981' : '#F59E0B' }}>
          <svg viewBox="0 0 24 24" fill="currentColor" className="w-5 h-5">
            <path d="M3 6h4l9 12h4L11 6H7L3 18h4l1.5-2h8l-1-2H10l3-4 5 6h-3l-1-2h-2l1 2H3z"/>
          </svg>
        </div>
        <div className="flex-1 min-w-0">
          {!configured ? (
            <>
              <div className="text-sm font-semibold text-ink-900">⚙️ Google Client ID ยังไม่ได้ตั้งค่า</div>
              <div className="text-[11px] text-ink-600 mt-0.5 leading-relaxed">
                ตั้งค่า OAuth Client ID ใน <code className="bg-white px-1 rounded">lib/config.jsx</code> ก่อนถึงจะใช้ได้
                · ดูคู่มือใน comment ของไฟล์
              </div>
            </>
          ) : connected ? (
            <>
              <div className="text-sm font-semibold text-emerald-700">✓ เชื่อม Google เรียบร้อย</div>
              <div className="text-[11px] text-ink-600 mt-0.5">
                {profile?.email || 'Google account'} · สร้าง slide ได้ทันที (เก็บใน Drive)
              </div>
            </>
          ) : (
            <>
              <div className="text-sm font-semibold text-ink-900">ยังไม่ได้เชื่อม Google</div>
              <div className="text-[11px] text-ink-600 mt-0.5">
                เชื่อมก่อน 1 ครั้ง → สร้าง template ลง Google Slides ของคุณได้เลย
              </div>
            </>
          )}
        </div>
        {configured && (connected ? (
          <Btn variant="ghost" size="sm" onClick={handleDisconnect}>ตัดการเชื่อม</Btn>
        ) : (
          <Btn variant="brand" size="sm" onClick={handleConnect}
               icon={<Icon name="line" className="w-3.5 h-3.5 rotate-90" />}>
            เชื่อม Google
          </Btn>
        ))}
      </div>

      {toast && (
        <div className={`rounded-lg p-2.5 text-[12px] flex items-center gap-2 ${toast.ok ? 'bg-emerald-50 border border-emerald-200 text-emerald-800' : 'bg-rose-50 border border-rose-200 text-rose-700'}`}>
          <span>{toast.ok ? '✓' : '✗'}</span>
          <span className="flex-1">{toast.msg}</span>
          {toast.url && (
            <a href={toast.url} target="_blank" rel="noopener noreferrer"
               className="text-emerald-700 font-semibold underline">เปิด ↗</a>
          )}
        </div>
      )}

      <div className="flex flex-wrap items-center gap-1.5">
        {groups.map(g => (
          <button key={g} onClick={() => setGroup(g)}
            className={`text-xs font-medium px-3 py-1.5 rounded-lg transition-all ${group === g ? 'bg-ink-900 text-white' : 'bg-white border border-ink-200 text-ink-600 hover:bg-ink-50'}`}>
            {g === 'all' ? 'ทั้งหมด' : g}
          </button>
        ))}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">
        {list.map(s => {
          const isBusy = busyId === s.id;
          const hasCustomTmpl = !!SLIDE_TEMPLATES[s.id];
          return (
            <Card key={s.id} pad={false} className="hover:shadow-lift transition-all overflow-hidden">
              <div className="aspect-[4/3] bg-gradient-to-br from-ink-50 to-brand-50 flex items-center justify-center text-5xl">
                {s.thumb}
              </div>
              <div className="p-4">
                <div className="flex items-center gap-2 mb-1">
                  <Pill color="#1B379F" tint="#EEF4FF" size="xs">{s.group}</Pill>
                  <span className="text-[10px] text-ink-400 num">{s.pages} pages</span>
                  {hasCustomTmpl && <Pill color="#10B981" tint="#E7F8F1" size="xs">✓ template พร้อม</Pill>}
                </div>
                <div className="text-sm font-semibold text-ink-900 mb-3">{s.title}</div>
                <Btn
                  variant={connected ? 'brand' : 'ghost'}
                  size="sm"
                  disabled={!configured || isBusy}
                  onClick={() => handleCreate(s)}
                  icon={<svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="currentColor"><path d="M6 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6H6zm7 1.5L18.5 9H13V3.5z"/></svg>}>
                  {isBusy ? 'กำลังสร้าง...' : (connected ? 'สร้างใน Google Slides' : 'เชื่อม Google ก่อน')}
                </Btn>
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

window.EmphasisSystemView = EmphasisSystemView;
