/* global React */
const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC } = React;

// Shared helpers ============================================================
window.LQ_fmtINR = (n) => '₹' + (Number(n) || 0).toLocaleString('en-IN');
window.LQ_fmtDate = (s) => {
  if (!s) return '';
  const d = new Date(s);
  if (isNaN(d)) return s;
  return d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
};
window.LQ_fmtDateTime = (s) => {
  if (!s) return '';
  const d = new Date(s.replace(' ', 'T'));
  if (isNaN(d)) return s;
  return d.toLocaleString('en-IN', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit', hour12: true });
};
window.LQ_phone = (m) => (m || '').replace(/[^\d+]/g, '');
window.LQ_waLink = (mobile, msg) => `https://wa.me/${(mobile || '').replace(/^\+/, '').replace(/[^\d]/g, '')}?text=${encodeURIComponent(msg || '')}`;

// =============================================================================
// DASHBOARD
// =============================================================================
window.DashboardSection = function DashboardSection({ user }) {
  const [data, setData] = useStateC(null);
  const [err, setErr] = useStateC('');

  useEffectC(() => {
    window.LQ.request('/dashboard').then(setData).catch((e) => setErr(e.message));
  }, []);

  if (err) return <div className="admin-error">{err}</div>;
  if (!data) return <div className="admin-loading">Loading dashboard…</div>;

  const stats = data.stats || {};
  const cards = [
    { label: 'Today\'s Appointments', value: stats.today_appointments,    sub: 'Pending or confirmed' },
    { label: 'Pending Orders',        value: stats.pending_orders,        sub: 'Need processing or shipping' },
    { label: 'Refill Due',            value: stats.refill_due,            sub: 'Clients to remind', highlight: stats.refill_due > 0 },
    { label: 'Low Stock',             value: stats.low_stock,             sub: 'Press-ons running low', highlight: stats.low_stock > 0 },
    { label: 'Total Clients',         value: stats.total_clients,         sub: 'Lifetime' },
    { label: 'Completed This Week',   value: stats.completed_this_week,   sub: 'Mon onwards' },
  ];

  return (
    <>
      <p className="admin-greeting">Welcome back, {user.name.split(' ')[0]}.</p>

      <div className="admin-stats-grid">
        {cards.map((c) => (
          <div key={c.label} className={`admin-stat-card ${c.highlight ? 'highlight' : ''}`}>
            <div className="admin-stat-label">{c.label}</div>
            <div className="admin-stat-value">{c.value ?? 0}</div>
            <div className="admin-stat-sub">{c.sub}</div>
          </div>
        ))}
      </div>

      <div className="admin-two-col">
        <div className="admin-panel">
          <div className="admin-panel-head">
            <h3>Upcoming Appointments</h3>
          </div>
          {!data.upcoming || data.upcoming.length === 0 ? (
            <div className="admin-empty-mini">No upcoming bookings.</div>
          ) : (
            <ul className="admin-mini-list">
              {data.upcoming.map((a) => (
                <li key={a.id}>
                  <div>
                    <strong>{a.name}</strong>
                    <span className="admin-mini-meta">· {a.service}</span>
                  </div>
                  <div className="admin-mini-meta">
                    {window.LQ_fmtDate(a.appt_date)} · {a.appt_time}
                    <span className={`admin-badge ${a.status}`}>{a.status}</span>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>

        <div className="admin-panel">
          <div className="admin-panel-head">
            <h3>Recent Orders</h3>
          </div>
          {!data.recent_orders || data.recent_orders.length === 0 ? (
            <div className="admin-empty-mini">No orders yet.</div>
          ) : (
            <ul className="admin-mini-list">
              {data.recent_orders.map((o) => (
                <li key={o.id}>
                  <div>
                    <strong>{o.customer_name}</strong>
                    <span className="admin-mini-meta">· {o.product_name}</span>
                  </div>
                  <div className="admin-mini-meta">
                    {window.LQ_fmtINR(o.total)}
                    <span className={`admin-badge ${o.status}`}>{o.status}</span>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
    </>
  );
};

// =============================================================================
// APPOINTMENTS
// =============================================================================
const SERVICES = ['Gel Polish', 'Nail Art', 'Nail Extensions', 'Gel Extensions', 'Acrylic Extensions', 'Permanent Extensions', 'Manicure', 'Pedicure', 'Builder Gel', 'Refill'];
const TIME_SLOTS = ['10:00 AM', '11:00 AM', '12:00 PM', '1:00 PM', '2:00 PM', '3:00 PM', '4:00 PM', '5:00 PM', '6:00 PM', '7:00 PM', '8:00 PM'];

window.AppointmentsSection = function AppointmentsSection() {
  const [list, setList] = useStateC([]);
  const [loading, setLoading] = useStateC(true);
  const [filterDate, setFilterDate] = useStateC('');
  const [filterStatus, setFilterStatus] = useStateC('');
  const [showAdd, setShowAdd] = useStateC(false);
  const [editing, setEditing] = useStateC(null);

  function load() {
    setLoading(true);
    const qs = filterStatus ? '?status=' + filterStatus : '';
    window.LQ.request('/appointments' + qs).then((r) => { setList(r || []); setLoading(false); }).catch(() => setLoading(false));
  }
  useEffectC(load, [filterStatus]);

  const filtered = useMemoC(() => {
    return filterDate ? list.filter((a) => a.appt_date === filterDate) : list;
  }, [list, filterDate]);

  async function setStatus(id, status) {
    await window.LQ.request(`/appointments/${id}`, { method: 'PATCH', body: { status } });
    load();
  }

  async function del(id) {
    if (!confirm('Delete this appointment?')) return;
    await window.LQ.request(`/appointments/${id}`, { method: 'DELETE' });
    load();
  }

  function downloadIcs(id) {
    window.LQ.downloadFile(`/ics/${id}`, `appointment-${id}.ics`);
  }
  function downloadAllIcs() {
    window.LQ.downloadFile('/ics', 'lacquery-appointments.ics');
  }

  return (
    <>
      <div className="admin-toolbar">
        <div className="admin-toolbar-filters">
          <select className="admin-input" value={filterStatus} onChange={(e) => setFilterStatus(e.target.value)}>
            <option value="">All status</option>
            <option value="pending">Pending</option>
            <option value="confirmed">Confirmed</option>
            <option value="completed">Completed</option>
            <option value="cancelled">Cancelled</option>
            <option value="no_show">No Show</option>
          </select>
          <input className="admin-input" type="date" value={filterDate} onChange={(e) => setFilterDate(e.target.value)} />
          {filterDate && <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setFilterDate('')}>Clear</button>}
        </div>
        <div className="admin-toolbar-actions">
          <button className="admin-btn admin-btn-ghost" onClick={downloadAllIcs}>Export to Calendar (.ics)</button>
          <button className="admin-btn admin-btn-primary" onClick={() => setShowAdd(true)}>+ New / Walk-in</button>
        </div>
      </div>

      {loading ? <div className="admin-loading">Loading…</div> :
       filtered.length === 0 ? <div className="admin-empty">No appointments found.</div> :
       <div className="admin-table-wrap">
         <table className="admin-table">
           <thead>
             <tr><th>Name</th><th>Service</th><th>Date · Time</th><th>Source</th><th>Status</th><th>Actions</th></tr>
           </thead>
           <tbody>
             {filtered.map((a) => (
               <tr key={a.id}>
                 <td>
                   <div className="admin-cell-strong">{a.name}</div>
                   <div className="admin-cell-sub">{a.mobile}</div>
                 </td>
                 <td>{a.service}</td>
                 <td>
                   <div>{window.LQ_fmtDate(a.appt_date)}</div>
                   <div className="admin-cell-sub">{a.appt_time}</div>
                 </td>
                 <td><span className="admin-chip">{a.source}</span></td>
                 <td><span className={`admin-badge ${a.status}`}>{a.status}</span></td>
                 <td>
                   <div className="admin-row-actions">
                     {a.status === 'pending' && <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setStatus(a.id, 'confirmed')}>Confirm</button>}
                     {(a.status === 'pending' || a.status === 'confirmed') && <>
                       <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setStatus(a.id, 'completed')}>Done</button>
                       <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setStatus(a.id, 'no_show')}>No-show</button>
                     </>}
                     <a className="admin-btn admin-btn-ghost admin-btn-sm" href={window.LQ_waLink(a.mobile, `Hi ${a.name}, this is Lacquery Nails — confirming your ${a.service} on ${window.LQ_fmtDate(a.appt_date)} at ${a.appt_time}.`)} target="_blank" rel="noopener">WA</a>
                     <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => downloadIcs(a.id)}>.ics</button>
                     <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setEditing(a)}>Edit</button>
                     <button className="admin-btn admin-btn-ghost admin-btn-sm admin-btn-danger" onClick={() => del(a.id)}>×</button>
                   </div>
                 </td>
               </tr>
             ))}
           </tbody>
         </table>
       </div>
      }

      {(showAdd || editing) && (
        <window.AppointmentModal
          appt={editing}
          onClose={() => { setShowAdd(false); setEditing(null); }}
          onSaved={() => { setShowAdd(false); setEditing(null); load(); }}
        />
      )}
    </>
  );
};

window.AppointmentModal = function AppointmentModal({ appt, onClose, onSaved }) {
  const isEdit = !!appt;
  const today = new Date().toISOString().slice(0, 10);
  const [form, setForm] = useStateC({
    name: appt?.name || '',
    mobile: appt?.mobile || '',
    email: appt?.email || '',
    service: appt?.service || SERVICES[0],
    appt_date: appt?.appt_date || today,
    appt_time: appt?.appt_time || TIME_SLOTS[2],
    guests: appt?.guests || 1,
    status: appt?.status || 'pending',
    source: appt?.source || 'walk_in',
    price: appt?.price || '',
    notes: appt?.notes || '',
  });
  const [saving, setSaving] = useStateC(false);
  const [err, setErr] = useStateC('');

  async function save(e) {
    e.preventDefault();
    setSaving(true); setErr('');
    try {
      const body = { ...form };
      if (body.price === '') body.price = null; else body.price = Number(body.price);
      body.guests = Number(body.guests);
      if (isEdit) await window.LQ.request(`/appointments/${appt.id}`, { method: 'PATCH', body });
      else await window.LQ.request('/appointments', { method: 'POST', body });
      onSaved();
    } catch (e) {
      setErr(e.message);
    } finally {
      setSaving(false);
    }
  }

  function set(k, v) { setForm((f) => ({ ...f, [k]: v })); }

  return (
    <div className="admin-modal-overlay" onClick={onClose}>
      <div className="admin-modal" onClick={(e) => e.stopPropagation()}>
        <div className="admin-modal-head">
          <h3>{isEdit ? 'Edit Appointment' : 'New / Walk-in Appointment'}</h3>
          <button className="admin-modal-close" onClick={onClose} aria-label="Close">×</button>
        </div>
        <form onSubmit={save} className="admin-modal-body">
          <div className="admin-form-grid">
            <div>
              <label className="admin-label">Name</label>
              <input className="admin-input" required value={form.name} onChange={(e) => set('name', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Mobile</label>
              <input className="admin-input" required value={form.mobile} onChange={(e) => set('mobile', e.target.value)} placeholder="+91…" />
            </div>
            <div>
              <label className="admin-label">Email (optional)</label>
              <input className="admin-input" type="email" value={form.email} onChange={(e) => set('email', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Service</label>
              <select className="admin-input" value={form.service} onChange={(e) => set('service', e.target.value)}>
                {SERVICES.map((s) => <option key={s}>{s}</option>)}
              </select>
            </div>
            <div>
              <label className="admin-label">Date</label>
              <input className="admin-input" type="date" required value={form.appt_date} onChange={(e) => set('appt_date', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Time</label>
              <select className="admin-input" value={form.appt_time} onChange={(e) => set('appt_time', e.target.value)}>
                {TIME_SLOTS.map((s) => <option key={s}>{s}</option>)}
              </select>
            </div>
            <div>
              <label className="admin-label">Guests</label>
              <input className="admin-input" type="number" min="1" max="10" value={form.guests} onChange={(e) => set('guests', e.target.value)} />
            </div>
            <div>
              <label className="admin-label">Price (optional)</label>
              <input className="admin-input" type="number" min="0" value={form.price} onChange={(e) => set('price', e.target.value)} placeholder="e.g. 1499" />
            </div>
            <div>
              <label className="admin-label">Status</label>
              <select className="admin-input" value={form.status} onChange={(e) => set('status', e.target.value)}>
                <option value="pending">Pending</option>
                <option value="confirmed">Confirmed</option>
                <option value="completed">Completed</option>
                <option value="cancelled">Cancelled</option>
                <option value="no_show">No Show</option>
              </select>
            </div>
            <div>
              <label className="admin-label">Source</label>
              <select className="admin-input" value={form.source} onChange={(e) => set('source', e.target.value)}>
                <option value="walk_in">Walk-in</option>
                <option value="phone">Phone</option>
                <option value="whatsapp">WhatsApp</option>
                <option value="online">Online</option>
                <option value="admin">Admin entry</option>
              </select>
            </div>
            <div className="admin-form-row-full">
              <label className="admin-label">Notes</label>
              <textarea className="admin-input" rows="2" value={form.notes} onChange={(e) => set('notes', e.target.value)} />
            </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…' : (isEdit ? 'Save changes' : 'Create')}</button>
          </div>
        </form>
      </div>
    </div>
  );
};

// =============================================================================
// CLIENTS
// =============================================================================
window.ClientsSection = function ClientsSection() {
  const [list, setList] = useStateC([]);
  const [filter, setFilter] = useStateC('');
  const [q, setQ] = useStateC('');
  const [loading, setLoading] = useStateC(true);
  const [drawerId, setDrawerId] = useStateC(null);

  function load() {
    setLoading(true);
    const params = new URLSearchParams();
    if (filter) params.set('filter', filter);
    if (q)      params.set('q', q);
    const qs = params.toString();
    window.LQ.request('/clients' + (qs ? '?' + qs : '')).then((r) => { setList(r || []); setLoading(false); }).catch(() => setLoading(false));
  }
  useEffectC(load, [filter]);

  function searchSubmit(e) { e.preventDefault(); load(); }

  function exportCsv() {
    if (!list.length) { alert('No clients to export.'); return; }
    const cols = ['id', 'name', 'mobile', 'email', 'total_visits', 'total_spend', 'no_show_count', 'last_visit_at', 'last_service', 'refill_due_at', 'tags', 'notes', 'created_at'];
    const escape = (v) => {
      if (v == null) return '';
      const s = Array.isArray(v) ? v.join('; ') : String(v);
      return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
    };
    const rows = [cols.join(','), ...list.map(c => cols.map(k => escape(c[k])).join(','))];
    // BOM so Excel opens UTF-8 correctly
    const blob = new Blob(['﻿' + rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'lacquery-clients-' + new Date().toISOString().slice(0, 10) + '.csv';
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  }

  return (
    <>
      <div className="admin-toolbar">
        <div className="admin-toolbar-filters">
          <button className={`admin-chip-btn ${filter === '' ? 'active' : ''}`} onClick={() => setFilter('')}>All</button>
          <button className={`admin-chip-btn ${filter === 'refill_due' ? 'active' : ''}`} onClick={() => setFilter('refill_due')}>Refill due</button>
          <button className={`admin-chip-btn ${filter === 'vip' ? 'active' : ''}`} onClick={() => setFilter('vip')}>VIP (3+ visits)</button>
        </div>
        <form className="admin-toolbar-actions" onSubmit={searchSubmit}>
          <input className="admin-input" placeholder="Search name, mobile, email" value={q} onChange={(e) => setQ(e.target.value)} />
          <button className="admin-btn admin-btn-ghost">Search</button>
          <button type="button" className="admin-btn admin-btn-ghost" onClick={exportCsv}>Download Excel (.csv)</button>
        </form>
      </div>

      {loading ? <div className="admin-loading">Loading…</div> :
       list.length === 0 ? <div className="admin-empty">No clients found.</div> :
       <div className="admin-table-wrap">
         <table className="admin-table">
           <thead>
             <tr><th>Name</th><th>Mobile</th><th>Visits</th><th>Spend</th><th>Last visit</th><th>Refill due</th><th>Actions</th></tr>
           </thead>
           <tbody>
             {list.map((c) => (
               <tr key={c.id}>
                 <td>
                   <div className="admin-cell-strong">{c.name}</div>
                   {c.email && <div className="admin-cell-sub">{c.email}</div>}
                 </td>
                 <td>{c.mobile}</td>
                 <td>{c.total_visits}</td>
                 <td>{window.LQ_fmtINR(c.total_spend)}</td>
                 <td>{window.LQ_fmtDate(c.last_visit_at)}{c.last_service && <div className="admin-cell-sub">{c.last_service}</div>}</td>
                 <td>{c.refill_due_at ? <span className={`admin-badge ${new Date(c.refill_due_at) <= new Date() && !c.refill_dismissed ? 'pending' : ''}`}>{window.LQ_fmtDate(c.refill_due_at)}</span> : <span className="admin-cell-sub">—</span>}</td>
                 <td>
                   <div className="admin-row-actions">
                     <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setDrawerId(c.id)}>View</button>
                     <a className="admin-btn admin-btn-ghost admin-btn-sm" href={window.LQ_waLink(c.mobile, `Hi ${c.name}!`)} target="_blank" rel="noopener">WA</a>
                   </div>
                 </td>
               </tr>
             ))}
           </tbody>
         </table>
       </div>
      }

      {drawerId && <window.ClientDrawer id={drawerId} onClose={() => setDrawerId(null)} onSaved={load} />}
    </>
  );
};

window.ClientDrawer = function ClientDrawer({ id, onClose, onSaved }) {
  const [data, setData] = useStateC(null);
  const [editing, setEditing] = useStateC(false);
  const [form, setForm] = useStateC(null);

  useEffectC(() => {
    window.LQ.request(`/clients/${id}/history`).then((d) => {
      setData(d);
      setForm({ name: d.client.name, mobile: d.client.mobile, email: d.client.email || '', notes: d.client.notes || '' });
    });
  }, [id]);

  async function save() {
    await window.LQ.request(`/clients/${id}`, { method: 'PATCH', body: form });
    const d = await window.LQ.request(`/clients/${id}/history`);
    setData(d); setEditing(false); onSaved && onSaved();
  }

  if (!data) return (
    <div className="admin-drawer-overlay" onClick={onClose}>
      <div className="admin-drawer" onClick={(e) => e.stopPropagation()}><div className="admin-loading">Loading…</div></div>
    </div>
  );

  const c = data.client;
  return (
    <div className="admin-drawer-overlay" onClick={onClose}>
      <div className="admin-drawer" onClick={(e) => e.stopPropagation()}>
        <div className="admin-drawer-head">
          <div>
            <h3 className="display">{c.name}</h3>
            <div className="admin-cell-sub">{c.mobile}{c.email ? ' · ' + c.email : ''}</div>
          </div>
          <button className="admin-modal-close" onClick={onClose}>×</button>
        </div>

        <div className="admin-drawer-stats">
          <div><span>Visits</span><strong>{c.total_visits}</strong></div>
          <div><span>Spend</span><strong>{window.LQ_fmtINR(c.total_spend)}</strong></div>
          <div><span>No-shows</span><strong>{c.no_show_count}</strong></div>
          <div><span>Last visit</span><strong>{window.LQ_fmtDate(c.last_visit_at) || '—'}</strong></div>
        </div>

        {!editing ? (
          <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => setEditing(true)}>Edit details</button>
        ) : (
          <div className="admin-form-grid" style={{ marginTop: 12 }}>
            <div><label className="admin-label">Name</label><input className="admin-input" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
            <div><label className="admin-label">Mobile</label><input className="admin-input" value={form.mobile} onChange={(e) => setForm({ ...form, mobile: e.target.value })} /></div>
            <div><label className="admin-label">Email</label><input className="admin-input" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} /></div>
            <div className="admin-form-row-full"><label className="admin-label">Notes</label><textarea className="admin-input" rows="2" value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></div>
            <div className="admin-form-row-full" style={{ display: 'flex', gap: 8 }}>
              <button className="admin-btn admin-btn-ghost" onClick={() => setEditing(false)}>Cancel</button>
              <button className="admin-btn admin-btn-primary" onClick={save}>Save</button>
            </div>
          </div>
        )}

        <div className="admin-drawer-section">
          <h4>Appointments ({data.appointments.length})</h4>
          {data.appointments.length === 0 ? <div className="admin-empty-mini">None.</div> :
           <ul className="admin-mini-list">
             {data.appointments.map((a) => (
               <li key={a.id}>
                 <div><strong>{a.service}</strong><span className="admin-mini-meta"> · {window.LQ_fmtDate(a.appt_date)} {a.appt_time}</span></div>
                 <span className={`admin-badge ${a.status}`}>{a.status}</span>
               </li>
             ))}
           </ul>}
        </div>

        <div className="admin-drawer-section">
          <h4>Orders ({data.orders.length})</h4>
          {data.orders.length === 0 ? <div className="admin-empty-mini">None.</div> :
           <ul className="admin-mini-list">
             {data.orders.map((o) => (
               <li key={o.id}>
                 <div><strong>{o.product_name}</strong><span className="admin-mini-meta"> · {o.order_code}</span></div>
                 <div>{window.LQ_fmtINR(o.total)} <span className={`admin-badge ${o.status}`}>{o.status}</span></div>
               </li>
             ))}
           </ul>}
        </div>
      </div>
    </div>
  );
};

// =============================================================================
// REMINDERS
// =============================================================================
window.RemindersSection = function RemindersSection() {
  const [data, setData] = useStateC(null);

  function load() {
    window.LQ.request('/reminders').then(setData);
  }
  useEffectC(load, []);

  async function markSent(type, id) {
    await window.LQ.request('/reminders/mark-sent', { method: 'POST', body: { type, appointment_id: id } });
    load();
  }

  async function sendRefill(clientId, sendEmail) {
    await window.LQ.request('/reminders/send-refill', { method: 'POST', body: { client_id: clientId, send_email: sendEmail } });
    load();
  }

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

  const total = (data.one_day?.length || 0) + (data.two_hour?.length || 0) + (data.refill?.length || 0);

  return (
    <>
      <p className="admin-section-intro">{total} reminders pending. Open WhatsApp to send each — pre-filled message included.</p>

      <div className="admin-panel">
        <div className="admin-panel-head">
          <h3>Tomorrow's Bookings (1-day reminder)</h3>
          <span className="admin-chip">{data.one_day.length}</span>
        </div>
        {data.one_day.length === 0 ? <div className="admin-empty-mini">None due.</div> :
          <ul className="admin-rem-list">
            {data.one_day.map((a) => (
              <li className="admin-rem-row" key={a.id}>
                <div className="admin-rem-info">
                  <div className="admin-rem-name">{a.name}</div>
                  <div className="admin-rem-meta">{a.mobile} · {a.service} · {a.appt_time}</div>
                </div>
                <div className="admin-rem-actions">
                  <a className="admin-btn admin-btn-ghost admin-btn-sm" target="_blank" rel="noopener"
                     href={window.LQ_waLink(a.mobile, `Hi ${a.name}! Just a friendly reminder — your ${a.service} appointment with Lacquery Nails is tomorrow at ${a.appt_time}. Reply to confirm or reschedule. ✨`)}>
                    WhatsApp
                  </a>
                  <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => markSent('1day', a.id)}>Mark sent</button>
                </div>
              </li>
            ))}
          </ul>
        }
      </div>

      <div className="admin-panel">
        <div className="admin-panel-head">
          <h3>Today's Bookings (2-hour reminder)</h3>
          <span className="admin-chip">{data.two_hour.length}</span>
        </div>
        {data.two_hour.length === 0 ? <div className="admin-empty-mini">None due.</div> :
          <ul className="admin-rem-list">
            {data.two_hour.map((a) => (
              <li className="admin-rem-row" key={a.id}>
                <div className="admin-rem-info">
                  <div className="admin-rem-name">{a.name}</div>
                  <div className="admin-rem-meta">{a.mobile} · {a.service} · {a.appt_time}</div>
                </div>
                <div className="admin-rem-actions">
                  <a className="admin-btn admin-btn-ghost admin-btn-sm" target="_blank" rel="noopener"
                     href={window.LQ_waLink(a.mobile, `Hi ${a.name}, see you in 2 hours at Lacquery Nails for your ${a.service} at ${a.appt_time}. Drop a pin if you need directions: maps.app.goo.gl/lacquery`)}>
                    WhatsApp
                  </a>
                  <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => markSent('2hr', a.id)}>Mark sent</button>
                </div>
              </li>
            ))}
          </ul>
        }
      </div>

      <div className="admin-panel">
        <div className="admin-panel-head">
          <h3>Refill Due (4-week extensions reminder)</h3>
          <span className="admin-chip">{data.refill.length}</span>
        </div>
        {data.refill.length === 0 ? <div className="admin-empty-mini">No refills due.</div> :
          <ul className="admin-rem-list">
            {data.refill.map((c) => (
              <li className="admin-rem-row" key={c.id}>
                <div className="admin-rem-info">
                  <div className="admin-rem-name">{c.name}</div>
                  <div className="admin-rem-meta">{c.mobile} · {c.last_service} · last visit {window.LQ_fmtDate(c.last_visit_at)}</div>
                </div>
                <div className="admin-rem-actions">
                  <a className="admin-btn admin-btn-ghost admin-btn-sm" target="_blank" rel="noopener"
                     href={window.LQ_waLink(c.mobile, `Hi ${c.name}! It's been a few weeks since your ${c.last_service} at Lacquery. Time for a refill? Reply to book your next slot. 💅`)}>
                    WhatsApp
                  </a>
                  {c.email && <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => sendRefill(c.id, true)}>Email + Done</button>}
                  <button className="admin-btn admin-btn-ghost admin-btn-sm" onClick={() => sendRefill(c.id, false)}>Mark done</button>
                </div>
              </li>
            ))}
          </ul>
        }
      </div>
    </>
  );
};
