// Admin panel — dashboard, lotteries, users, dreams, templates, predictions

window.AdminPanel = function AdminPanel() {
  const { user, go, adminSection, setAdminSection, logout } = useApp();
  const nav = [
    { id: 'dashboard',   label: 'Dashboard',     icon: '📊' },
    { id: 'lotteries',   label: 'จัดการหวย',      icon: '🎰' },
    { id: 'users',       label: 'ผู้ใช้งาน',       icon: '👥' },
    { id: 'dreams',      label: 'ทำนายฝัน',       icon: '🌙' },
    { id: 'predictions', label: 'Top 5 งวดนี้',    icon: '🏆' },
    { id: 'templates',   label: 'Template',       icon: '📝' },
  ];
  return (
    <div style={{
      width: '100%', height: '100%', minHeight: 780,
      background: '#F7F4EE', display: 'flex',
      fontFamily: "'Noto Sans Thai', sans-serif",
      borderRadius: 18, overflow: 'hidden', border: '1px solid #E5DFD1',
      boxShadow: '0 12px 30px rgba(0,0,0,0.08)',
    }}>
      {/* sidebar */}
      <div style={{
        width: 230, background: '#1A1814', color: '#E8E3D6',
        display: 'flex', flexDirection: 'column', padding: '20px 14px',
      }}>
        <div style={{ padding: '0 8px 20px', borderBottom: '1px solid #3A3630' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: 'linear-gradient(135deg, #B91C1C, #8B1010)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#fff', fontWeight: 800, fontSize: 18,
            }}>฿</div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 800 }}>สุ่มเลข</div>
              <div style={{ fontSize: 10, opacity: 0.6 }}>Admin Panel</div>
            </div>
          </div>
        </div>
        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 2 }}>
          {nav.map(n => {
            const active = adminSection === n.id;
            return (
              <button key={n.id} onClick={() => setAdminSection(n.id)} style={{
                padding: '10px 12px', borderRadius: 9, border: 0, cursor: 'pointer',
                background: active ? '#B91C1C' : 'transparent',
                color: active ? '#fff' : '#C4BEB0',
                fontSize: 13, fontWeight: active ? 700 : 500, fontFamily: 'inherit',
                display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left',
              }}>
                <span style={{ fontSize: 15 }}>{n.icon}</span>
                <span>{n.label}</span>
              </button>
            );
          })}
        </div>
        <div style={{ marginTop: 'auto', padding: 8, borderTop: '1px solid #3A3630' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 4px' }}>
            <div style={{ width: 32, height: 32, borderRadius: 999, background: '#B91C1C', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13 }}>{user?.name?.[0] || 'A'}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user?.name}</div>
              <div style={{ fontSize: 10, opacity: 0.6 }}>ผู้ดูแล</div>
            </div>
          </div>
          <button onClick={() => go('home')} style={{
            width: '100%', padding: 8, marginTop: 4, borderRadius: 8,
            border: '1px solid #3A3630', background: 'transparent', color: '#C4BEB0',
            fontSize: 11, cursor: 'pointer', fontFamily: 'inherit',
          }}>← กลับไปแอป</button>
        </div>
      </div>

      {/* content */}
      <div style={{ flex: 1, overflow: 'auto', padding: 24 }}>
        {adminSection === 'dashboard' && <AdminDashboard />}
        {adminSection === 'lotteries' && <AdminLotteries />}
        {adminSection === 'users' && <AdminUsers />}
        {adminSection === 'dreams' && <AdminDreams />}
        {adminSection === 'predictions' && <AdminPredictions />}
        {adminSection === 'templates' && <AdminTemplates />}
      </div>
    </div>
  );
};

function AdminHeader({ title, sub, action }) {
  return (
    <div style={{ marginBottom: 20, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16 }}>
      <div>
        <div style={{ fontSize: 22, fontWeight: 800, color: '#1A1A1A' }}>{title}</div>
        {sub && <div style={{ fontSize: 13, color: '#8C8678', marginTop: 3 }}>{sub}</div>}
      </div>
      {action}
    </div>
  );
}

function AdminCard({ children, style = {} }) {
  return (
    <div style={{
      background: '#fff', borderRadius: 14, border: '1px solid #EDE7DC',
      boxShadow: '0 2px 6px rgba(90,85,70,0.04)', ...style,
    }}>{children}</div>
  );
}

