/* global React */
const { useState: useStateCfg, useEffect: useEffectCfg, useMemo: useMemoCfg } = React;

// =============================================================================
// OFFERS (banner toggle + live preview)
// =============================================================================
window.OffersSection = function OffersSection() {
  const [offers, setOffers] = useStateCfg(null);
  const [saving, setSaving] = useStateCfg(false);
  const [savedTick, setSavedTick] = useStateCfg(0);

  useEffectCfg(() => {
    window.LQ.request('/settings/offers_banner').then(setOffers).catch(() => setOffers({ enabled: false, text: '' }));
  }, []);

  useEffectCfg(() => {
    if (!offers) return;
    const t = setTimeout(async () => {
      setSaving(true);
      try {
        await window.LQ.request('/settings/offers_banner', { method: 'PUT', body: offers });
        setSavedTick(savedTick + 1);
      } catch {}
      setSaving(false);
    }, 600);
    return () => clearTimeout(t);
  }, [offers && offers.enabled, offers && offers.text]);

  if (!offers) return <div className="admin-loading">Loading…</div>;

  const previewText = (offers.text || '').trim();

  return (
    <>
      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Marquee Banner</h3>{saving && <span className="admin-cell-sub">Saving…</span>}</div>
        <p className="admin-section-intro">Shows above the header on every public page when enabled. Use it for festive offers, holiday hours, or new arrivals.</p>

        <label className="admin-toggle-row">
          <input type="checkbox" checked={!!offers.enabled} onChange={(e) => setOffers({ ...offers, enabled: e.target.checked })} />
          <span>Banner enabled</span>
        </label>

        <label className="admin-label" style={{ marginTop: 18 }}>Banner text</label>
        <textarea className="admin-input" rows="2" maxLength="200"
                  value={offers.text || ''}
                  onChange={(e) => setOffers({ ...offers, text: e.target.value })}
                  placeholder="e.g. Festive offer · 20% off all press-ons · code LACQUER20" />
        <div className="admin-cell-sub">{(offers.text || '').length} / 200</div>
      </div>

      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Live Preview</h3></div>
        <p className="admin-section-intro">This is exactly how the banner appears on the public site.</p>
        <div className="admin-banner-preview-frame">
          {offers.enabled && previewText ? (
            <div className="admin-banner-preview">
              <div className="admin-banner-preview-track">
                {previewText} ✦ {previewText} ✦ {previewText} ✦ {previewText}
              </div>
            </div>
          ) : (
            <div className="admin-banner-preview-off">Banner is off — toggle above to show on public site.</div>
          )}
        </div>
        <div className="admin-cell-sub" style={{ marginTop: 12 }}>Public pages refresh banner data on every load — changes go live immediately.</div>
      </div>
    </>
  );
};

// =============================================================================
// BLOG
// =============================================================================
window.BlogSection = function BlogSection() {
  const [list, setList] = useStateCfg([]);
  const [editing, setEditing] = useStateCfg(null);
  const [adding, setAdding] = useStateCfg(false);
  const [loading, setLoading] = useStateCfg(true);

  function load() {
    setLoading(true);
    window.LQ.request('/blog').then((r) => { setList(r || []); setLoading(false); });
  }
  useEffectCfg(load, []);

  async function del(id) {
    if (!confirm('Delete this post permanently?')) return;
    await window.LQ.request(`/blog/${id}`, { method: 'DELETE' });
    if (editing && editing.id === id) setEditing(null);
    load();
  }

  return (
    <>
      <div className="admin-toolbar">
        <p className="admin-section-intro" style={{ margin: 0 }}>{list.length} posts.</p>
        <button className="admin-btn admin-btn-primary" onClick={() => setAdding(true)}>+ New post</button>
      </div>

      <div className="admin-blog-layout">
        <div className="admin-blog-list">
          {loading ? <div className="admin-loading">Loading…</div> :
           list.length === 0 ? <div className="admin-empty">No posts yet.</div> :
           list.map((p) => (
             <button key={p.id}
                     className={`admin-blog-list-item ${editing && editing.id === p.id ? 'active' : ''}`}
                     onClick={() => setEditing(p)}>
               <div className="admin-cell-strong">{p.title}</div>
               <div className="admin-cell-sub">{window.LQ_fmtDate(p.updated_at)} · <span className={`admin-badge ${p.status}`}>{p.status}</span></div>
             </button>
           ))
          }
        </div>

        <div className="admin-blog-editor">
          {(editing || adding) ?
            <window.BlogEditor
              post={editing}
              isNew={adding}
              onSaved={(updated) => { setAdding(false); setEditing(updated); load(); }}
              onDelete={() => editing && del(editing.id)}
            /> :
            <div className="admin-empty">Pick a post on the left, or create a new one.</div>}
        </div>
      </div>
    </>
  );
};

