// Admin panel — login, club membership requests (+ filled PDF download),
// events + competitors management, trails + GPX upload
const { useState: useStateAd, useEffect: useEffectAd } = React;

const adInput = {
  width: '100%', padding: '12px 14px', background: 'var(--bg)',
  color: 'var(--fg)', border: '1px solid var(--border)',
  fontFamily: 'JetBrains Mono, monospace', fontSize: 13, outline: 'none',
};
const adLabel = txt => (
  <label className="mono" style={{ display: 'block', fontSize: 10, color: 'var(--fg-dim)', letterSpacing: '0.16em', marginBottom: 6 }}>{txt.toUpperCase()}</label>
);
const adBtn = {
  padding: '10px 18px', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, fontWeight: 700,
  letterSpacing: '0.1em', background: 'var(--accent)', color: '#fff', border: '1px solid var(--accent)', cursor: 'pointer',
};
const adBtnGhost = { ...adBtn, background: 'transparent', color: 'var(--fg-dim)', border: '1px solid var(--border-bright)' };

function loadScriptOnce(src) {
  return new Promise((resolve, reject) => {
    if (document.querySelector(`script[src="${src}"]`)) return resolve();
    const s = document.createElement('script');
    s.src = src; s.onload = resolve; s.onerror = reject;
    document.head.appendChild(s);
  });
}

// ── Filled PDF download (draws member data over the official form) ──────────
// Coordinates are in PDF points (A4 = 595 x 842, origin bottom-left).
// Tune here if text lands off the dotted lines.
const PDF_COORDS = {
  member: {
    full_name: [152, 661], cnp: [70, 645.5], birth_date: [128, 630],
    address: [110, 614.5], phone: [95, 599], email: [80, 583.5],
    date: [90, 420],
  },
  guardian: {
    guardian_name: [265, 347], guardian_cnp: [70, 330.5], guardian_address: [110, 314],
    guardian_phone: [95, 297], guardian_email: [80, 280],
    minor_name: [283, 257], date: [90, 183],
  },
};

function fmtRoDate(iso) {
  if (!iso) return '';
  const [y, m, d] = iso.split('-');
  return `${d}.${m}.${y}`;
}

async function downloadMemberPdf(m) {
  await loadScriptOnce('https://unpkg.com/pdf-lib@1.17.1/dist/pdf-lib.min.js');
  await loadScriptOnce('https://unpkg.com/@pdf-lib/fontkit@1.1.1/dist/fontkit.umd.min.js');
  const { PDFDocument, rgb } = window.PDFLib;
  const [tplBytes, fontBytes] = await Promise.all([
    fetch('/assets/formular-inscriere.pdf').then(r => r.arrayBuffer()),
    fetch('/assets/DejaVuSans.ttf').then(r => r.arrayBuffer()),
  ]);
  const pdf = await PDFDocument.load(tplBytes);
  pdf.registerFontkit(window.fontkit);
  const font = await pdf.embedFont(fontBytes, { subset: true });
  const page = pdf.getPages()[0];
  const draw = (txt, [x, y]) => { if (txt) page.drawText(String(txt), { x, y, size: 9.5, font, color: rgb(0.12, 0.12, 0.12) }); };

  const c = PDF_COORDS.member;
  draw(m.full_name, c.full_name);
  draw(m.cnp, c.cnp);
  draw(fmtRoDate(m.birth_date), c.birth_date);
  draw(m.address, c.address);
  draw(m.phone, c.phone);
  draw(m.email, c.email);
  draw(fmtRoDate((m.created_at || '').slice(0, 10)), c.date);

  if (m.is_minor) {
    const g = PDF_COORDS.guardian;
    draw(m.guardian_name, g.guardian_name);
    draw(m.guardian_cnp, g.guardian_cnp);
    draw(m.guardian_address, g.guardian_address);
    draw(m.guardian_phone, g.guardian_phone);
    draw(m.guardian_email, g.guardian_email);
    draw(m.minor_name || m.full_name, g.minor_name);
    draw(fmtRoDate((m.created_at || '').slice(0, 10)), g.date);
  }

  const bytes = await pdf.save();
  const blob = new Blob([bytes], { type: 'application/pdf' });
  const a = document.createElement('a');
  a.href = URL.createObjectURL(blob);
  a.download = `formular-inscriere-${(m.full_name || 'membru').replace(/\s+/g, '-')}.pdf`;
  a.click();
  URL.revokeObjectURL(a.href);
}