function AdminDashboard() {
  const { setAdminSection } = useApp();
  const stats = [
    { label: 'Users ที่ active', value: '347', chg: '+12 วันนี้', color: '#16A34A' },
    { label: 'หวยที่เปิดอยู่', value: '7', chg: '1 ปิดใช้งาน', color: '#B91C1C' },
    { label: 'งวดใกล้ปิด', value: '3', chg: 'ใน 2 ชม.', color: '#D97706' },
    { label: 'Dreams analyzed (30d)', value: '1,284', chg: '+8%', color: '#7C3AED' },
  ];
  return (
    <>
      <AdminHeader title="ภาพรวม" sub="ข้อมูลอัปเดต 19 เม.ย. 2569 9:41 น." />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
        {stats.map(s => (
          <AdminCard key={s.label} style={{ padding: 18 }}>
            <div style={{ fontSize: 12, color: '#8C8678', fontWeight: 600 }}>{s.label}</div>
            <div style={{ fontSize: 30, fontWeight: 800, color: '#1A1A1A', marginTop: 4 }}>{s.value}</div>
            <div style={{ fontSize: 11, color: s.color, marginTop: 4, fontWeight: 600 }}>● {s.chg}</div>
          </AdminCard>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 14 }}>
        <AdminCard style={{ padding: 18 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#1A1A1A', marginBottom: 14 }}>งวดที่กำลังจะปิด</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {MOCK_LOTTERIES.slice(0,5).map(l => (
              <div key={l.slug} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: '#FAF7F2', borderRadius: 10 }}>
                <div style={{ fontSize: 20 }}>{l.flag}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700 }}>{l.name}</div>
                  <div style={{ fontSize: 11, color: '#8C8678' }}>{l.cadence}</div>
                </div>
                <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 13, fontWeight: 700, color: '#B91C1C' }}>ปิด {l.close}</div>
              </div>
            ))}
          </div>
        </AdminCard>
        <AdminCard style={{ padding: 18 }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#1A1A1A', marginBottom: 14 }}>Quick actions</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <QuickAction icon="➕" label="เพิ่ม User ใหม่" onClick={() => setAdminSection('users')} />
            <QuickAction icon="🔁" label="สุ่ม Top 5 ใหม่" onClick={() => setAdminSection('predictions')} />
            <QuickAction icon="📥" label="Import dreams CSV" onClick={() => setAdminSection('dreams')} />
            <QuickAction icon="🔒" label="Lock user" onClick={() => setAdminSection('users')} />
          </div>
        </AdminCard>
      </div>
    </>
  );
}

function QuickAction({ icon, label, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: '10px 12px', borderRadius: 10, border: '1px solid #EDE7DC',
      background: '#fff', cursor: 'pointer', fontFamily: 'inherit',
      display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, color: '#1A1A1A', fontWeight: 500,
    }}>
      <span>{icon}</span>{label}
    </button>
  );
}

