// Participants (database/41): one row per person on a verified booking, plus their participant form.
async function fetchParticipantsLive() {
  const { data, error } = await window.sb.from('event_participants')
    .select('*,orders(order_code,status,buyer_name),main_events(title)')
    .order('created_at', { ascending: true }).limit(2000);
  if (error) throw new Error(/does not exist|schema cache/i.test(error.message) ? 'Participants need database/41_participant_forms_and_welcome.sql to be run first.' : error.message);
  const emails = Array.from(new Set((data || []).map((r) => (r.email || '').toLowerCase()).filter(Boolean)));
  const prof = {};
  if (emails.length) { const { data: ps } = await window.sb.from('participant_profiles').select('*').in('email', emails); (ps || []).forEach((p) => { prof[p.email] = p; }); }
  return (data || []).filter((r) => !r.orders || r.orders.status === 'paid').map((r) => Object.assign({}, r, {
    name: ((r.first_name || '') + ' ' + (r.last_name || '')).trim(), orderRef: r.orders ? r.orders.order_code : '', bookedBy: r.orders ? r.orders.buyer_name : '',
    eventTitle: r.main_events ? r.main_events.title : '', profile: prof[(r.email || '').toLowerCase()] || null,
  }));
}
async function participantRpc(fn, args) {
  const { data, error } = await window.sb.rpc(fn, args);
  if (error) throw new Error(error.message);
  return data;
}
Object.assign(window, { fetchParticipantsLive, participantRpc });