// ── Login ───────────────────────────────────────────────────────────────────
function AdminLogin({ onLogin }) {
  const [email, setEmail] = useStateAd('');
  const [pass, setPass] = useStateAd('');
  const [err, setErr] = useStateAd(null);
  const [busy, setBusy] = useStateAd(false);

  const submit = async e => {
    e.preventDefault();
    setBusy(true); setErr(null);
    const { data, error } = await sb.auth.signInWithPassword({ email, password: pass });
    setBusy(false);
    if (error) setErr('Email sau parolă greșite.');
    else onLogin(data.session);
  };

  return (
    <section className="section" style={{ minHeight: '60vh' }}>
      <div className="container" style={{ maxWidth: 480 }}>
        <div className="eyebrow" style={{ marginBottom: 20 }}>/ admin</div>
        <h1 className="display display-lg" style={{ marginBottom: 40 }}>AUTENTIFICARE</h1>
        <form onSubmit={submit} style={{ background: 'var(--bg-2)', padding: 36, border: '1px solid var(--border)' }}>
          <div style={{ marginBottom: 20 }}>
            {adLabel('Email')}
            <input type="email" required value={email} onChange={e => setEmail(e.target.value)} style={adInput} />
          </div>
          <div style={{ marginBottom: 28 }}>
            {adLabel('Parolă')}
            <input type="password" required value={pass} onChange={e => setPass(e.target.value)} style={adInput} />
          </div>
          <button type="submit" disabled={busy} className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', opacity: busy ? 0.7 : 1 }}>
            {busy ? '...' : 'INTRĂ'} <span className="arrow">→</span>
          </button>
          {err && <p style={{ color: 'var(--accent-bright)', marginTop: 14, fontSize: 14 }}>{err}</p>}
        </form>
      </div>
    </section>
  );
}

// ── Members tab ─────────────────────────────────────────────────────────────
const MEMBER_STATUSES = ['nou', 'contactat', 'membru', 'respins'];