function AdminLotteries() {
  const [editing, setEditing] = useState(null);
  const [toggles, setToggles] = useState(() => Object.fromEntries(MOCK_LOTTERIES.map(l => [l.slug, { active: l.active, ai: l.aiEnabled }])));
  const toggle = (slug, key) => setToggles(p => ({ ...p, [slug]: { ...p[slug], [key]: !p[slug][key] } }));
  const blankLot = { slug: '', name: 'หวยใหม่', flag: '🎫', group: 'ในประเทศ', color: '#B91C1C', close: '21:00', cadence: 'รายวัน', active: true, aiEnabled: true };
  return (
    <>
      <AdminHeader title="จัดการประเภทหวย" sub={`${MOCK_LOTTERIES.length} รายการ`} action={<AdminBtn onClick={() => setEditing(blankLot)}>+ เพิ่มประเภทหวย</AdminBtn>} />
      <AdminCard>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#FAF7F2', color: '#5A5546' }}>
              <Th>ชื่อ</Th><Th>กลุ่ม</Th><Th>เปิด-ปิดรับ</Th><Th>ตาราง</Th><Th>Active</Th><Th>AI</Th><Th></Th>
            </tr>
          </thead>
          <tbody>
            {MOCK_LOTTERIES.map(l => (
              <tr key={l.slug} style={{ borderTop: '1px solid #F0EBE0' }}>
                <Td><div style={{ display:'flex', alignItems:'center', gap: 10 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 8, background: `${l.color}22`, display:'flex', alignItems:'center', justifyContent:'center' }}>{l.flag}</div>
                  <div>
                    <div style={{ fontWeight: 700, color: '#1A1A1A' }}>{l.name}</div>
                    <div style={{ fontSize: 10, color: '#8C8678' }}>/{l.slug}</div>
                  </div>
                </div></Td>
                <Td>{l.group}</Td>
                <Td><span style={{ fontFamily: 'ui-monospace, monospace' }}>09:00 → {l.close}</span></Td>
                <Td>{l.cadence}</Td>
                <Td><MiniToggle on={toggles[l.slug].active} onClick={() => toggle(l.slug, 'active')} /></Td>
                <Td><MiniToggle on={toggles[l.slug].ai} onClick={() => toggle(l.slug, 'ai')} /></Td>
                <Td><button onClick={() => setEditing(l)} style={linkBtn}>แก้ไข</button></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </AdminCard>
      {editing && <EditLotteryModal lot={editing} onClose={() => setEditing(null)} />}
    </>
  );
}

function EditLotteryModal({ lot, onClose }) {
  const [cadence, setCadence] = useState('daily');
  const days = ['จ','อ','พ','พฤ','ศ','ส','อา'];
  const [selected, setSelected] = useState({ จ: true, พ: true, ศ: true });
  const [image, setImage] = useState(null);
  const [categories, setCategories] = useState(['ในประเทศ', 'ต่างประเทศ', 'หวยหุ้น', 'หวยรายชั่วโมง']);
  const [category, setCategory] = useState(lot.group);
  const [addingCat, setAddingCat] = useState(false);
  const [newCat, setNewCat] = useState('');
  const fileRef = React.useRef();

  const onPickFile = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = () => setImage(reader.result);
    reader.readAsDataURL(f);
  };
  const addCategory = () => {
    if (newCat.trim() && !categories.includes(newCat.trim())) {
      setCategories([...categories, newCat.trim()]);
      setCategory(newCat.trim());
    }
    setNewCat(''); setAddingCat(false);
  };

  return (
    <Modal onClose={onClose} title={`แก้ไข: ${lot.name}`}>
      {/* Image upload — full width at top */}
      <Field label="รูปธง / ไอคอนประจำ (แสดงในหน้าการ์ด)">
        <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
          <div style={{
            width: 88, height: 88, borderRadius: 14,
            background: image ? `url(${image}) center/cover` : `${lot.color}18`,
            border: '1.5px dashed #D4CCB8',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 42, flexShrink: 0, overflow: 'hidden',
          }}>
            {!image && lot.flag}
          </div>
          <div style={{ flex: 1 }}>
            <input ref={fileRef} type="file" accept="image/*" onChange={onPickFile} style={{ display: 'none' }} />
            <button onClick={() => fileRef.current?.click()} style={{
              padding: '9px 16px', borderRadius: 9, border: '1.5px solid #B91C1C',
              background: '#fff', color: '#B91C1C', fontSize: 13, fontWeight: 700,
              cursor: 'pointer', fontFamily: 'inherit',
            }}>📤 อัปโหลดรูป</button>
            {image && (
              <button onClick={() => setImage(null)} style={{
                marginLeft: 8, padding: '9px 14px', borderRadius: 9,
                border: '1px solid #E5DFD1', background: '#fff', color: '#8C8678',
                fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
              }}>ลบรูป</button>
            )}
            <div style={{ fontSize: 11, color: '#8C8678', marginTop: 6 }}>
              รองรับ PNG, JPG, SVG — แนะนำสี่เหลี่ยมจัตุรัส 256×256 px
            </div>
          </div>
        </div>
      </Field>

      <Field label="ชื่อ" style={{ marginTop: 14 }}><Input defaultValue={lot.name} /></Field>

      <Field label="หมวดหมู่" style={{ marginTop: 14 }}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
          {categories.map(c => (
            <button key={c} onClick={() => setCategory(c)} style={{
              padding: '7px 14px', borderRadius: 999,
              border: `1.5px solid ${category === c ? '#B91C1C' : '#E5DFD1'}`,
              background: category === c ? '#FEF2F2' : '#fff',
              color: category === c ? '#B91C1C' : '#5A5546',
              fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            }}>{c}</button>
          ))}
          {!addingCat ? (
            <button onClick={() => setAddingCat(true)} style={{
              padding: '7px 14px', borderRadius: 999,
              border: '1.5px dashed #D4CCB8', background: '#fff', color: '#8C8678',
              fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            }}>+ เพิ่มหมวดหมู่</button>
          ) : (
            <div style={{ display: 'flex', gap: 4 }}>
              <Input autoFocus value={newCat} onChange={e => setNewCat(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter') addCategory(); if (e.key === 'Escape') { setAddingCat(false); setNewCat(''); } }}
                placeholder="ชื่อหมวด" style={{ width: 140 }} />
              <button onClick={addCategory} style={{
                padding: '7px 12px', borderRadius: 8, border: 0,
                background: '#B91C1C', color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
              }}>เพิ่ม</button>
            </div>
          )}
        </div>
      </Field>

      <Field label="ประเภทตาราง" style={{ marginTop: 14 }}>
        <div style={{ display: 'flex', gap: 8 }}>
          {[['daily','รายวัน'], ['weekly','รายสัปดาห์'], ['monthly','รายเดือน']].map(([v,l]) => (
            <button key={v} onClick={() => setCadence(v)} style={{
              padding: '8px 14px', borderRadius: 8,
              border: `1.5px solid ${cadence === v ? '#B91C1C' : '#E5DFD1'}`,
              background: cadence === v ? '#FEF2F2' : '#fff',
              color: cadence === v ? '#B91C1C' : '#5A5546',
              fontWeight: 600, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
            }}>{l}</button>
          ))}
        </div>
      </Field>

      {cadence !== 'monthly' ? (
        <Field label="วัน" style={{ marginTop: 10 }}>
          <div style={{ display: 'flex', gap: 6 }}>
            {days.map(d => (
              <button key={d} onClick={() => setSelected(s => ({ ...s, [d]: !s[d] }))} style={{
                width: 40, height: 40, borderRadius: 8,
                border: `1.5px solid ${selected[d] ? '#B91C1C' : '#E5DFD1'}`,
                background: selected[d] ? '#B91C1C' : '#fff',
                color: selected[d] ? '#fff' : '#5A5546',
                fontWeight: 600, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
              }}>{d}</button>
            ))}
          </div>
        </Field>
      ) : (
        <Field label="วันที่ของเดือน" style={{ marginTop: 10 }}>
          <Input defaultValue="1, 16" placeholder="เช่น 1, 16" />
        </Field>
      )}

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginTop: 14 }}>
        <Field label="เปิดรับ"><Input defaultValue="09:00" /></Field>
        <Field label="ปิดรับ"><Input defaultValue={lot.close} /></Field>
        <Field label="เวลาออกผล / รีเซ็ต"><Input defaultValue="21:00" /></Field>
      </div>

      <div style={{ display: 'flex', gap: 18, marginTop: 18, padding: '14px 0', borderTop: '1px solid #F0EBE0' }}>
        <ToggleRow label="เปิดใช้งาน" defaultOn={lot.active} />
        <ToggleRow label="เปิดการวิเคราะห์ AI" defaultOn={lot.aiEnabled} />
      </div>

      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 14 }}>
        <AdminBtn variant="ghost" onClick={onClose}>ยกเลิก</AdminBtn>
        <AdminBtn onClick={onClose}>บันทึก</AdminBtn>
      </div>
    </Modal>
  );
}