function ParticipantsPanel() {
  const { Badge } = window.TheUpperDeckDesignSystem_4d3294;
  const { SearchInput, CustomSelect, Btn } = window.UdUI;
  const [rows, setRows] = React.useState(null);
  const [error, setError] = React.useState('');
  const [query, setQuery] = React.useState('');
  const [eventId, setEventId] = React.useState('');
  const [show, setShow] = React.useState('all');
  const [list, setList] = React.useState('people');
  const [busy, setBusy] = React.useState(null);
  const [msg, setMsg] = React.useState('');
  const [open, setOpen] = React.useState(null);
  const [linkFor, setLinkFor] = React.useState(null);
  const load = () => window.fetchParticipantsLive().then((r) => { setRows(r); if (!eventId && r.length) setEventId(r[r.length - 1].main_event_id); }).catch((e) => { setError(e.message || 'Could not load participants.'); setRows([]); });
  React.useEffect(() => { load(); }, []);

  const events = Array.from(new Map((rows || []).map((r) => [r.main_event_id, r.eventTitle])).entries()).map(([value, label]) => ({ value, label: label || 'Event' }));
  const inEvent = (rows || []).filter((r) => !eventId || r.main_event_id === eventId);
  const linked = inEvent.filter((r) => r.order_id);
  const loose = inEvent.filter((r) => !r.order_id);
  const doneN = linked.filter((r) => r.form_submitted_at).length;
  const q = query.trim().toLowerCase();
  const match = (r) => !q || [r.name, r.email, r.orderRef, r.cert_name, r.bookedBy].join(' ').toLowerCase().includes(q);
  const base = show === 'loose' ? loose : linked.filter((r) => show === 'all' || (show === 'done' ? r.form_submitted_at : !r.form_submitted_at));
  const none = (s) => !s || /^\s*(none|n\/?a|no|nil|-)\s*\.?\s*$/i.test(s);
  const subset = base.filter(match).filter((r) => {
    if (list === 'food') return r.form_submitted_at && !none(r.diet);
    if (list === 'medical') return r.form_submitted_at && (!none(r.health) || !none(r.medication));
    if (list === 'photo') return r.form_submitted_at && r.photo_ok === false;
    if (list === 'certs' || list === 'emergency') return !!r.form_submitted_at;
    return true;
  });
  const course = (t) => ({ imc: 'IMC only', hybrid: 'Hybrid only', combo: 'IMC + Hybrid' }[t] || '—');
  const when = (iso) => iso ? new Date(iso).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';

  async function act(r, kind) {
    const label = kind === 'welcome' ? 'Resend the welcome email to ' : 'Send the form reminder to ';
    if (!(await window.udConfirm(label + r.name + ' (' + r.email + ')?', { title: kind === 'welcome' ? 'Resend welcome?' : 'Send form reminder?', okLabel: 'Send', danger: false }))) return;
    setBusy(r.id + kind); setMsg('');
    try {
      const res = await window.participantRpc(kind === 'welcome' ? 'admin_resend_welcome' : 'admin_send_form_reminder', { p_participant: r.id });
      setMsg(res === 'sent' ? 'Sent to ' + r.email + '.' : res === 'already_submitted' ? r.name + ' already sent their form.' : 'Could not send: ' + res);
      await load();
    } catch (e) { setMsg(e.message); }
    setBusy(null);
  }
  async function linkTo(target) {
    setBusy('link');
    try { await window.participantRpc('admin_link_participant_form', { p_loose: linkFor.id, p_target: target.id }); setMsg('Form linked to ' + target.name + '.'); setLinkFor(null); await load(); }
    catch (e) { setMsg(e.message); }
    setBusy(null);
  }

  const arr = (a) => (a || []).join('; ');
  function exportCsv() {
    const head = ['Booking ref', 'Booked by', 'Course', 'Name', 'Email', 'Form sent', 'Certificate name', 'Mobile', 'Age range', 'Gender', 'Based in', 'Roles', 'How they train', 'Workplace', 'Years in field', 'Work settings', 'Weekly clients', 'Works with', 'Fitness qualifications', 'Other qualifications', 'Why joining', 'Heard from', 'Future interest', 'Health', 'Medication', 'Diet', 'Emergency contact', 'Relationship', 'Emergency mobile', 'Photos OK'];
    const lines = [head].concat(base.filter(match).map((r) => { const p = r.profile || {}; return [r.orderRef, r.bookedBy, course(r.course_type), r.name, r.email, r.form_submitted_at || '', r.cert_name, p.mobile, p.age_range, p.gender, p.based_in, arr(p.roles), arr(p.train_styles), p.workplace, p.years_in_field, arr(p.work_settings), p.weekly_clients, arr(p.client_types), p.fitness_quals, p.other_quals, arr(r.goals), arr(r.heard_from), arr(p.future_interest), r.health, r.medication, r.diet, r.ec_name, r.ec_relation, r.ec_phone, r.photo_ok == null ? '' : r.photo_ok ? 'Yes' : 'No']; }));
    const csv = lines.map((l) => l.map((v) => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"').join(',')).join('\n');
    const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([csv], { type: 'text/csv' })); a.download = 'participants.csv'; a.click();
  }

  const cell = { padding: '12px 16px', verticalAlign: 'top' };
  const sub = { color: 'var(--text-muted)', fontSize: 'var(--text-xs)', marginTop: 2 };
  const person = (r) => <td style={cell}><div style={{ fontWeight: 600 }}>{r.name || '—'}{r.is_booker && <span style={{ ...sub, marginLeft: 6 }}>Booker</span>}</div><div style={sub}>{r.email}</div></td>;
  const COLS = {
    people: ['Person', 'Booking', 'Course', 'Welcome email', 'Form', ''],
    certs: ['Person', 'Name on certificate', 'Course'],
    food: ['Person', 'Dietary restrictions or allergies'],
    medical: ['Person', 'Injury or condition', 'Medication'],
    emergency: ['Person', 'Emergency contact', 'Relationship', 'Mobile'],
    photo: ['Person', 'Booking'],
  };
  const row = (r) => {
    if (list === 'certs') return <>{person(r)}<td style={{ ...cell, fontWeight: 600 }}>{r.cert_name}</td><td style={cell}>{course(r.course_type)}</td></>;
    if (list === 'food') return <>{person(r)}<td style={{ ...cell, whiteSpace: 'pre-wrap' }}>{r.diet}</td></>;
    if (list === 'medical') return <>{person(r)}<td style={{ ...cell, whiteSpace: 'pre-wrap' }}>{r.health}</td><td style={{ ...cell, whiteSpace: 'pre-wrap' }}>{r.medication}</td></>;
    if (list === 'emergency') return <>{person(r)}<td style={cell}>{r.ec_name}</td><td style={cell}>{r.ec_relation}</td><td style={cell}><a href={'tel:' + r.ec_phone} style={{ color: 'inherit' }}>{r.ec_phone}</a></td></>;
    if (list === 'photo') return <>{person(r)}<td style={cell}>{r.orderRef}</td></>;
    return <>{person(r)}
      <td style={cell}>{r.order_id ? <><div style={{ fontWeight: 600 }}>{r.orderRef}</div><div style={sub}>by {r.bookedBy}</div></> : <Badge tone="warning">Needs linking</Badge>}</td>
      <td style={cell}>{course(r.course_type)}</td>
      <td style={cell}>{r.order_id ? (r.welcome_sent_at ? (/^failed/.test(r.welcome_status || '') ? <Badge tone="error">Failed</Badge> : <><Badge tone="info">Sent</Badge><div style={sub}>{when(r.welcome_sent_at)}</div></>) : <Badge tone="default">Not sent</Badge>) : '—'}</td>
      <td style={cell}>{r.form_submitted_at ? <><Badge tone="success">Submitted</Badge><div style={sub}>{when(r.form_submitted_at)}</div></> : <><Badge tone="warning">Pending</Badge>{r.form_reminder_sent_at && <div style={sub}>Reminded {when(r.form_reminder_sent_at)}</div>}</>}</td>
      <td style={{ ...cell, whiteSpace: 'nowrap' }}><div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        {r.form_submitted_at && <Btn size="sm" variant="ghost" onClick={() => setOpen(r)}>View form</Btn>}
        {!r.order_id && <Btn size="sm" onClick={() => setLinkFor(r)}>Link to booking</Btn>}
        {r.order_id && !r.form_submitted_at && <Btn size="sm" variant="ghost" onClick={() => act(r, 'reminder')} disabled={busy === r.id + 'reminder'}>{busy === r.id + 'reminder' ? 'Sending…' : 'Send reminder'}</Btn>}
        {r.order_id && <Btn size="sm" variant="ghost" onClick={() => act(r, 'welcome')} disabled={busy === r.id + 'welcome'}>{busy === r.id + 'welcome' ? 'Sending…' : 'Resend welcome'}</Btn>}
      </div></td></>;
  };

  const QA = (label, val) => (val == null || val === '' || (Array.isArray(val) && !val.length)) ? null : (
    <div style={{ display: 'grid', gap: 2, padding: '10px 0', borderTop: '1px solid var(--border-default)' }}>
      <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
      <div style={{ whiteSpace: 'pre-wrap' }}>{Array.isArray(val) ? val.join(', ') : val === true ? 'Yes' : val === false ? 'No' : val}</div>
    </div>);
  const head = (t) => <h4 style={{ margin: '18px 0 4px', fontFamily: 'var(--font-display)', fontSize: 'var(--text-md)' }}>{t}</h4>;
  const modal = (content, onClose, w) => ReactDOM.createPortal(
    <div className="ud-overlay" onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 24 }}>
      <div className="ud-modal" onClick={(e) => e.stopPropagation()} style={{ width: 'min(' + (w || 620) + 'px, 100%)', boxSizing: 'border-box', maxHeight: '88vh', overflowY: 'auto', background: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', padding: 24, fontSize: 'var(--text-sm)' }}>{content}
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}><Btn onClick={onClose}>Close</Btn></div></div>
    </div>, document.body);

  return (
    <div>
      <div className="ud-tablewrap" style={{ display: 'flex', gap: 12, marginBottom: 12, flexWrap: 'wrap', alignItems: 'center' }}>
        {events.length > 1 && <CustomSelect value={eventId} onChange={(v) => setEventId(v || '')} placeholder="All events" width={240} options={events} />}
        <SearchInput placeholder="Search name, email, ref…" value={query} onChange={setQuery} width={220} />
        <CustomSelect value={show} onChange={(v) => setShow(v || 'all')} placeholder="Everyone" width={170} options={[{ value: 'all', label: 'Everyone' }, { value: 'pending', label: 'Form pending' }, { value: 'done', label: 'Form submitted' }, { value: 'loose', label: 'Needs linking (' + loose.length + ')' }]} />
        <CustomSelect value={list} onChange={(v) => setList(v || 'people')} placeholder="People" width={200} options={[{ value: 'people', label: 'People' }, { value: 'certs', label: 'Certificate names' }, { value: 'food', label: 'Food restrictions' }, { value: 'medical', label: 'Medical notes' }, { value: 'emergency', label: 'Emergency contacts' }, { value: 'photo', label: 'No photos' }]} />
        <Btn onClick={exportCsv}>Export CSV</Btn>
      </div>
      <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)', marginBottom: 16, maxWidth: 760, lineHeight: 1.5 }}>
        {linked.length ? <><b style={{ color: 'var(--text-primary)' }}>{doneN} of {linked.length}</b> participants have sent their form. </> : null}
        Everyone on a verified booking gets a welcome email with their own form link. One reminder goes out 3 days later if the form is still empty. Forms sent without a matching booking show under Needs linking.
      </div>
      {msg && <div onClick={() => setMsg('')} style={{ marginBottom: 12, padding: '10px 14px', borderRadius: 'var(--radius-md)', background: 'var(--bg-sunken)', border: '1px solid var(--border-default)', fontSize: 'var(--text-sm)', cursor: 'pointer' }}>{msg}</div>}
      {error && <div style={{ marginBottom: 12, padding: '10px 14px', borderRadius: 'var(--radius-md)', background: 'var(--status-error-bg)', color: 'var(--status-error)', fontSize: 'var(--text-sm)' }}>{error}</div>}
      <div style={{ background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', overflowX: 'auto' }}>
        {rows === null ? <window.UdSkeleton variant="table" /> : (
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 'var(--text-sm)', minWidth: list === 'people' ? 980 : 640 }}>
            <thead><tr style={{ textAlign: 'left', background: 'var(--bg-sunken)', color: 'var(--text-muted)', fontSize: 'var(--text-xs)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
              {COLS[list].map((h, i) => <th key={i} style={{ padding: '12px 16px', fontWeight: 600 }}>{h}</th>)}
            </tr></thead>
            <tbody>
              {subset.map((r) => <tr key={r.id} style={{ borderTop: '1px solid var(--border-default)' }}>{row(r)}</tr>)}
              {subset.length === 0 && <tr><td colSpan={COLS[list].length} style={{ padding: 32, textAlign: 'center', color: 'var(--text-muted)' }}>{list === 'people' ? 'No participants yet. People appear here once their booking is verified.' : 'Nothing to show yet.'}</td></tr>}
            </tbody>
          </table>
        )}
      </div>

      {open && modal(<>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-xl)', margin: '0 0 4px' }}>{open.cert_name || open.name}</h3>
        <div style={{ color: 'var(--text-muted)', marginBottom: 8 }}>{open.email} · {open.orderRef || 'Not linked'} · {course(open.course_type)}</div>
        {head('Details')}{QA('Name on certificate', open.cert_name)}{QA('Mobile', open.profile && open.profile.mobile)}{QA('Age range', open.profile && open.profile.age_range)}{QA('Gender', open.profile && open.profile.gender)}{QA('Based in', open.profile && open.profile.based_in)}
        {head('Work')}{QA('Roles', open.profile && open.profile.roles)}{QA('How they train', open.profile && open.profile.train_styles)}{QA('Workplace', open.profile && open.profile.workplace)}{QA('Years in the field', open.profile && open.profile.years_in_field)}{QA('Works most often at', open.profile && open.profile.work_settings)}{QA('Clients per week', open.profile && open.profile.weekly_clients)}{QA('Works with', open.profile && open.profile.client_types)}{QA('Fitness qualifications', open.profile && open.profile.fitness_quals)}{QA('Coaching, combat or physio qualifications', open.profile && open.profile.other_quals)}
        {head('Goals')}{QA('Why joining', open.goals)}{QA('Heard about it from', open.heard_from)}{QA('Future programs', open.profile && open.profile.future_interest)}
        {head('Health and safety')}{QA('Injury or condition', open.health)}{QA('Medication', open.medication)}{QA('Diet', open.diet)}{QA('Emergency contact', [open.ec_name, open.ec_relation, open.ec_phone].filter(Boolean).join(' · '))}
        {head('Consent')}{QA('Data privacy', open.consent_privacy)}{QA('Health acknowledgement', open.consent_health)}{QA('Photos and videos', open.photo_ok)}
      </>, () => setOpen(null))}

      {linkFor && modal(<>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 'var(--text-xl)', margin: '0 0 4px' }}>Link form to a booking</h3>
        <div style={{ color: 'var(--text-muted)', marginBottom: 12 }}>{linkFor.cert_name} · {linkFor.email}. Pick the person on a booking this form belongs to. Their answers move over and this loose entry is removed.</div>
        <div style={{ display: 'grid', gap: 6 }}>
          {linked.filter((r) => !r.form_submitted_at).map((r) => (
            <button key={r.id} onClick={() => linkTo(r)} disabled={busy === 'link'} style={{ textAlign: 'left', padding: '10px 12px', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', background: 'white', cursor: 'pointer', font: 'inherit' }}>
              <b>{r.name}</b> <span style={{ color: 'var(--text-muted)' }}>· {r.email || 'no email'} · {r.orderRef}</span>
            </button>))}
          {!linked.some((r) => !r.form_submitted_at) && <div style={{ color: 'var(--text-muted)' }}>Everyone on a booking has already sent a form.</div>}
        </div>
      </>, () => setLinkFor(null), 560)}
    </div>
  );
}
window.ParticipantsPanel = ParticipantsPanel;