function AdminMembers() {
  const [rows, setRows] = useStateAd(null);
  const [open, setOpen] = useStateAd(null);

  const load = () => sb.from('members').select('*').order('created_at', { ascending: false })
    .then(({ data }) => setRows(data || []));
  useEffectAd(() => { load(); }, []);

  const setStatus = async (m, status) => {
    await sb.from('members').update({ status }).eq('id', m.id);
    load();
  };
  const remove = async m => {
    if (!confirm(`Ștergi cererea lui ${m.full_name}?`)) return;
    await sb.from('members').delete().eq('id', m.id);
    load();
  };

  if (rows === null) return <p className="mono" style={{ color: 'var(--fg-dim)' }}>Se încarcă...</p>;
  if (rows.length === 0) return <p style={{ color: 'var(--fg-dim)' }}>Nicio cerere de înscriere încă.</p>;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 1, background: 'var(--border)' }}>
      {rows.map(m => (
        <div key={m.id} style={{ background: 'var(--bg)', padding: '18px 24px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 200, cursor: 'pointer' }} onClick={() => setOpen(open === m.id ? null : m.id)}>
              <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 800, fontSize: 20, textTransform: 'uppercase' }}>
                {m.full_name} {m.is_minor && <span style={{ fontSize: 11, fontFamily: 'JetBrains Mono', background: 'var(--bg-3)', border: '1px solid var(--border-bright)', padding: '2px 8px', marginLeft: 8, verticalAlign: 'middle' }}>MINOR</span>}
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-dim)' }}>
                {new Date(m.created_at).toLocaleDateString('ro-RO')} · {m.phone} · {m.email}
              </div>
            </div>
            <select value={m.status} onChange={e => setStatus(m, e.target.value)} style={{ ...adInput, width: 130 }}>
              {MEMBER_STATUSES.map(s => <option key={s} value={s}>{s.toUpperCase()}</option>)}
            </select>
            <button style={adBtn} onClick={() => downloadMemberPdf(m)}>PDF ⬇</button>
            <button style={adBtnGhost} onClick={() => remove(m)}>✕</button>
          </div>
          {open === m.id && (
            <div className="mono" style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--border)', fontSize: 12, color: 'var(--fg-dim)', lineHeight: 2 }}>
              CNP: {m.cnp || '—'} · Născut: {fmtRoDate(m.birth_date) || '—'}<br />
              Domiciliu: {m.address || '—'}<br />
              Consimțăminte: regulament {m.declaration_consent ? '✓' : '✗'} · GDPR {m.gdpr_consent ? '✓' : '✗'}
              {m.is_minor && (<>
                <br />Tutore: {m.guardian_name || '—'} · CNP {m.guardian_cnp || '—'} · {m.guardian_phone || '—'} · {m.guardian_email || '—'}
                <br />Domiciliu tutore: {m.guardian_address || '—'}
              </>)}
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// ── Events tab ──────────────────────────────────────────────────────────────
const EMPTY_EVENT = { title: '', event_date: '', event_time: '', location: '', description: '', distance: '', categories: '', event_type: 'OPEN', registration_open: true, is_published: true };

function AdminEvents() {
  const [rows, setRows] = useStateAd(null);
  const [editing, setEditing] = useStateAd(null); // event object or 'new'
  const [form, setForm] = useStateAd(EMPTY_EVENT);
  const [regsFor, setRegsFor] = useStateAd(null);
  const [regs, setRegs] = useStateAd([]);
  const [newReg, setNewReg] = useStateAd({ full_name: '', phone: '', bike: '', category: '' });

  const load = () => sb.from('events').select('*').order('event_date', { ascending: false, nullsFirst: true })
    .then(({ data }) => setRows(data || []));
  useEffectAd(() => { load(); }, []);

  const loadRegs = evId => sb.from('event_registrations').select('*').eq('event_id', evId).order('created_at')
    .then(({ data }) => setRegs(data || []));

  const startEdit = ev => {
    setEditing(ev ? ev.id : 'new');
    setForm(ev ? { ...ev, event_date: ev.event_date || '', event_time: ev.event_time || '', location: ev.location || '', description: ev.description || '', distance: ev.distance || '', categories: ev.categories || '' } : EMPTY_EVENT);
  };

  const save = async e => {
    e.preventDefault();
    const payload = { ...form, event_date: form.event_date || null };
    delete payload.id; delete payload.created_at;
    if (editing === 'new') await sb.from('events').insert(payload);
    else await sb.from('events').update(payload).eq('id', editing);
    setEditing(null); load();
  };

  const remove = async ev => {
    if (!confirm(`Ștergi evenimentul „${ev.title}” (împreună cu toate înscrierile)?`)) return;
    await sb.from('events').delete().eq('id', ev.id);
    setRegsFor(null); load();
  };

  const addReg = async e => {
    e.preventDefault();
    await sb.from('event_registrations').insert({ ...newReg, event_id: regsFor, added_by_admin: true });
    setNewReg({ full_name: '', phone: '', bike: '', category: '' });
    loadRegs(regsFor);
  };
  const removeReg = async r => {
    if (!confirm(`Ștergi concurentul ${r.full_name}?`)) return;
    await sb.from('event_registrations').delete().eq('id', r.id);
    loadRegs(regsFor);
  };

  if (rows === null) return <p className="mono" style={{ color: 'var(--fg-dim)' }}>Se încarcă...</p>;

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <button style={adBtn} onClick={() => startEdit(null)}>+ EVENIMENT NOU</button>
      </div>

      {editing && (
        <form onSubmit={save} style={{ background: 'var(--bg-2)', border: '1px solid var(--accent)', padding: 28, marginBottom: 28 }}>
          <div className="form-2col" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 16, marginBottom: 16 }}>
            <div>{adLabel('Titlu')}<input required value={form.title} onChange={e => setForm({ ...form, title: e.target.value })} style={adInput} /></div>
            <div>{adLabel('Data')}<input type="date" value={form.event_date} onChange={e => setForm({ ...form, event_date: e.target.value })} style={{ ...adInput, colorScheme: 'dark' }} /></div>
            <div>{adLabel('Ora')}<input value={form.event_time} onChange={e => setForm({ ...form, event_time: e.target.value })} placeholder="10:00" style={adInput} /></div>
          </div>
          <div className="form-2col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16, marginBottom: 16 }}>
            <div>{adLabel('Locație')}<input value={form.location} onChange={e => setForm({ ...form, location: e.target.value })} style={adInput} /></div>
            <div>{adLabel('Distanță')}<input value={form.distance} onChange={e => setForm({ ...form, distance: e.target.value })} placeholder="38 KM" style={adInput} /></div>
            <div>{adLabel('Categorii (cu virgulă)')}<input value={form.categories} onChange={e => setForm({ ...form, categories: e.target.value })} placeholder="Hobby, Expert, Pro" style={adInput} /></div>
          </div>
          <div style={{ marginBottom: 16 }}>{adLabel('Descriere')}<textarea rows="4" value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} style={{ ...adInput, resize: 'vertical' }} /></div>
          <div style={{ display: 'flex', gap: 24, alignItems: 'center', marginBottom: 20, flexWrap: 'wrap' }}>
            <div>{adLabel('Tip')}
              <select value={form.event_type} onChange={e => setForm({ ...form, event_type: e.target.value })} style={{ ...adInput, width: 180 }}>
                <option value="OPEN">DESCHIS TUTUROR</option>
                <option value="MEMBERS">MEMBRI CLUB</option>
                <option value="COMP">COMPETIȚIE</option>
              </select>
            </div>
            <label className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)', display: 'flex', gap: 8, alignItems: 'center', cursor: 'pointer' }}>
              <input type="checkbox" checked={form.registration_open} onChange={e => setForm({ ...form, registration_open: e.target.checked })} style={{ accentColor: 'var(--accent)' }} /> ÎNSCRIERI DESCHISE
            </label>
            <label className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)', display: 'flex', gap: 8, alignItems: 'center', cursor: 'pointer' }}>
              <input type="checkbox" checked={form.is_published} onChange={e => setForm({ ...form, is_published: e.target.checked })} style={{ accentColor: 'var(--accent)' }} /> PUBLICAT PE SITE
            </label>
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <button type="submit" style={adBtn}>SALVEAZĂ</button>
            <button type="button" style={adBtnGhost} onClick={() => setEditing(null)}>ANULEAZĂ</button>
          </div>
        </form>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 1, background: 'var(--border)' }}>
        {rows.map(ev => (
          <div key={ev.id} style={{ background: 'var(--bg)', padding: '18px 24px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
              <div style={{ flex: 1, minWidth: 220 }}>
                <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 800, fontSize: 20, textTransform: 'uppercase' }}>
                  {ev.title}
                  {!ev.is_published && <span style={{ fontSize: 10, fontFamily: 'JetBrains Mono', border: '1px solid var(--border-bright)', color: 'var(--fg-dim)', padding: '2px 8px', marginLeft: 10, verticalAlign: 'middle' }}>NEPUBLICAT</span>}
                </div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--fg-dim)' }}>
                  {[ev.event_date, ev.event_time, ev.location, ev.event_type].filter(Boolean).join(' · ')}
                </div>
              </div>
              <button style={adBtnGhost} onClick={() => { if (regsFor === ev.id) { setRegsFor(null); } else { setRegsFor(ev.id); loadRegs(ev.id); } }}>CONCURENȚI</button>
              <button style={adBtnGhost} onClick={() => startEdit(ev)}>EDIT</button>
              <button style={adBtnGhost} onClick={() => remove(ev)}>✕</button>
            </div>

            {regsFor === ev.id && (
              <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border)' }}>
                <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.16em', marginBottom: 12 }}>
                  LISTA CONCURENȚILOR [ {regs.length} ]
                </div>
                {regs.length > 0 && (
                  <div style={{ overflowX: 'auto', marginBottom: 16 }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 640 }}>
                      <thead>
                        <tr>
                          {['#', 'NUME', 'TELEFON', 'EMAIL', 'MOTOR', 'CATEGORIE', 'SURSĂ', ''].map(h => (
                            <th key={h} className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)', letterSpacing: '0.14em', textAlign: 'left', padding: '8px 10px', borderBottom: '1px solid var(--border)' }}>{h}</th>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {regs.map((r, i) => (
                          <tr key={r.id}>
                            <td className="mono" style={{ padding: '8px 10px', fontSize: 12, color: 'var(--accent)' }}>{i + 1}</td>
                            <td style={{ padding: '8px 10px', fontSize: 14, fontWeight: 600 }}>{r.full_name}</td>
                            <td className="mono" style={{ padding: '8px 10px', fontSize: 12, color: 'var(--fg-dim)' }}>{r.phone || '—'}</td>
                            <td className="mono" style={{ padding: '8px 10px', fontSize: 12, color: 'var(--fg-dim)' }}>{r.email || '—'}</td>
                            <td className="mono" style={{ padding: '8px 10px', fontSize: 12, color: 'var(--fg-dim)' }}>{r.bike || '—'}</td>
                            <td className="mono" style={{ padding: '8px 10px', fontSize: 12, color: 'var(--fg-dim)' }}>{r.category || '—'}</td>
                            <td className="mono" style={{ padding: '8px 10px', fontSize: 11, color: 'var(--fg-dimmer)' }}>{r.added_by_admin ? 'ADMIN' : 'SITE'}</td>
                            <td style={{ padding: '8px 10px' }}><button style={{ ...adBtnGhost, padding: '4px 10px' }} onClick={() => removeReg(r)}>✕</button></td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
                <form onSubmit={addReg} style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'flex-end' }}>
                  <div style={{ flex: 2, minWidth: 160 }}>{adLabel('Nume')}<input required value={newReg.full_name} onChange={e => setNewReg({ ...newReg, full_name: e.target.value })} style={adInput} /></div>
                  <div style={{ flex: 1, minWidth: 120 }}>{adLabel('Telefon')}<input value={newReg.phone} onChange={e => setNewReg({ ...newReg, phone: e.target.value })} style={adInput} /></div>
                  <div style={{ flex: 1, minWidth: 120 }}>{adLabel('Motor')}<input value={newReg.bike} onChange={e => setNewReg({ ...newReg, bike: e.target.value })} style={adInput} /></div>
                  <div style={{ flex: 1, minWidth: 120 }}>{adLabel('Categorie')}<input value={newReg.category} onChange={e => setNewReg({ ...newReg, category: e.target.value })} style={adInput} /></div>
                  <button type="submit" style={adBtn}>+ ADAUGĂ</button>
                </form>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Trails tab ──────────────────────────────────────────────────────────────
const EMPTY_TRAIL = { name: '', zone: '', description: '', distance_km: '', elevation_m: '', difficulty: 'MID', duration: '', is_published: true, sort_order: 0 };

function AdminTrails() {
  const [rows, setRows] = useStateAd(null);
  const [editing, setEditing] = useStateAd(null);
  const [form, setForm] = useStateAd(EMPTY_TRAIL);
  const [gpxFile, setGpxFile] = useStateAd(null);
  const [busy, setBusy] = useStateAd(false);

  const load = () => sb.from('trails').select('*').order('sort_order').order('created_at')
    .then(({ data }) => setRows(data || []));
  useEffectAd(() => { load(); }, []);

  const startEdit = tr => {
    setEditing(tr ? tr.id : 'new');
    setGpxFile(null);
    setForm(tr ? { ...tr, distance_km: tr.distance_km ?? '', elevation_m: tr.elevation_m ?? '', zone: tr.zone || '', description: tr.description || '', duration: tr.duration || '' } : EMPTY_TRAIL);
  };

  const save = async e => {
    e.preventDefault();
    setBusy(true);
    let gpx_path = form.gpx_path || null;
    if (gpxFile) {
      const path = `${Date.now()}-${gpxFile.name.replace(/[^a-zA-Z0-9.\-_]/g, '_')}`;
      const { error } = await sb.storage.from('gpx').upload(path, gpxFile, { contentType: 'application/gpx+xml' });
      if (error) { alert('Eroare la upload GPX: ' + error.message); setBusy(false); return; }
      gpx_path = path;
    }
    const payload = {
      name: form.name, zone: form.zone || null, description: form.description || null,
      distance_km: form.distance_km === '' ? null : Number(form.distance_km),
      elevation_m: form.elevation_m === '' ? null : Number(form.elevation_m),
      difficulty: form.difficulty, duration: form.duration || null,
      is_published: form.is_published, sort_order: Number(form.sort_order) || 0,
      gpx_path,
    };
    if (editing === 'new') await sb.from('trails').insert(payload);
    else await sb.from('trails').update(payload).eq('id', editing);
    setBusy(false); setEditing(null); load();
  };

  const remove = async tr => {
    if (!confirm(`Ștergi traseul „${tr.name}”?`)) return;
    if (tr.gpx_path) await sb.storage.from('gpx').remove([tr.gpx_path]);
    await sb.from('trails').delete().eq('id', tr.id);
    load();
  };

  if (rows === null) return <p className="mono" style={{ color: 'var(--fg-dim)' }}>Se încarcă...</p>;

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <button style={adBtn} onClick={() => startEdit(null)}>+ TRASEU NOU</button>
      </div>

      {editing && (
        <form onSubmit={save} style={{ background: 'var(--bg-2)', border: '1px solid var(--accent)', padding: 28, marginBottom: 28 }}>
          <div className="form-2col" style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, marginBottom: 16 }}>
            <div>{adLabel('Nume traseu')}<input required value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} style={adInput} /></div>
            <div>{adLabel('Zonă')}<input value={form.zone} onChange={e => setForm({ ...form, zone: e.target.value })} placeholder="Straja / Parâng..." style={adInput} /></div>
          </div>
          <div className="form-2col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 16, marginBottom: 16 }}>
            <div>{adLabel('KM')}<input type="number" step="0.1" value={form.distance_km} onChange={e => setForm({ ...form, distance_km: e.target.value })} style={adInput} /></div>
            <div>{adLabel('Urcare (m)')}<input type="number" value={form.elevation_m} onChange={e => setForm({ ...form, elevation_m: e.target.value })} style={adInput} /></div>
            <div>{adLabel('Durată')}<input value={form.duration} onChange={e => setForm({ ...form, duration: e.target.value })} placeholder="3h 30m" style={adInput} /></div>
            <div>{adLabel('Dificultate')}
              <select value={form.difficulty} onChange={e => setForm({ ...form, difficulty: e.target.value })} style={adInput}>
                {['EASY', 'MID', 'HARD'].map(d => <option key={d} value={d}>{d}</option>)}
              </select>
            </div>
          </div>
          <div style={{ marginBottom: 16 }}>{adLabel('Descriere scurtă')}<input value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} style={adInput} /></div>
          <div style={{ display: 'flex', gap: 24, alignItems: 'center', marginBottom: 20, flexWrap: 'wrap' }}>
            <div>
              {adLabel('Fișier GPX (de pe Garmin)')}
              <input type="file" accept=".gpx" onChange={e => setGpxFile(e.target.files[0] || null)} className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)' }} />
              {form.gpx_path && !gpxFile && <div className="mono" style={{ fontSize: 11, color: 'var(--fg-dimmer)', marginTop: 6 }}>Existent: {form.gpx_path}</div>}
            </div>
            <label className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)', display: 'flex', gap: 8, alignItems: 'center', cursor: 'pointer' }}>
              <input type="checkbox" checked={form.is_published} onChange={e => setForm({ ...form, is_published: e.target.checked })} style={{ accentColor: 'var(--accent)' }} /> PUBLICAT
            </label>
            <div>{adLabel('Ordine')}<input type="number" value={form.sort_order} onChange={e => setForm({ ...form, sort_order: e.target.value })} style={{ ...adInput, width: 90 }} /></div>
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <button type="submit" disabled={busy} style={{ ...adBtn, opacity: busy ? 0.7 : 1 }}>{busy ? 'SE SALVEAZĂ...' : 'SALVEAZĂ'}</button>
            <button type="button" style={adBtnGhost} onClick={() => setEditing(null)}>ANULEAZĂ</button>
          </div>
        </form>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 1, background: 'var(--border)' }}>
        {rows.map(tr => (
          <div key={tr.id} style={{ background: 'var(--bg)', padding: '16px 24px', display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 200 }}>
              <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 800, fontSize: 19, textTransform: 'uppercase' }}>
                {tr.name}
                {!tr.is_published && <span style={{ fontSize: 10, fontFamily: 'JetBrains Mono', border: '1px solid var(--border-bright)', color: 'var(--fg-dim)', padding: '2px 8px', marginLeft: 10, verticalAlign: 'middle' }}>NEPUBLICAT</span>}
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--fg-dim)' }}>
                {[tr.zone, tr.distance_km && tr.distance_km + ' km', tr.elevation_m && tr.elevation_m + ' m↑', tr.difficulty, tr.gpx_path ? 'GPX ✓' : 'fără GPX'].filter(Boolean).join(' · ')}
              </div>
            </div>
            <button style={adBtnGhost} onClick={() => startEdit(tr)}>EDIT</button>
            <button style={adBtnGhost} onClick={() => remove(tr)}>✕</button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Main admin page ─────────────────────────────────────────────────────────