function AdminUsers() {
  const [filter, setFilter] = useState('all');
  const [q, setQ] = useState('');
  const [editing, setEditing] = useState(null);
  const [users, setUsers] = useState(MOCK_USERS);
  const blank = { phone: '', name: '', created: '—', lastLogin: '—', status: 'active', admin: false, _new: true };
  const filtered = users.filter(u =>
    (filter === 'all' || (filter === 'active' && u.status === 'active') || (filter === 'locked' && u.status === 'locked') || (filter === 'admin' && u.admin)) &&
    (u.phone.includes(q) || u.name.includes(q))
  );
  const toggleLock = (phone) => setUsers(us => us.map(u => u.phone === phone ? { ...u, status: u.status === 'locked' ? 'active' : 'locked' } : u));
  const saveUser = (u) => setUsers(us => u._new ? [{ ...u, _new: false }, ...us] : us.map(x => x.phone === u.phone ? u : x));
  return (
    <>
      <AdminHeader title="จัดการ Users" sub={`${users.length} คน`} action={<AdminBtn onClick={() => setEditing(blank)}>+ เพิ่ม User</AdminBtn>} />
      <AdminCard style={{ padding: 14, marginBottom: 14, display: 'flex', gap: 10, alignItems: 'center' }}>
        <Input placeholder="ค้นหาเบอร์หรือชื่อ..." value={q} onChange={e => setQ(e.target.value)} style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 4, background: '#FAF7F2', padding: 3, borderRadius: 8 }}>
          {[['all','ทั้งหมด'],['active','Active'],['locked','Locked'],['admin','Admin']].map(([v,l]) => (
            <button key={v} onClick={() => setFilter(v)} style={{
              padding: '6px 12px', borderRadius: 6, border: 0,
              background: filter === v ? '#fff' : 'transparent',
              color: filter === v ? '#B91C1C' : '#5A5546',
              fontWeight: 600, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
              boxShadow: filter === v ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
            }}>{l}</button>
          ))}
        </div>
      </AdminCard>
      <AdminCard>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#FAF7F2', color: '#5A5546' }}>
              <Th>เบอร์โทร</Th><Th>ชื่อ</Th><Th>สร้างเมื่อ</Th><Th>Login ล่าสุด</Th><Th>สถานะ</Th><Th></Th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(u => (
              <tr key={u.phone} style={{ borderTop: '1px solid #F0EBE0' }}>
                <Td><span style={{ fontFamily: 'ui-monospace, monospace', fontWeight: 600 }}>{u.phone}</span></Td>
                <Td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ width: 28, height: 28, borderRadius: 999, background: '#B91C1C22', color: '#B91C1C', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 800 }}>{u.name[0]}</div>
                    <span>{u.name}</span>
                    {u.admin && <Badge>Admin</Badge>}
                  </div>
                </Td>
                <Td style={{ color: '#8C8678' }}>{u.created}</Td>
                <Td style={{ color: '#8C8678' }}>{u.lastLogin}</Td>
                <Td>{u.status === 'active' ? <Badge variant="green">Active</Badge> : <Badge variant="gray">Locked</Badge>}</Td>
                <Td style={{ textAlign: 'right' }}>
                  <button onClick={() => setEditing(u)} style={linkBtn}>แก้ไข</button>
                  <span style={{ color: '#E5DFD1', margin: '0 6px' }}>·</span>
                  <button onClick={() => toggleLock(u.phone)} style={{ ...linkBtn, color: '#B91C1C' }}>{u.status === 'locked' ? 'Unlock' : 'Lock'}</button>
                </Td>
              </tr>
            ))}
          </tbody>
        </table>
      </AdminCard>
      {editing && <EditUserModal user={editing} onClose={() => setEditing(null)} onSave={(u) => { saveUser(u); setEditing(null); }} />}
    </>
  );
}

function EditUserModal({ user, onClose, onSave }) {
  const [u, setU] = useState(user);
  return (
    <Modal title={u._new ? 'เพิ่ม User ใหม่' : `แก้ไข: ${u.name}`} onClose={onClose}>
      <Field label="เบอร์โทร"><Input value={u.phone} onChange={e => setU({ ...u, phone: e.target.value })} placeholder="0xx-xxx-xxxx" /></Field>
      <Field label="ชื่อแสดง" style={{ marginTop: 12 }}><Input value={u.name} onChange={e => setU({ ...u, name: e.target.value })} /></Field>
      <div style={{ display: 'flex', gap: 18, marginTop: 18, padding: '14px 0', borderTop: '1px solid #F0EBE0' }}>
        <ToggleRow label="เป็น Admin" defaultOn={u.admin} />
        <ToggleRow label="Active" defaultOn={u.status === 'active'} />
      </div>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 14 }}>
        <AdminBtn variant="ghost" onClick={onClose}>ยกเลิก</AdminBtn>
        <AdminBtn onClick={() => onSave(u)}>บันทึก</AdminBtn>
      </div>
    </Modal>
  );
}

