/* ============================================================
   admin.jsx — Password-protected admin panel
   AdminLogin + ContentEditor (Articles / Courses / Teachers / Pricing / Settings)
   ============================================================ */

function AdminLogin({ onSuccess, onCancel }) {
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState('');
  const [loading, setLoading] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setErr('');
    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password: pw }),
      });
      const data = await r.json();
      if (!r.ok) { setErr(data.error || 'เกิดข้อผิดพลาด'); return; }
      onSuccess(data.token);
    } catch {
      setErr('ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '70vh', padding: '40px 16px' }}>
      <div className="editor-card" style={{ maxWidth: 400, width: '100%' }}>
        <div className="section-eyebrow">ระบบหลังบ้าน · ADMIN</div>
        <h2 style={{ margin: '8px 0 24px' }}>เข้าสู่ระบบ</h2>
        <form onSubmit={submit}>
          <div className="field">
            <label>รหัสผ่าน</label>
            <input
              type="password"
              value={pw}
              onChange={e => setPw(e.target.value)}
              autoFocus
              placeholder="กรอกรหัสผ่านผู้ดูแล"
            />
          </div>
          {err && (
            <div style={{ color: 'oklch(0.5 0.15 25)', fontSize: 14, marginBottom: 14 }}>{err}</div>
          )}
          <div style={{ display: 'flex', gap: 10 }}>
            <button type="button" className="btn" onClick={onCancel} style={{ flex: 1 }}>ยกเลิก</button>
            <button type="submit" className="btn btn-primary" disabled={loading} style={{ flex: 2 }}>
              {loading ? 'กำลังเข้าสู่ระบบ…' : 'เข้าสู่ระบบ →'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Articles tab ───────────────────────────────────────────────────────────────

function ArticlesAdminTab({ articles, onEdit, onDelete, onNew, onReset }) {
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <span style={{ fontWeight: 600 }}>บทความทั้งหมด ({articles.length} รายการ)</span>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="btn btn-sm" onClick={onReset}>รีเซ็ต</button>
          <button className="btn btn-primary btn-sm" onClick={onNew}>+ บทความใหม่</button>
        </div>
      </div>

      {articles.map(a => (
        <div key={a.id} className="admin-row">
          <div style={{ width: 80, aspectRatio: '16/10', borderRadius: 6, overflow: 'hidden', flexShrink: 0, border: '1px solid var(--line-soft)' }}>
            {a.coverUrl
              ? <img src={a.coverUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              : <ArticleCover kind={a.cover || 1} />}
          </div>
          <div className="title-line">
            <h4>{a.title}</h4>
            <div className="meta">{a.category} · {a.author}</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn btn-sm" onClick={() => onEdit(a)}>แก้ไข</button>
            <button className="btn btn-sm" onClick={() => { if (confirm('ลบ "' + a.title + '" ?')) onDelete(a); }}>ลบ</button>
          </div>
        </div>
      ))}

      {articles.length === 0 && (
        <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--ink-3)' }}>ยังไม่มีบทความ</div>
      )}
    </div>
  );
}

// ── Hero editor ───────────────────────────────────────────────────────────────

function HeroEditor({ hero, onSave, saving }) {
  const [draft, setDraft] = React.useState(() => ({ ...DEFAULT_HERO, ...hero }));
  const set = (key, val) => setDraft(d => ({ ...d, [key]: val }));

  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 18 }}>
        แก้ไขข้อความบนหน้าแรก — ส่วน "em" (เน้นสี) คือคำที่แสดงด้วยตัวเอียงสีน้ำตาล
      </div>

      <div style={{ borderBottom: '1px solid var(--line-soft)', paddingBottom: 20, marginBottom: 20 }}>
        <div style={{ fontWeight: 600, marginBottom: 12, fontSize: 13, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)' }}>
          Eyebrow · บรรทัดเล็กบนหัว
        </div>
        <div className="field">
          <label>ข้อความ eyebrow</label>
          <input value={draft.eyebrow} onChange={e => set('eyebrow', e.target.value)} placeholder="โรงเรียนสอนดนตรี · BANGKOK" />
        </div>
      </div>

      <div style={{ borderBottom: '1px solid var(--line-soft)', paddingBottom: 20, marginBottom: 20 }}>
        <div style={{ fontWeight: 600, marginBottom: 12, fontSize: 13, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)' }}>
          Heading h1 · ชื่อหลัก (3 บรรทัด)
        </div>
        <div style={{ background: 'var(--bg-2)', border: '1px solid var(--line-soft)', borderRadius: 10, padding: '14px 18px', marginBottom: 14, fontFamily: 'var(--font-thai-display)', fontSize: 20, lineHeight: 1.7 }}>
          {draft.titleLine1}<em style={{ color: 'var(--accent)' }}>{draft.titleEm1}</em><br />
          {draft.titleLine2}<em style={{ color: 'var(--accent)' }}>{draft.titleEm2}</em><br />
          {draft.titleLine3}
        </div>
        <div className="field-row">
          <div className="field">
            <label>บรรทัด 1 (ก่อน em)</label>
            <input value={draft.titleLine1} onChange={e => set('titleLine1', e.target.value)} placeholder="ที่นี่คือ" />
          </div>
          <div className="field">
            <label>em 1 (สีเน้น)</label>
            <input value={draft.titleEm1} onChange={e => set('titleEm1', e.target.value)} placeholder="บ้าน" />
          </div>
        </div>
        <div className="field-row">
          <div className="field">
            <label>บรรทัด 2 (ก่อน em)</label>
            <input value={draft.titleLine2} onChange={e => set('titleLine2', e.target.value)} placeholder="และ" />
          </div>
          <div className="field">
            <label>em 2 (สีเน้น)</label>
            <input value={draft.titleEm2} onChange={e => set('titleEm2', e.target.value)} placeholder="ดนตรี" />
          </div>
        </div>
        <div className="field">
          <label>บรรทัด 3</label>
          <input value={draft.titleLine3} onChange={e => set('titleLine3', e.target.value)} placeholder="คือเสียงของเรา" />
        </div>
      </div>

      <div style={{ borderBottom: '1px solid var(--line-soft)', paddingBottom: 20, marginBottom: 20 }}>
        <div style={{ fontWeight: 600, marginBottom: 12, fontSize: 13, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)' }}>
          Tagline · คำอธิบายใต้ชื่อ
        </div>
        <div className="field">
          <label>ข้อความ tagline</label>
          <textarea value={draft.tagline} onChange={e => set('tagline', e.target.value)} style={{ minHeight: 90 }} />
        </div>
      </div>

      <div style={{ marginBottom: 20 }}>
        <div style={{ fontWeight: 600, marginBottom: 12, fontSize: 13, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-3)' }}>
          ปุ่ม CTA
        </div>
        <div className="field-row">
          <div className="field">
            <label>ปุ่มหลัก (สีเข้ม)</label>
            <input value={draft.btnPrimary} onChange={e => set('btnPrimary', e.target.value)} placeholder="ทดลองเรียนฟรี 30 นาที →" />
          </div>
          <div className="field">
            <label>ปุ่มรอง</label>
            <input value={draft.btnSecondary} onChange={e => set('btnSecondary', e.target.value)} placeholder="ดูหลักสูตรทั้งหมด" />
          </div>
        </div>
      </div>

      <button className="btn btn-primary" onClick={() => onSave(draft)} disabled={saving}>
        {saving ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
      </button>
    </div>
  );
}

// ── Courses editor ─────────────────────────────────────────────────────────────

function CoursesEditor({ courses, onSave, saving }) {
  const [draft, setDraft] = React.useState(() => JSON.parse(JSON.stringify(courses)));

  const update = (idx, key, val) =>
    setDraft(d => d.map((c, i) => i === idx ? { ...c, [key]: val } : c));

  return (
    <div>
      {draft.map((course, idx) => (
        <div key={course.id} style={{ borderBottom: '1px solid var(--line-soft)', paddingBottom: 24, marginBottom: 24 }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 10, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            หลักสูตร {idx + 1}
          </div>
          <div className="field-row">
            <div className="field">
              <label>ชื่อวิชา (ภาษาไทย)</label>
              <input value={course.name} onChange={e => update(idx, 'name', e.target.value)} />
            </div>
            <div className="field">
              <label>ชื่อวิชา (English)</label>
              <input value={course.nameEn} onChange={e => update(idx, 'nameEn', e.target.value)} />
            </div>
          </div>
          <div className="field-row">
            <div className="field">
              <label>ราคา (฿ / คาบ)</label>
              <input type="number" value={course.price} onChange={e => update(idx, 'price', Number(e.target.value))} />
            </div>
            <div className="field">
              <label>ระยะเวลา</label>
              <input value={course.duration} onChange={e => update(idx, 'duration', e.target.value)} />
            </div>
          </div>
          <div className="field-row">
            <div className="field">
              <label>ช่วงอายุ</label>
              <input value={course.ages} onChange={e => update(idx, 'ages', e.target.value)} />
            </div>
            <div className="field">
              <label>Tag (ป้ายกำกับ)</label>
              <input value={course.tag || ''} onChange={e => update(idx, 'tag', e.target.value)} />
            </div>
          </div>
          <div className="field">
            <label>คำอธิบายหลักสูตร</label>
            <textarea value={course.desc} onChange={e => update(idx, 'desc', e.target.value)} style={{ minHeight: 80 }} />
          </div>
        </div>
      ))}
      <button className="btn btn-primary" onClick={() => onSave(draft)} disabled={saving}>
        {saving ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
      </button>
    </div>
  );
}

// ── Teachers editor ────────────────────────────────────────────────────────────

function TeachersEditor({ teachers, onSave, saving }) {
  const [draft, setDraft] = React.useState(() => JSON.parse(JSON.stringify(teachers)));

  const update = (idx, key, val) =>
    setDraft(d => d.map((t, i) => i === idx ? { ...t, [key]: val } : t));

  return (
    <div>
      {draft.map((teacher, idx) => (
        <div key={teacher.id} style={{ borderBottom: '1px solid var(--line-soft)', paddingBottom: 24, marginBottom: 24 }}>
          <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 14 }}>
            <img src={teacher.photo} alt={teacher.name} style={{ width: 52, height: 52, borderRadius: '50%', objectFit: 'cover', border: '2px solid var(--line)' }} />
            <div>
              <strong style={{ fontFamily: 'var(--font-body)' }}>{teacher.name}</strong>
              <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{teacher.subjects.join(', ')}</div>
            </div>
          </div>
          <div className="field-row">
            <div className="field">
              <label>ชื่อ (ไทย)</label>
              <input value={teacher.name} onChange={e => update(idx, 'name', e.target.value)} />
            </div>
            <div className="field">
              <label>ชื่อ (English)</label>
              <input value={teacher.nameEn} onChange={e => update(idx, 'nameEn', e.target.value)} />
            </div>
          </div>
          <div className="field">
            <label>ตำแหน่ง / บทบาท</label>
            <input value={teacher.role} onChange={e => update(idx, 'role', e.target.value)} />
          </div>
          <div className="field">
            <label>ประวัติย่อ</label>
            <textarea value={teacher.bio} onChange={e => update(idx, 'bio', e.target.value)} style={{ minHeight: 80 }} />
          </div>
          <div className="field">
            <label>คำคม (quote)</label>
            <input value={teacher.quote || ''} onChange={e => update(idx, 'quote', e.target.value)} />
          </div>
        </div>
      ))}
      <button className="btn btn-primary" onClick={() => onSave(draft)} disabled={saving}>
        {saving ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
      </button>
    </div>
  );
}

// ── Pricing editor ─────────────────────────────────────────────────────────────

function PricingEditor({ pricing, onSave, saving }) {
  const [draft, setDraft] = React.useState(() => JSON.parse(JSON.stringify(pricing)));

  const updatePlan = (idx, key, val) =>
    setDraft(d => d.map((p, i) => i === idx ? { ...p, [key]: val } : p));

  const updateFeature = (planIdx, featIdx, val) =>
    setDraft(d => d.map((p, i) => {
      if (i !== planIdx) return p;
      const features = [...p.features];
      features[featIdx] = val;
      return { ...p, features };
    }));

  const addFeature = (planIdx) =>
    setDraft(d => d.map((p, i) => i === planIdx ? { ...p, features: [...p.features, ''] } : p));

  const removeFeature = (planIdx, featIdx) =>
    setDraft(d => d.map((p, i) => {
      if (i !== planIdx) return p;
      return { ...p, features: p.features.filter((_, j) => j !== featIdx) };
    }));

  return (
    <div>
      {draft.map((plan, idx) => (
        <div key={plan.id} style={{
          border: plan.featured ? '2px solid var(--brand)' : '1px solid var(--line)',
          borderRadius: 12, padding: 20, marginBottom: 16
        }}>
          {plan.featured && (
            <div style={{ fontSize: 12, color: 'var(--brand)', fontWeight: 600, marginBottom: 10 }}>★ แพ็กเกจยอดนิยม</div>
          )}
          <div className="field-row">
            <div className="field">
              <label>ชื่อแพ็กเกจ</label>
              <input value={plan.title} onChange={e => updatePlan(idx, 'title', e.target.value)} />
            </div>
            <div className="field">
              <label>ราคา (เช่น 10,000)</label>
              <input value={plan.price} onChange={e => updatePlan(idx, 'price', e.target.value)} />
            </div>
          </div>
          <div className="field-row">
            <div className="field">
              <label>ช่วงราคา (เช่น – 1,500 หรือเว้นว่าง)</label>
              <input value={plan.priceRange || ''} onChange={e => updatePlan(idx, 'priceRange', e.target.value)} placeholder="เว้นว่างถ้าไม่มี" />
            </div>
            <div className="field">
              <label>คำอธิบายราคา</label>
              <input value={plan.per} onChange={e => updatePlan(idx, 'per', e.target.value)} />
            </div>
          </div>
          <div className="field">
            <label>สิทธิประโยชน์</label>
            {plan.features.map((f, fi) => (
              <div key={fi} style={{ display: 'flex', gap: 8, marginBottom: 6 }}>
                <input value={f} onChange={e => updateFeature(idx, fi, e.target.value)} style={{ flex: 1 }} />
                <button className="btn btn-sm" onClick={() => removeFeature(idx, fi)}>×</button>
              </div>
            ))}
            <button className="btn btn-sm" onClick={() => addFeature(idx)} style={{ marginTop: 4 }}>+ เพิ่มรายการ</button>
          </div>
        </div>
      ))}
      <button className="btn btn-primary" onClick={() => onSave(draft)} disabled={saving}>
        {saving ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
      </button>
    </div>
  );
}

// ── Gallery editor ─────────────────────────────────────────────────────────────

function GalleryEditor({ gallery, onSave, saving }) {
  const [draft, setDraft] = React.useState(() => JSON.parse(JSON.stringify(gallery)));

  const update = (idx, key, val) =>
    setDraft(d => d.map((item, i) => i === idx ? { ...item, [key]: val } : item));

  const LAYOUT_OPTS = [
    { value: '', label: 'ปกติ' },
    { value: 'wide', label: 'กว้าง (wide)' },
    { value: 'tall', label: 'สูง (tall)' },
  ];

  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 18 }}>
        แก้ไข caption และรูปแต่ละช่องในแกลเลอรี่ — ระบุ path รูปเป็น gallery/gXX.jpg หรือ uploads/ชื่อไฟล์
      </div>
      {draft.map((item, idx) => (
        <div key={idx} style={{ display: 'flex', gap: 14, alignItems: 'center', borderBottom: '1px solid var(--line-soft)', paddingBottom: 14, marginBottom: 14 }}>
          <img
            src={item.img}
            alt={item.label}
            style={{ width: 90, height: 65, objectFit: 'cover', borderRadius: 8, flexShrink: 0, border: '1px solid var(--line)' }}
          />
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <div className="field-row" style={{ marginBottom: 0 }}>
              <div className="field" style={{ marginBottom: 0 }}>
                <label>Caption</label>
                <input value={item.label} onChange={e => update(idx, 'label', e.target.value)} />
              </div>
              <div className="field" style={{ marginBottom: 0, maxWidth: 130 }}>
                <label>Layout</label>
                <select value={item.c || ''} onChange={e => update(idx, 'c', e.target.value)}
                  style={{ width: '100%', padding: '8px 10px', border: '1px solid var(--line)', borderRadius: 8, background: 'var(--bg)', fontFamily: 'var(--font-body)', fontSize: 14 }}>
                  {LAYOUT_OPTS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
                </select>
              </div>
            </div>
            <div className="field" style={{ marginBottom: 0 }}>
              <label>Path รูปภาพ</label>
              <input value={item.img} onChange={e => update(idx, 'img', e.target.value)} style={{ fontFamily: 'var(--font-mono, monospace)', fontSize: 12 }} />
            </div>
          </div>
        </div>
      ))}
      <button className="btn btn-primary" onClick={() => onSave(draft)} disabled={saving}>
        {saving ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
      </button>
    </div>
  );
}

// ── Reviews editor ────────────────────────────────────────────────────────────

function ReviewsEditor({ reviews, onSave, saving }) {
  const [draft, setDraft] = React.useState(() => JSON.parse(JSON.stringify(reviews)));

  const update = (idx, key, val) =>
    setDraft(d => d.map((r, i) => i === idx ? { ...r, [key]: val } : r));

  const addReview = () => {
    const newId = 'r' + Date.now();
    setDraft(d => [...d, { id: newId, name: 'ชื่อผู้เขียนรีวิว', rating: 5, text: 'เพิ่มข้อความรีวิวที่นี่' }]);
  };

  const removeReview = (idx) => {
    setDraft(d => d.filter((_, i) => i !== idx));
  };

  return (
    <div>
      <div style={{ fontSize: 13, color: 'var(--ink-3)', marginBottom: 18 }}>
        เพิ่มและแก้ไขรีวิวจากผู้ปกครองและนักเรียน — rating ตั้งแต่ 1-5
      </div>
      {draft.map((review, idx) => (
        <div key={review.id} style={{ borderBottom: '1px solid var(--line-soft)', paddingBottom: 24, marginBottom: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <h4 style={{ margin: 0, fontFamily: 'var(--font-body)' }}>รีวิว #{idx + 1}</h4>
            <button className="btn btn-sm" onClick={() => removeReview(idx)} style={{ color: 'oklch(0.5 0.15 25)' }}>ลบ</button>
          </div>
          <div className="field-row">
            <div className="field">
              <label>ชื่อผู้เขียน</label>
              <input value={review.name} onChange={e => update(idx, 'name', e.target.value)} placeholder="เช่น ชญาน ศิริศร" />
            </div>
            <div className="field">
              <label>คะแนน (1-5)</label>
              <input type="number" min="1" max="5" value={review.rating} onChange={e => update(idx, 'rating', Number(e.target.value))} />
            </div>
          </div>
          <div className="field">
            <label>ข้อความรีวิว</label>
            <textarea value={review.text} onChange={e => update(idx, 'text', e.target.value)} style={{ minHeight: 100 }} />
          </div>
        </div>
      ))}
      <div style={{ display: 'flex', gap: 8 }}>
        <button className="btn" onClick={addReview}>+ เพิ่มรีวิว</button>
        <button className="btn btn-primary" onClick={() => onSave(draft)} disabled={saving}>
          {saving ? 'กำลังบันทึก…' : 'บันทึกการเปลี่ยนแปลง'}
        </button>
      </div>
    </div>
  );
}

// ── Payments tab ──────────────────────────────────────────────────────────────

function PaymentsTab({ token }) {
  const [payments, setPayments] = React.useState(null);

  React.useEffect(() => {
    fetch('/api/payments', { headers: { 'x-auth-token': token } })
      .then(r => r.json())
      .then(data => setPayments(Array.isArray(data) ? data : []))
      .catch(() => setPayments([]));
  }, []);

  const STATUS_LABEL = { pending: 'รอชำระ', paid: 'ชำระแล้ว', failed: 'ไม่สำเร็จ' };
  const STATUS_COLOR = {
    pending: 'oklch(0.65 0.1 65)',
    paid:    'oklch(0.45 0.1 140)',
    failed:  'oklch(0.5 0.15 25)',
  };

  if (!payments) return <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)' }}>กำลังโหลด…</div>;

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <span style={{ fontWeight: 600 }}>ออเดอร์ทั้งหมด ({payments.length} รายการ)</span>
        <span style={{ fontSize: 13, color: 'var(--ink-3)' }}>อัปเดตโดย GB Prime Pay webhook</span>
      </div>

      {payments.length === 0 && (
        <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--ink-3)' }}>
          ยังไม่มีออเดอร์ — เมื่อลูกค้าซื้อแพ็กเกจจะปรากฏที่นี่
        </div>
      )}

      {payments.map((pmt, i) => (
        <div key={i} className="admin-row" style={{ alignItems: 'flex-start', flexWrap: 'wrap', gap: 12 }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div style={{ fontWeight: 600, marginBottom: 2 }}>{pmt.customer?.name || '—'}</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>{pmt.subjectName} · {pmt.sessions} คาบ · ผ่อน {pmt.installments} งวด</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2, fontFamily: 'monospace' }}>{pmt.referenceNo}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontWeight: 700, color: 'var(--accent)', fontSize: 16 }}>
              ฿{(pmt.amount || 0).toLocaleString('th-TH')}
            </div>
            <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>
              {pmt.createdAt ? new Date(pmt.createdAt * 1000).toLocaleDateString('th-TH') : '—'}
            </div>
          </div>
          <div>
            <span style={{
              fontSize: 12, fontWeight: 600, padding: '4px 10px', borderRadius: 20,
              background: STATUS_COLOR[pmt.status] + '22',
              color: STATUS_COLOR[pmt.status],
              border: '1px solid ' + STATUS_COLOR[pmt.status] + '55',
            }}>
              {STATUS_LABEL[pmt.status] || pmt.status}
            </span>
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Settings editor ────────────────────────────────────────────────────────────

function SettingsEditor({ token }) {
  const [pw, setPw] = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [msg, setMsg] = React.useState('');
  const [err, setErr] = React.useState('');

  const submit = async (e) => {
    e.preventDefault();
    setMsg(''); setErr('');
    if (pw !== pw2) { setErr('รหัสผ่านไม่ตรงกัน'); return; }
    if (pw.length < 6) { setErr('รหัสผ่านต้องมีอย่างน้อย 6 ตัวอักษร'); return; }
    try {
      const r = await fetch('/api/auth/password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-auth-token': token },
        body: JSON.stringify({ newPassword: pw }),
      });
      if (r.ok) { setMsg('เปลี่ยนรหัสผ่านสำเร็จ'); setPw(''); setPw2(''); }
      else { const d = await r.json(); setErr(d.error || 'เกิดข้อผิดพลาด'); }
    } catch { setErr('ไม่สามารถเชื่อมต่อได้'); }
  };

  return (
    <div style={{ maxWidth: 400 }}>
      <h4 style={{ marginBottom: 16, fontFamily: 'var(--font-body)', fontWeight: 600 }}>เปลี่ยนรหัสผ่านผู้ดูแล</h4>
      <form onSubmit={submit}>
        <div className="field">
          <label>รหัสผ่านใหม่</label>
          <input type="password" value={pw} onChange={e => setPw(e.target.value)} />
        </div>
        <div className="field">
          <label>ยืนยันรหัสผ่าน</label>
          <input type="password" value={pw2} onChange={e => setPw2(e.target.value)} />
        </div>
        {err && <div style={{ color: 'oklch(0.5 0.15 25)', fontSize: 13, marginBottom: 12 }}>{err}</div>}
        {msg && <div style={{ color: 'oklch(0.45 0.1 140)', fontSize: 13, marginBottom: 12 }}>{msg}</div>}
        <button className="btn btn-primary" type="submit">เปลี่ยนรหัสผ่าน</button>
      </form>
    </div>
  );
}

// ── Content editor (main admin shell) ─────────────────────────────────────────

function ContentEditor({ token, articles, onArticleEdit, onArticleDelete, onArticleNew, onArticlesReset, onContentSave, onLogout, onBack }) {
  const [tab, setTab] = React.useState('articles');
  const [content, setContent] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [saveMsg, setSaveMsg] = React.useState('');

  React.useEffect(() => {
    fetch('/api/content')
      .then(r => r.json())
      .then(data => {
        const c = data || {};
        setContent({
          hero:     { ...DEFAULT_HERO, ...(c.hero || {}) },
          courses:  c.courses  || JSON.parse(JSON.stringify(COURSES)),
          teachers: c.teachers || JSON.parse(JSON.stringify(TEACHERS)),
          pricing:  c.pricing  || JSON.parse(JSON.stringify(DEFAULT_PRICING)),
          gallery:  c.gallery  || JSON.parse(JSON.stringify(DEFAULT_GALLERY)),
          reviews:  c.reviews  || JSON.parse(JSON.stringify(DEFAULT_REVIEWS)),
        });
      })
      .catch(() => {
        setContent({
          hero:     { ...DEFAULT_HERO },
          courses:  JSON.parse(JSON.stringify(COURSES)),
          teachers: JSON.parse(JSON.stringify(TEACHERS)),
          pricing:  JSON.parse(JSON.stringify(DEFAULT_PRICING)),
          gallery:  JSON.parse(JSON.stringify(DEFAULT_GALLERY)),
          reviews:  JSON.parse(JSON.stringify(DEFAULT_REVIEWS)),
        });
      });
  }, []);

  const saveContent = async (updates) => {
    setSaving(true);
    setSaveMsg('');
    try {
      await fetch('/api/content', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', 'x-auth-token': token },
        body: JSON.stringify(updates),
      });
      setContent(updates);
      onContentSave(updates);
      setSaveMsg('บันทึกสำเร็จ');
      setTimeout(() => setSaveMsg(''), 3000);
    } finally {
      setSaving(false);
    }
  };

  const TABS = [
    { id: 'hero',     label: 'หน้าหลัก' },
    { id: 'articles', label: 'บทความ' },
    { id: 'courses',  label: 'หลักสูตร' },
    { id: 'teachers', label: 'ครูผู้สอน' },
    { id: 'pricing',  label: 'ค่าเรียน' },
    { id: 'gallery',  label: 'แกลเลอรี่' },
    { id: 'reviews',  label: 'รีวิว' },
    { id: 'payments', label: 'การชำระเงิน' },
    { id: 'settings', label: 'ตั้งค่า' },
  ];

  return (
    <div className="editor-shell">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <button className="btn btn-ghost btn-sm" onClick={onBack}>← กลับสู่หน้าเว็บ</button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {saveMsg && <span style={{ fontSize: 13, color: 'oklch(0.45 0.1 140)' }}>✓ {saveMsg}</span>}
          <button className="btn btn-sm" onClick={onLogout}>ออกจากระบบ</button>
        </div>
      </div>

      <div className="editor-card">
        <div className="section-eyebrow">ระบบหลังบ้าน · ADMIN</div>
        <h2 style={{ margin: '6px 0 20px' }}>จัดการเนื้อหา</h2>

        {/* Tab bar */}
        <div style={{ display: 'flex', gap: 2, marginBottom: 28, borderBottom: '1px solid var(--line)' }}>
          {TABS.map(t => (
            <button
              key={t.id}
              onClick={() => setTab(t.id)}
              style={{
                padding: '8px 16px',
                border: 'none',
                background: 'none',
                cursor: 'pointer',
                fontSize: 14,
                fontFamily: 'var(--font-body)',
                color: tab === t.id ? 'var(--brand)' : 'var(--ink-2)',
                borderBottom: tab === t.id ? '2px solid var(--brand)' : '2px solid transparent',
                marginBottom: -1,
                fontWeight: tab === t.id ? 600 : 400,
                transition: 'color 0.15s',
              }}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Hero tab */}
        {tab === 'hero' && (
          content
            ? <HeroEditor hero={content.hero} onSave={h => saveContent({ ...content, hero: h })} saving={saving} />
            : <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)' }}>กำลังโหลด…</div>
        )}

        {/* Articles tab */}
        {tab === 'articles' && (
          <ArticlesAdminTab
            articles={articles}
            onEdit={onArticleEdit}
            onDelete={onArticleDelete}
            onNew={onArticleNew}
            onReset={onArticlesReset}
          />
        )}

        {/* Courses tab */}
        {tab === 'courses' && (
          content
            ? <CoursesEditor courses={content.courses} onSave={c => saveContent({ ...content, courses: c })} saving={saving} />
            : <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)' }}>กำลังโหลด…</div>
        )}

        {/* Teachers tab */}
        {tab === 'teachers' && (
          content
            ? <TeachersEditor teachers={content.teachers} onSave={t => saveContent({ ...content, teachers: t })} saving={saving} />
            : <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)' }}>กำลังโหลด…</div>
        )}

        {/* Pricing tab */}
        {tab === 'pricing' && (
          content
            ? <PricingEditor pricing={content.pricing} onSave={p => saveContent({ ...content, pricing: p })} saving={saving} />
            : <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)' }}>กำลังโหลด…</div>
        )}

        {/* Gallery tab */}
        {tab === 'gallery' && (
          content
            ? <GalleryEditor gallery={content.gallery} onSave={g => saveContent({ ...content, gallery: g })} saving={saving} />
            : <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)' }}>กำลังโหลด…</div>
        )}

        {/* Reviews tab */}
        {tab === 'reviews' && (
          content
            ? <ReviewsEditor reviews={content.reviews} onSave={r => saveContent({ ...content, reviews: r })} saving={saving} />
            : <div style={{ padding: '40px 0', textAlign: 'center', color: 'var(--ink-3)' }}>กำลังโหลด…</div>
        )}

        {/* Payments tab */}
        {tab === 'payments' && <PaymentsTab token={token} />}

        {/* Settings tab */}
        {tab === 'settings' && <SettingsEditor token={token} />}
      </div>
    </div>
  );
}

Object.assign(window, { AdminLogin, ContentEditor });