function PageAdmin() {
  const [session, setSession] = useStateAd(undefined); // undefined = loading
  const [tab, setTab] = useStateAd('members');

  useEffectAd(() => {
    sb.auth.getSession().then(({ data }) => setSession(data.session));
    const { data: sub } = sb.auth.onAuthStateChange((_e, s) => setSession(s));
    return () => sub.subscription.unsubscribe();
  }, []);

  if (session === undefined) return <div style={{ minHeight: '60vh' }}></div>;
  if (!session) return <AdminLogin onLogin={setSession} />;

  const tabs = [
    ['members', 'ÎNSCRIERI CLUB'],
    ['events', 'EVENIMENTE'],
    ['trails', 'TRASEE'],
  ];

  return (
    <div>
      <section style={{ padding: '60px 0 0' }}>
        <div className="container">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 20, marginBottom: 40 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 16 }}>/ admin panel</div>
              <h1 className="display display-lg">CARPAT ENDURO</h1>
            </div>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
              <span className="mono" style={{ fontSize: 11, color: 'var(--fg-dim)' }}>{session.user.email}</span>
              <button style={adBtnGhost} onClick={() => sb.auth.signOut()}>IEȘI</button>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6, borderBottom: '1px solid var(--border)', flexWrap: 'wrap' }}>
            {tabs.map(([k, l]) => (
              <button key={k} onClick={() => setTab(k)} style={{
                padding: '12px 22px', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, fontWeight: 700, letterSpacing: '0.12em',
                background: tab === k ? 'var(--accent)' : 'var(--bg-2)',
                color: tab === k ? '#fff' : 'var(--fg-dim)',
                borderTop: '1px solid ' + (tab === k ? 'var(--accent)' : 'var(--border)'),
                borderLeft: '1px solid ' + (tab === k ? 'var(--accent)' : 'var(--border)'),
                borderRight: '1px solid ' + (tab === k ? 'var(--accent)' : 'var(--border)'),
                borderBottom: 'none',
              }}>{l}</button>
            ))}
          </div>
        </div>
      </section>
      <section style={{ padding: '40px 0 100px' }}>
        <div className="container">
          {tab === 'members' && <AdminMembers />}
          {tab === 'events' && <AdminEvents />}
          {tab === 'trails' && <AdminTrails />}
        </div>
      </section>
    </div>
  );
}
window.PageAdmin = PageAdmin;