function AdminDreams() {
  const [q, setQ] = useState('');
  const [editing, setEditing] = useState(null);
  const [importing, setImporting] = useState(false);
  const [dreams, setDreams] = useState(MOCK_ADMIN_DREAMS);
  const filtered = dreams.filter(d => d.keyword.includes(q) || d.category.includes(q));
  const blank = { id: Date.now(), keyword: '', category: 'สัตว์', nums2: [], nums3: [], meaning: '', priority: 50, active: true, _new: true };
  const save = (d) => { setDreams(ds => d._new ? [{ ...d, _new: false }, ...ds] : ds.map(x => x.id === d.id ? d : x)); setEditing(null); };
  return (
    <>
      <AdminHeader title="จัดการคำทำนายฝัน" sub={`${dreams.length} คำ`} action={
        <div style={{ display: 'flex', gap: 8 }}>
          <AdminBtn variant="ghost" onClick={() => setImporting(true)}>📥 Import CSV</AdminBtn>
          <AdminBtn onClick={() => setEditing(blank)}>+ เพิ่มคำ</AdminBtn>
        </div>
      } />
      <AdminCard style={{ padding: 14, marginBottom: 14 }}>
        <Input placeholder="ค้นหา keyword / category..." value={q} onChange={e => setQ(e.target.value)} />
      </AdminCard>
      <AdminCard>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#FAF7F2', color: '#5A5546' }}>
              <Th>Keyword</Th><Th>หมวด</Th><Th>2 ตัว</Th><Th>3 ตัว</Th><Th>Priority</Th><Th>Active</Th><Th></Th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(d => (
              <tr key={d.id} style={{ borderTop: '1px solid #F0EBE0' }}>
                <Td><span style={{ fontSize: 15, fontWeight: 700 }}>{d.keyword}</span></Td>
                <Td><Badge variant="gray">{d.category}</Badge></Td>
                <Td><div style={{ display: 'flex', gap: 4 }}>{d.nums2.map(n => <Chip key={n}>{n}</Chip>)}</div></Td>
                <Td><div style={{ display: 'flex', gap: 4 }}>{d.nums3.map(n => <Chip key={n}>{n}</Chip>)}</div></Td>
                <Td><div style={{ width: 60, height: 6, borderRadius: 3, background: '#EDE7DC', position: 'relative' }}>
                  <div style={{ position: 'absolute', inset: 0, width: `${d.priority}%`, background: '#B91C1C', borderRadius: 3 }} />
                </div></Td>
                <Td><MiniToggle on={d.active} /></Td>
                <Td style={{ textAlign: 'right' }}><button onClick={() => setEditing(d)} style={linkBtn}>แก้ไข</button></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </AdminCard>
      {editing && <EditDreamModal dream={editing} onClose={() => setEditing(null)} onSave={save} />}
      {importing && <ImportCSVModal onClose={() => setImporting(false)} />}
    </>
  );
}

function EditDreamModal({ dream, onClose, onSave }) {
  const [d, setD] = useState(dream);
  const cats = ['สัตว์', 'คน', 'ของ', 'สถานที่', 'กิจกรรม', 'อื่นๆ'];
  return (
    <Modal title={d._new ? 'เพิ่มคำทำนายฝัน' : `แก้ไข: ${d.keyword}`} onClose={onClose}>
      <Field label="Keyword"><Input value={d.keyword} onChange={e => setD({ ...d, keyword: e.target.value })} /></Field>
      <Field label="หมวด" style={{ marginTop: 12 }}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {cats.map(c => (
            <button key={c} onClick={() => setD({ ...d, category: c })} style={{
              padding: '7px 14px', borderRadius: 999,
              border: `1.5px solid ${d.category === c ? '#B91C1C' : '#E5DFD1'}`,
              background: d.category === c ? '#FEF2F2' : '#fff',
              color: d.category === c ? '#B91C1C' : '#5A5546',
              fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            }}>{c}</button>
          ))}
        </div>
      </Field>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 12 }}>
        <Field label="เลข 2 ตัว (คั่น , )"><Input value={d.nums2.join(', ')} onChange={e => setD({ ...d, nums2: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })} placeholder="23, 89" /></Field>
        <Field label="เลข 3 ตัว (คั่น , )"><Input value={d.nums3.join(', ')} onChange={e => setD({ ...d, nums3: e.target.value.split(',').map(s => s.trim()).filter(Boolean) })} placeholder="230, 897" /></Field>
      </div>
      <Field label="ความหมาย" style={{ marginTop: 12 }}>
        <textarea value={d.meaning} onChange={e => setD({ ...d, meaning: e.target.value })} rows={3} style={{ width: '100%', padding: 10, borderRadius: 8, border: '1.5px solid #E5DFD1', fontFamily: 'inherit', fontSize: 13, boxSizing: 'border-box', outline: 'none', resize: 'vertical' }} />
      </Field>
      <Field label={`Priority: ${d.priority}`} style={{ marginTop: 12 }}>
        <input type="range" min="0" max="100" value={d.priority} onChange={e => setD({ ...d, priority: +e.target.value })} style={{ width: '100%' }} />
      </Field>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 14, paddingTop: 14, borderTop: '1px solid #F0EBE0' }}>
        <AdminBtn variant="ghost" onClick={onClose}>ยกเลิก</AdminBtn>
        <AdminBtn onClick={() => onSave(d)}>บันทึก</AdminBtn>
      </div>
    </Modal>
  );
}