window.BlogEditor = function BlogEditor({ post, isNew, onSaved, onDelete }) {
  const [form, setForm] = useStateCfg(null);
  const [saving, setSaving] = useStateCfg(false);
  const [err, setErr] = useStateCfg('');

  useEffectCfg(() => {
    if (isNew) {
      setForm({ title: '', slug: '', meta_desc: '', body: '', status: 'draft' });
    } else if (post) {
      // Fetch full post (list view doesn't include body)
      window.LQ.request(`/blog/${post.id}`).then((p) => setForm({
        title: p.title, slug: p.slug, meta_desc: p.meta_desc || '', body: p.body || '', status: p.status
      }));
    }
  }, [post && post.id, isNew]);

  if (!form) return <div className="admin-loading">Loading…</div>;

  function set(k, v) {
    setForm((f) => {
      const next = { ...f, [k]: v };
      if (k === 'title' && (!post || !post.slug || f.slug === window.LQ_slug(f.title || ''))) {
        next.slug = window.LQ_slug(v);
      }
      return next;
    });
  }

  async function save(e) {
    e && e.preventDefault();
    setSaving(true); setErr('');
    try {
      let saved;
      if (post && !isNew) {
        await window.LQ.request(`/blog/${post.id}`, { method: 'PATCH', body: form });
        saved = { ...post, ...form };
      } else {
        const r = await window.LQ.request('/blog', { method: 'POST', body: form });
        saved = { id: r.id, ...form };
      }
      onSaved(saved);
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  }

  return (
    <form onSubmit={save} className="admin-blog-form">
      <label className="admin-label">Title</label>
      <input className="admin-input" required value={form.title} onChange={(e) => set('title', e.target.value)} />

      <label className="admin-label" style={{ marginTop: 14 }}>Slug</label>
      <input className="admin-input" value={form.slug} onChange={(e) => set('slug', window.LQ_slug(e.target.value))} />

      <label className="admin-label" style={{ marginTop: 14 }}>Meta Description ({(form.meta_desc || '').length} / 160)</label>
      <textarea className="admin-input" rows="2" maxLength="200" value={form.meta_desc} onChange={(e) => set('meta_desc', e.target.value)} />

      <label className="admin-label" style={{ marginTop: 14 }}>Body</label>
      <textarea className="admin-input admin-input-mono" rows="14" value={form.body} onChange={(e) => set('body', e.target.value)} placeholder="Markdown or plain text — public blog rendering is on the roadmap." />

      <label className="admin-toggle-row" style={{ marginTop: 14 }}>
        <input type="checkbox" checked={form.status === 'published'} onChange={(e) => set('status', e.target.checked ? 'published' : 'draft')} />
        <span>{form.status === 'published' ? 'Published' : 'Draft'}</span>
      </label>

      {err && <div className="admin-auth-msg err">{err}</div>}
      <div className="admin-modal-foot" style={{ borderTop: '1px solid rgba(2,0,73,0.08)', paddingTop: 16 }}>
        {post && !isNew && <button type="button" className="admin-btn admin-btn-ghost admin-btn-danger" onClick={onDelete}>Delete</button>}
        <div style={{ flex: 1 }} />
        <button type="submit" className="admin-btn admin-btn-primary" disabled={saving}>{saving ? 'Saving…' : 'Save'}</button>
      </div>
    </form>
  );
};

window.LQ_slug = function (s) {
  return (s || '').toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
};

// =============================================================================
// PAYMENT (RazorPay)
// =============================================================================
window.PaymentSection = function PaymentSection() {
  const [payment, setPayment] = useStateCfg(null);
  const [saving, setSaving] = useStateCfg(false);

  useEffectCfg(() => {
    window.LQ.request('/settings/payment').then(setPayment).catch(() => setPayment({}));
  }, []);

  async function save() {
    setSaving(true);
    await window.LQ.request('/settings/payment', { method: 'PUT', body: payment });
    setSaving(false);
    alert('Payment settings saved.');
  }

  if (!payment) return <div className="admin-loading">Loading…</div>;

  function set(k, v) { setPayment({ ...payment, [k]: v }); }

  return (
    <>
      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Razorpay Credentials</h3></div>
        <p className="admin-section-intro">Get these from your Razorpay Dashboard → Settings → API Keys.</p>
        <div className="admin-form-grid">
          <div>
            <label className="admin-label">Key ID</label>
            <input className="admin-input" value={payment.razorpay_key_id || ''} onChange={(e) => set('razorpay_key_id', e.target.value)} placeholder="rzp_live_…" />
          </div>
          <div>
            <label className="admin-label">Key Secret</label>
            <input className="admin-input" type="password" value={payment.razorpay_key_secret || ''} onChange={(e) => set('razorpay_key_secret', e.target.value)} />
          </div>
          <div className="admin-form-row-full">
            <label className="admin-label">Webhook Secret</label>
            <input className="admin-input" type="password" value={payment.webhook_secret || ''} onChange={(e) => set('webhook_secret', e.target.value)} />
          </div>
        </div>
      </div>

      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Payment Toggles</h3></div>
        <label className="admin-toggle-row">
          <input type="checkbox" checked={!!payment.enable_booking_fee} onChange={(e) => set('enable_booking_fee', e.target.checked)} />
          <span>Charge booking deposit on appointment</span>
        </label>
        <label className="admin-toggle-row" style={{ marginTop: 12 }}>
          <input type="checkbox" checked={!!payment.enable_shop_payment} onChange={(e) => set('enable_shop_payment', e.target.checked)} />
          <span>Online payment for press-on shop</span>
        </label>
      </div>

      <button className="admin-btn admin-btn-primary" onClick={save} disabled={saving}>{saving ? 'Saving…' : 'Save payment settings'}</button>
    </>
  );
};

// =============================================================================
// SITE SETTINGS + REFILL RULES + BACKUP
// =============================================================================
window.SettingsSection = function SettingsSection() {
  const [site, setSite] = useStateCfg(null);
  const [refill, setRefill] = useStateCfg(null);
  const [savingS, setSavingS] = useStateCfg(false);
  const [savingR, setSavingR] = useStateCfg(false);

  useEffectCfg(() => {
    Promise.all([
      window.LQ.request('/settings/site').catch(() => ({})),
      window.LQ.request('/settings/refill_rules').catch(() => ({ days: 21, services: [] })),
    ]).then(([s, r]) => { setSite(s); setRefill(r); });
  }, []);

  async function saveSite() {
    setSavingS(true);
    await window.LQ.request('/settings/site', { method: 'PUT', body: site });
    setSavingS(false);
    alert('Site settings saved. Public pages will read these on next load.');
  }

  async function saveRefill() {
    setSavingR(true);
    await window.LQ.request('/settings/refill_rules', { method: 'PUT', body: refill });
    setSavingR(false);
    alert('Refill rules saved.');
  }

  function exportBackup() {
    window.LQ.downloadFile('/backup', `lacquery-backup-${new Date().toISOString().slice(0, 10)}.json`);
  }

  async function importBackup(file) {
    if (!confirm('Restore from this file? It REPLACES clients, appointments, products, orders, photos, blog, and settings. Users + audit log are preserved.')) return;
    const text = await file.text();
    try {
      const json = JSON.parse(text);
      await window.LQ.request('/backup', { method: 'POST', body: json });
      alert('Backup restored.');
      location.reload();
    } catch (e) {
      alert('Restore failed: ' + e.message);
    }
  }

  if (!site || !refill) return <div className="admin-loading">Loading…</div>;

  return (
    <>
      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Site Settings</h3></div>
        <p className="admin-section-intro">Single source of truth for the contact details that appear on the public site, in WhatsApp links, and in email signatures.</p>
        <div className="admin-form-grid">
          <div>
            <label className="admin-label">WhatsApp Number (no +)</label>
            <input className="admin-input" value={site.whatsappNumber || ''} onChange={(e) => setSite({ ...site, whatsappNumber: e.target.value.replace(/\D/g, '') })} placeholder="918317451779" />
          </div>
          <div>
            <label className="admin-label">Display Phone</label>
            <input className="admin-input" value={site.phone || ''} onChange={(e) => setSite({ ...site, phone: e.target.value })} />
          </div>
          <div>
            <label className="admin-label">Email</label>
            <input className="admin-input" value={site.email || ''} onChange={(e) => setSite({ ...site, email: e.target.value })} />
          </div>
          <div>
            <label className="admin-label">Hours</label>
            <input className="admin-input" value={site.hours || ''} onChange={(e) => setSite({ ...site, hours: e.target.value })} />
          </div>
          <div className="admin-form-row-full">
            <label className="admin-label">Address</label>
            <input className="admin-input" value={site.address || ''} onChange={(e) => setSite({ ...site, address: e.target.value })} />
          </div>
        </div>
        <button className="admin-btn admin-btn-primary" style={{ marginTop: 16 }} onClick={saveSite} disabled={savingS}>{savingS ? 'Saving…' : 'Save site settings'}</button>
      </div>

      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Refill Rules</h3></div>
        <p className="admin-section-intro">When a client completes one of these services, a refill reminder is auto-flagged after the chosen number of days.</p>
        <div className="admin-form-grid">
          <div>
            <label className="admin-label">Days until refill due</label>
            <input className="admin-input" type="number" min="1" max="120" value={refill.days || 21} onChange={(e) => setRefill({ ...refill, days: Number(e.target.value) })} />
          </div>
          <div className="admin-form-row-full">
            <label className="admin-label">Refill-trigger services</label>
            <div className="admin-chip-toggle-row">
              {['Gel Extensions','Nail Extensions','Acrylic Extensions','Permanent Extensions','Builder Gel','Refill','Gel Polish','Nail Art'].map((s) => {
                const on = (refill.services || []).includes(s);
                return (
                  <button type="button" key={s}
                          className={`admin-chip-btn ${on ? 'active' : ''}`}
                          onClick={() => setRefill({ ...refill, services: on ? refill.services.filter((x) => x !== s) : [...(refill.services || []), s] })}>{s}</button>
                );
              })}
            </div>
          </div>
        </div>
        <button className="admin-btn admin-btn-primary" style={{ marginTop: 16 }} onClick={saveRefill} disabled={savingR}>{savingR ? 'Saving…' : 'Save refill rules'}</button>
      </div>

      <div className="admin-panel">
        <div className="admin-panel-head"><h3>Backup & Restore</h3></div>
        <p className="admin-section-intro">Download a JSON snapshot of all data, or restore from a previous backup. Take one weekly to be safe.</p>
        <div className="admin-row-actions">
          <button className="admin-btn admin-btn-ghost" onClick={exportBackup}>Download backup (JSON)</button>
          <label className="admin-btn admin-btn-ghost">
            Restore from backup
            <input type="file" accept="application/json" style={{ display: 'none' }} onChange={(e) => e.target.files[0] && importBackup(e.target.files[0])} />
          </label>
        </div>
      </div>
    </>
  );
};

// =============================================================================
// USERS (admin manages staff + permissions)
// =============================================================================
window.UsersSection = function UsersSection({ user: me }) {
  const [list, setList] = useStateCfg([]);
  const [adding, setAdding] = useStateCfg(false);
  const [editing, setEditing] = useStateCfg(null);
  const [loading, setLoading] = useStateCfg(true);

  function load() {
    setLoading(true);
    window.LQ.request('/users').then((r) => { setList(r || []); setLoading(false); });
  }
  useEffectCfg(load, []);

  async function deactivate(id) {
    if (!confirm('Deactivate this user? They will lose access immediately.')) return;
    await window.LQ.request(`/users/${id}`, { method: 'DELETE' });
    load();
  }

  async function reactivate(id) {
    await window.LQ.request(`/users/${id}`, { method: 'PATCH', body: { is_active: true } });
    load();
  }

  if (loading) return <div className="admin-loading">Loading…</div>;

  return (
    <>
      <div className="admin-toolbar">
        <p className="admin-section-intro" style={{ margin: 0 }}>{list.filter((u) => u.is_active).length} active · {list.filter((u) => !u.is_active).length} inactive</p>
        <button className="admin-btn admin-btn-primary" onClick={() => setAdding(true)}>+ Add user</button>
      </div>

      <div className="admin-table-wrap">
        <table className="admin-table">
          <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Tabs</th><th>Last login</th><th>Actions</th></tr></thead>
          <tbody>
            {list.map((u) => (
              <tr key={u.id} style={{ opacity: u.is_active ? 1 : 0.5 }}>
                <td><strong>{u.name}</strong>{u.id === me.id && <span className="admin-chip" style={{ marginLeft: 6 }}>You</span>}</td>
                <td>{u.email}</td>
                <td><span className={`admin-badge ${u.role}`}>{u.role}</span></td>
                <td>
                  {u.role === 'admin' ? <span className="admin-cell-sub">All</span> :
                   (u.permissions && u.permissions.length) ?
                     <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                       {u.permissions.map((p) => <span key={p} className="admin-chip">{p}</span>)}
                     </div> :
                     <span className="admin-cell-sub">None</span>}
                </td>
                <td>{u.last_login_at ? window.LQ_fmtDateTime(u.last_login_at) : '—'}</td>
                <td>
                  <div className="admin-row-actions">
                    <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setEditing(u)}>Edit</button>
                    {u.is_active && u.id !== me.id && <button className="admin-btn admin-btn-ghost admin-btn-sm admin-btn-danger" onClick={() => deactivate(u.id)}>Deactivate</button>}
                    {!u.is_active && <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => reactivate(u.id)}>Reactivate</button>}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {(adding || editing) && <window.UserModal user={editing} isNew={adding} onClose={() => { setAdding(false); setEditing(null); }} onSaved={() => { setAdding(false); setEditing(null); load(); }} />}
    </>
  );
};

window.UserModal = function UserModal({ user, isNew, onClose, onSaved }) {
  const [form, setForm] = useStateCfg(() => ({
    name: user?.name || '',
    email: user?.email || '',
    password: '',
    role: user?.role || 'staff',
    permissions: user?.permissions || window.LQ_TABS.filter((t) => t.defaultStaff && !t.adminOnly).map((t) => t.key),
    send_invite: true,
  }));
  const [saving, setSaving] = useStateCfg(false);
  const [err, setErr] = useStateCfg('');

  function togglePerm(k) {
    setForm((f) => ({ ...f, permissions: f.permissions.includes(k) ? f.permissions.filter((x) => x !== k) : [...f.permissions, k] }));
  }

  function generatePassword() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
    let p = '';
    for (let i = 0; i < 12; i++) p += chars[Math.floor(Math.random() * chars.length)];
    setForm((f) => ({ ...f, password: p }));
  }

  async function save(e) {
    e.preventDefault();
    setSaving(true); setErr('');
    try {
      if (isNew) {
        await window.LQ.request('/users', { method: 'POST', body: form });
      } else {
        const body = { name: form.name, role: form.role, permissions: form.permissions };
        if (form.email !== user.email) body.email = form.email;
        if (form.password) body.password = form.password;
        await window.LQ.request(`/users/${user.id}`, { method: 'PATCH', body });
      }
      onSaved();
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="admin-modal-overlay" onClick={onClose}>
      <div className="admin-modal admin-modal-wide" onClick={(e) => e.stopPropagation()}>
        <div className="admin-modal-head">
          <h3>{isNew ? 'Add User' : 'Edit User'}</h3>
          <button className="admin-modal-close" onClick={onClose}>×</button>
        </div>
        <form onSubmit={save} className="admin-modal-body">
          <div className="admin-form-grid">
            <div>
              <label className="admin-label">Full Name</label>
              <input className="admin-input" required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
            </div>
            <div>
              <label className="admin-label">Email</label>
              <input className="admin-input" type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
            </div>
            <div>
              <label className="admin-label">{isNew ? 'Temporary Password' : 'Reset Password (optional)'}</label>
              <div style={{ display: 'flex', gap: 6 }}>
                <input className="admin-input" type="text" value={form.password} required={isNew} minLength={isNew ? 8 : 0} onChange={(e) => setForm({ ...form, password: e.target.value })} placeholder="8+ chars" />
                <button type="button" className="admin-btn admin-btn-ghost admin-btn-sm" onClick={generatePassword}>Generate</button>
              </div>
            </div>
            <div>
              <label className="admin-label">Role</label>
              <select className="admin-input" value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
                <option value="admin">Admin (full access)</option>
                <option value="staff">Staff (custom permissions)</option>
              </select>
            </div>

            {form.role === 'staff' && (
              <div className="admin-form-row-full">
                <label className="admin-label">Tabs this staff member can access</label>
                <div className="admin-perm-grid">
                  {window.LQ_TABS.filter((t) => !t.adminOnly).map((t) => (
                    <label key={t.key} className="admin-perm-item">
                      <input type="checkbox"
                             checked={form.permissions.includes(t.key)}
                             onChange={() => togglePerm(t.key)} />
                      <span>{t.label}</span>
                    </label>
                  ))}
                </div>
                <p className="admin-cell-sub" style={{ marginTop: 8 }}>Users + Audit Log are admin-only and cannot be granted to staff.</p>
              </div>
            )}

            {isNew && (
              <div className="admin-form-row-full">
                <label className="admin-toggle-row">
                  <input type="checkbox" checked={form.send_invite} onChange={(e) => setForm({ ...form, send_invite: e.target.checked })} />
                  <span>Email login credentials to {form.email || 'them'}</span>
                </label>
              </div>
            )}
          </div>
          {err && <div className="admin-auth-msg err">{err}</div>}
          <div className="admin-modal-foot">
            <button type="button" className="admin-btn admin-btn-ghost" onClick={onClose}>Cancel</button>
            <button type="submit" className="admin-btn admin-btn-primary" disabled={saving}>{saving ? 'Saving…' : (isNew ? 'Create user' : 'Save changes')}</button>
          </div>
        </form>
      </div>
    </div>
  );
};

// =============================================================================
// AUDIT LOG
// =============================================================================
window.AuditSection = function AuditSection() {
  const [rows, setRows] = useStateCfg([]);
  const [loading, setLoading] = useStateCfg(true);
  const [filterAction, setFilterAction] = useStateCfg('');

  function load() {
    setLoading(true);
    const qs = filterAction ? '?action=' + encodeURIComponent(filterAction) : '';
    window.LQ.request('/audit' + qs).then((r) => { setRows(r || []); setLoading(false); });
  }
  useEffectCfg(load, [filterAction]);

  if (loading) return <div className="admin-loading">Loading…</div>;

  return (
    <>
      <div className="admin-toolbar">
        <p className="admin-section-intro" style={{ margin: 0 }}>{rows.length} entries · most recent first.</p>
        <select className="admin-input" value={filterAction} onChange={(e) => setFilterAction(e.target.value)}>
          <option value="">All actions</option>
          <option value="login">Login</option>
          <option value="logout">Logout</option>
          <option value="appointment_create">Appointment created</option>
          <option value="appointment_update">Appointment updated</option>
          <option value="order_create">Order created</option>
          <option value="order_update">Order updated</option>
          <option value="product_create">Product created</option>
          <option value="product_update">Product updated</option>
          <option value="user_create">User created</option>
          <option value="user_update">User updated</option>
          <option value="settings_update">Settings updated</option>
          <option value="photo_upload">Photo uploaded</option>
          <option value="backup_export">Backup export</option>
          <option value="backup_restore">Backup restore</option>
        </select>
      </div>

      <div className="admin-table-wrap">
        <table className="admin-table">
          <thead><tr><th>When</th><th>Who</th><th>Action</th><th>Entity</th><th>Details</th><th>IP</th></tr></thead>
          <tbody>
            {rows.map((r) => (
              <tr key={r.id}>
                <td className="admin-cell-sub">{window.LQ_fmtDateTime(r.created_at)}</td>
                <td>{r.user_email || <span className="admin-cell-sub">—</span>}</td>
                <td><span className="admin-chip">{r.action}</span></td>
                <td className="admin-cell-sub">{r.entity_type ? `${r.entity_type}#${r.entity_id ?? '—'}` : '—'}</td>
                <td className="admin-cell-sub" style={{ maxWidth: 240, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  {r.meta ? JSON.stringify(r.meta) : ''}
                </td>
                <td className="admin-cell-sub">{r.ip}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
};