function ImportCSVModal({ onClose }) {
  const [step, setStep] = useState('upload');
  return (
    <Modal title="Import dreams CSV" onClose={onClose}>
      {step === 'upload' ? (
        <div style={{ padding: 32, border: '2px dashed #D4CCB8', borderRadius: 12, textAlign: 'center', background: '#FAF7F2' }}>
          <div style={{ fontSize: 42 }}>📄</div>
          <div style={{ fontSize: 14, fontWeight: 700, marginTop: 8 }}>ลากไฟล์ CSV มาวางที่นี่</div>
          <div style={{ fontSize: 12, color: '#8C8678', marginTop: 4 }}>คอลัมน์: keyword, category, nums2, nums3, meaning, priority</div>
          <button onClick={() => setStep('preview')} style={{
            marginTop: 14, padding: '9px 18px', borderRadius: 9, border: 0,
            background: '#B91C1C', color: '#fff', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
          }}>เลือกไฟล์ตัวอย่าง</button>
        </div>
      ) : (
        <div>
          <div style={{ fontSize: 13, color: '#5A5546', marginBottom: 10 }}>พบ 3 คำใหม่ ทับซ้อน 2 คำ — ตรวจก่อนยืนยัน</div>
          <div style={{ background: '#FAF7F2', borderRadius: 10, padding: 14, fontFamily: 'ui-monospace, monospace', fontSize: 12, lineHeight: 1.8 }}>
            <div>+ แมว → สัตว์ → 24, 48</div>
            <div>+ เสือ → สัตว์ → 15, 51</div>
            <div>+ พระ → คน → 89, 98</div>
            <div style={{ color: '#C9A961' }}>⚠️ นก → ซ้ำกับของเดิม (ข้าม)</div>
            <div style={{ color: '#C9A961' }}>⚠️ ปลา → ซ้ำกับของเดิม (ข้าม)</div>
          </div>
          <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 14 }}>
            <AdminBtn variant="ghost" onClick={onClose}>ยกเลิก</AdminBtn>
            <AdminBtn onClick={onClose}>นำเข้า 3 คำ</AdminBtn>
          </div>
        </div>
      )}
    </Modal>
  );
}

function AdminPredictions() {
  const [lottery, setLottery] = useState('gov-th');
  const [data, setData] = useState(MOCK_TOP5);
  const [editing, setEditing] = useState(null);
  const [toast, setToast] = useState('');
  const items = data[lottery] || [];
  const shuffle = () => {
    setData(d => ({ ...d, [lottery]: (d[lottery] || []).map(t => ({ ...t, num: String(Math.floor(Math.random() * (t.num.length === 3 ? 1000 : 100))).padStart(t.num.length, '0'), confidence: Math.floor(50 + Math.random() * 40) })) }));
    setToast('สุ่มใหม่แล้ว ✓'); setTimeout(() => setToast(''), 1600);
  };
  const save = (t) => { setData(d => ({ ...d, [lottery]: d[lottery].map(x => x.rank === t.rank ? { ...t, edited: true } : x) })); setEditing(null); };
  return (
    <>
      <AdminHeader title="จัดการ Top 5 งวดนี้" sub="แก้ไข/สุ่มใหม่ได้ ก่อนปิดรับ" action={<AdminBtn onClick={shuffle}>🔁 สุ่มใหม่ทั้งหมด</AdminBtn>} />
      <AdminCard style={{ padding: 14, marginBottom: 14, display: 'flex', gap: 10, alignItems: 'center' }}>
        <div style={{ fontSize: 13, color: '#5A5546', fontWeight: 600 }}>หวย:</div>
        <Select options={MOCK_LOTTERIES.map(l => l.name)} value={MOCK_LOTTERIES.find(l => l.slug === lottery)?.name} onChange={e => {
          const l = MOCK_LOTTERIES.find(l => l.name === e.target.value);
          if (l) setLottery(l.slug);
        }} style={{ minWidth: 200 }} />
        <div style={{ marginLeft: 'auto', fontSize: 12, color: '#8C8678' }}>งวด: 1 เม.ย. 2569</div>
      </AdminCard>
      <AdminCard>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#FAF7F2', color: '#5A5546' }}>
              <Th>อันดับ</Th><Th>เลข</Th><Th>ประเภท</Th><Th>%</Th><Th>คำอธิบาย</Th><Th>Admin edit</Th><Th></Th>
            </tr>
          </thead>
          <tbody>
            {items.map(t => (
              <tr key={t.rank} style={{ borderTop: '1px solid #F0EBE0' }}>
                <Td><div style={{ width: 28, height: 28, borderRadius: 999, background: t.rank <= 3 ? '#C9A961' : '#E5DFD1', color: t.rank <= 3 ? '#fff' : '#5A5546', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 13 }}>{t.rank}</div></Td>
                <Td><span style={{ fontSize: 22, fontWeight: 800, color: '#B91C1C' }}>{t.num}</span></Td>
                <Td><Badge variant="gray">{t.type}</Badge></Td>
                <Td><span style={{ color: '#16A34A', fontWeight: 700 }}>{t.confidence}%</span></Td>
                <Td style={{ maxWidth: 280, color: '#5A5546' }}>{t.desc}</Td>
                <Td>{t.edited ? <Badge variant="red">edited</Badge> : t.rank === 1 ? <Badge variant="red">edited</Badge> : <span style={{ color: '#C4BEB0' }}>—</span>}</Td>
                <Td style={{ textAlign: 'right' }}><button onClick={() => setEditing(t)} style={linkBtn}>แก้ไข</button></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </AdminCard>
      {toast && <div style={{ position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)', background: '#1A1A1A', color: '#fff', padding: '10px 18px', borderRadius: 10, fontSize: 13, fontWeight: 600, zIndex: 200 }}>{toast}</div>}
      {editing && <EditPredictionModal item={editing} onClose={() => setEditing(null)} onSave={save} />}
    </>
  );
}

function EditPredictionModal({ item, onClose, onSave }) {
  const [t, setT] = useState(item);
  return (
    <Modal title={`แก้ไขอันดับ ${t.rank}`} onClose={onClose}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="เลข"><Input value={t.num} onChange={e => setT({ ...t, num: e.target.value })} /></Field>
        <Field label="ประเภท"><Select options={['2 ตัวท้าย','2 ตัวบน','3 ตัวท้าย','3 ตัวบน','วิ่งบน','วิ่งล่าง']} value={t.type} onChange={e => setT({ ...t, type: e.target.value })} /></Field>
      </div>
      <Field label={`ความมั่นใจ: ${t.confidence}%`} style={{ marginTop: 12 }}>
        <input type="range" min="0" max="100" value={t.confidence} onChange={e => setT({ ...t, confidence: +e.target.value })} style={{ width: '100%' }} />
      </Field>
      <Field label="คำอธิบาย" style={{ marginTop: 12 }}>
        <textarea value={t.desc} onChange={e => setT({ ...t, desc: e.target.value })} rows={3} style={{ width: '100%', padding: 10, borderRadius: 8, border: '1.5px solid #E5DFD1', fontFamily: 'inherit', fontSize: 13, boxSizing: 'border-box', outline: 'none', resize: 'vertical' }} />
      </Field>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 14, paddingTop: 14, borderTop: '1px solid #F0EBE0' }}>
        <AdminBtn variant="ghost" onClick={onClose}>ยกเลิก</AdminBtn>
        <AdminBtn onClick={() => onSave(t)}>บันทึก</AdminBtn>
      </div>
    </Modal>
  );
}

function AdminTemplates() {
  const [editing, setEditing] = useState(null);
  const [templates, setTemplates] = useState(MOCK_TEMPLATES);
  const blank = { id: Date.now(), text: '', applies: '2_digit', active: true, _new: true };
  const save = (t) => { setTemplates(ts => t._new ? [{ ...t, _new: false }, ...ts] : ts.map(x => x.id === t.id ? t : x)); setEditing(null); };
  return (
    <>
      <AdminHeader title="Template คำอธิบาย" sub="ใช้ render อธิบาย Top 5 อัตโนมัติ" action={<AdminBtn onClick={() => setEditing(blank)}>+ เพิ่ม Template</AdminBtn>} />
      <AdminCard>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr style={{ background: '#FAF7F2', color: '#5A5546' }}>
              <Th>Template</Th><Th>ใช้กับ</Th><Th>ตัวอย่าง</Th><Th>Active</Th><Th></Th>
            </tr>
          </thead>
          <tbody>
            {templates.map(t => (
              <tr key={t.id} style={{ borderTop: '1px solid #F0EBE0' }}>
                <Td><code style={{ fontFamily: 'ui-monospace, monospace', fontSize: 12, background: '#FAF7F2', padding: '3px 8px', borderRadius: 6 }}>{t.text}</code></Td>
                <Td><Badge variant="gray">{t.applies}</Badge></Td>
                <Td style={{ color: '#5A5546', maxWidth: 260 }}>{t.text.replace('{n}', '3').replace('{num}','23').replace('{period}','เดือนนี้').replace('{weeks}','12')}</Td>
                <Td><MiniToggle on={t.active} /></Td>
                <Td style={{ textAlign: 'right' }}><button onClick={() => setEditing(t)} style={linkBtn}>แก้ไข</button></Td>
              </tr>
            ))}
          </tbody>
        </table>
      </AdminCard>
      {editing && <EditTemplateModal tpl={editing} onClose={() => setEditing(null)} onSave={save} />}
    </>
  );
}

function EditTemplateModal({ tpl, onClose, onSave }) {
  const [t, setT] = useState(tpl);
  const preview = t.text.replace('{n}', '3').replace('{num}', '23').replace('{period}', 'เดือนนี้').replace('{weeks}', '12');
  return (
    <Modal title={t._new ? 'เพิ่ม Template' : 'แก้ไข Template'} onClose={onClose}>
      <Field label="Template (ตัวแปร: {n}, {num}, {period}, {weeks})">
        <textarea value={t.text} onChange={e => setT({ ...t, text: e.target.value })} rows={3} placeholder="เช่น: ออกซ้ำทุก {n} งวดในช่วง {period}" style={{ width: '100%', padding: 10, borderRadius: 8, border: '1.5px solid #E5DFD1', fontFamily: 'inherit', fontSize: 13, boxSizing: 'border-box', outline: 'none', resize: 'vertical' }} />
      </Field>
      <Field label="ใช้กับ" style={{ marginTop: 12 }}>
        <div style={{ display: 'flex', gap: 8 }}>
          {[['2_digit','2 ตัว'],['3_digit','3 ตัว'],['both','ทั้งสอง']].map(([v,l]) => (
            <button key={v} onClick={() => setT({ ...t, applies: v })} style={{
              padding: '8px 14px', borderRadius: 8,
              border: `1.5px solid ${t.applies === v ? '#B91C1C' : '#E5DFD1'}`,
              background: t.applies === v ? '#FEF2F2' : '#fff',
              color: t.applies === v ? '#B91C1C' : '#5A5546',
              fontWeight: 600, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
            }}>{l}</button>
          ))}
        </div>
      </Field>
      <Field label="ตัวอย่าง (แทนค่า)" style={{ marginTop: 12 }}>
        <div style={{ padding: 12, background: '#FAF7F2', borderRadius: 8, fontSize: 13, color: '#1A1A1A', minHeight: 40 }}>{preview || <span style={{ color: '#C4BEB0' }}>— พิมพ์ template ด้านบน —</span>}</div>
      </Field>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', marginTop: 14, paddingTop: 14, borderTop: '1px solid #F0EBE0' }}>
        <AdminBtn variant="ghost" onClick={onClose}>ยกเลิก</AdminBtn>
        <AdminBtn onClick={() => onSave(t)}>บันทึก</AdminBtn>
      </div>
    </Modal>
  );
}

// helpers
const Th = ({ children }) => <th style={{ textAlign: 'left', padding: '12px 16px', fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4 }}>{children}</th>;
const Td = ({ children, style }) => <td style={{ padding: '12px 16px', color: '#1A1A1A', verticalAlign: 'middle', ...style }}>{children}</td>;
const linkBtn = { border: 0, background: 'transparent', color: '#5A5546', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600 };
function AdminBtn({ children, variant = 'solid', onClick }) {
  return <button onClick={onClick} style={{
    padding: '9px 16px', borderRadius: 9,
    border: variant === 'ghost' ? '1px solid #EDE7DC' : 0,
    background: variant === 'ghost' ? '#fff' : '#B91C1C',
    color: variant === 'ghost' ? '#5A5546' : '#fff',
    fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
  }}>{children}</button>;
}
function Input({ style = {}, ...p }) {
  return <input {...p} style={{ padding: '9px 12px', borderRadius: 8, border: '1.5px solid #E5DFD1', fontSize: 13, fontFamily: 'inherit', width: '100%', boxSizing: 'border-box', outline: 'none', ...style }} />;
}
function Select({ options, value, onChange, style = {} }) {
  return <select value={value} onChange={onChange} style={{ padding: '9px 12px', borderRadius: 8, border: '1.5px solid #E5DFD1', fontSize: 13, fontFamily: 'inherit', background: '#fff', outline: 'none', ...style }}>
    {options.map(o => <option key={o}>{o}</option>)}
  </select>;
}
function Field({ label, children, style = {} }) {
  return <div style={style}>
    <div style={{ fontSize: 11, color: '#5A5546', fontWeight: 700, marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.4 }}>{label}</div>
    {children}
  </div>;
}
function MiniToggle({ on, onClick }) {
  return <button onClick={onClick} style={{
    width: 36, height: 20, borderRadius: 999, border: 0, cursor: 'pointer',
    background: on ? '#16A34A' : '#D4CCB8', position: 'relative', padding: 0,
  }}>
    <div style={{ position: 'absolute', top: 2, left: on ? 18 : 2, width: 16, height: 16, borderRadius: 999, background: '#fff', transition: 'left .15s', boxShadow: '0 1px 2px rgba(0,0,0,0.2)' }} />
  </button>;
}
function Badge({ children, variant = 'red' }) {
  const colors = { red: ['#FEF2F2', '#B91C1C'], green: ['#ECFDF5', '#16A34A'], gray: ['#F5F0E6', '#5A5546'] };
  const [bg, fg] = colors[variant];
  return <span style={{ padding: '3px 8px', borderRadius: 6, background: bg, color: fg, fontSize: 11, fontWeight: 700 }}>{children}</span>;
}
function Chip({ children }) {
  return <span style={{ padding: '3px 8px', borderRadius: 6, background: '#FAF7F2', border: '1px solid #E5DFD1', fontSize: 12, fontWeight: 600, color: '#1A1A1A', fontFamily: 'ui-monospace, monospace' }}>{children}</span>;
}
function ToggleRow({ label, defaultOn }) {
  const [on, setOn] = useState(defaultOn);
  return <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
    <MiniToggle on={on} onClick={() => setOn(!on)} />
    <span style={{ fontSize: 13, color: '#1A1A1A', fontWeight: 500 }}>{label}</span>
  </div>;
}
function Modal({ title, onClose, children }) {
  return <div onClick={onClose} style={{
    position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 100,
    display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
  }}>
    <div onClick={e => e.stopPropagation()} style={{
      background: '#fff', borderRadius: 16, padding: 24, width: 560, maxHeight: '85vh', overflow: 'auto',
      boxShadow: '0 24px 48px rgba(0,0,0,0.25)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ fontSize: 18, fontWeight: 800 }}>{title}</div>
        <button onClick={onClose} style={{ border: 0, background: '#FAF7F2', width: 30, height: 30, borderRadius: 8, cursor: 'pointer', fontSize: 16 }}>×</button>
      </div>
      {children}
    </div>
  </div>;
}

// Explicitly expose nested modals/components so they're guaranteed findable
// at render time regardless of how Babel hoists function declarations.
Object.assign(window, {
  AdminHeader, AdminCard,
  AdminDashboard, QuickAction,
  AdminLotteries, EditLotteryModal,
  AdminUsers, EditUserModal,
  AdminDreams, EditDreamModal, ImportCSVModal,
  AdminPredictions, EditPredictionModal,
  AdminTemplates, EditTemplateModal,
  AdminBtn, Input, Select, Field, MiniToggle, Badge, Chip, ToggleRow, Modal,
});
