// EventsSection.jsx — events + trophy admin (extracted from legacy AdminPage).

const EventsSection = ({ onBanner }) => {
  const store = useEventsStore();
  const [editing, setEditing] = useState(null);

  return (
    <>
      <StoreStatusBar
        store={store}
        label="Events"
        onRefresh={() => window.EventsStore.refresh()}
      />

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 28, color: 'var(--wbbq-bone)', margin: 0, letterSpacing: '0.02em' }}>Events ({store.events.length})</h2>
        <button onClick={() => setEditing({ _new: true, id: '', date: '', year: String(new Date().getFullYear()), name: '', location: '', category: '', status: 'LOCKED IN', url: '', notes: '', done: false, place: '', score: '', teams: '', results: {}, ancillary: [] })} className="btn btn-primary" disabled={!store.connected} style={{ fontSize: 13, padding: '12px 20px', opacity: store.connected ? 1 : 0.4 }}>
          + Add Event
        </button>
      </div>

      <div style={{ display: 'grid', gap: 12 }}>
        {store.events.length === 0 && <div style={{ color: 'var(--fg3)', fontSize: 14 }}>No events yet.</div>}
        {store.events.map(e => (
          <AdminEventRow key={e.id} ev={e} onEdit={() => setEditing({ ...e })} connected={store.connected} />
        ))}
      </div>

      {editing && (
        <EventEditor
          ev={editing}
          isNew={editing._new}
          onClose={() => setEditing(null)}
          onSaved={(msg) => { setEditing(null); onBanner({ kind: 'ok', msg }); }}
          onError={(msg) => onBanner({ kind: 'err', msg })}
        />
      )}
    </>
  );
};
window.EventsSection = EventsSection;

const AdminEventRow = ({ ev, onEdit, connected }) => {
  const statusColor = ev.done ? 'var(--wbbq-flame)' :
    ev.status === 'LOCKED IN' ? 'var(--wbbq-slime)' :
    ev.status === 'TENTATIVE' ? 'var(--wbbq-blue)' :
    'var(--wbbq-bone)';
  return (
    <div onClick={connected ? onEdit : undefined} style={{
      display: 'grid', gridTemplateColumns: '100px 1fr auto', gap: 16, alignItems: 'center',
      padding: '16px 18px',
      background: 'var(--wbbq-ink)', border: '2px solid var(--border)',
      cursor: connected ? 'pointer' : 'default',
      transition: 'border-color 120ms',
    }}
    onMouseEnter={(e) => { if (connected) e.currentTarget.style.borderColor = statusColor; }}
    onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; }}
    >
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, color: statusColor }}>
        {ev.date}<br/>
        <span style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--fg3)' }}>{ev.year}</span>
      </div>
      <div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 16, color: 'var(--wbbq-bone)', letterSpacing: '0.02em' }}>{ev.name || <span style={{ color: 'var(--fg3)' }}>(untitled)</span>}</div>
        <div style={{ fontSize: 12, color: 'var(--fg2)', marginTop: 4 }}>
          {ev.location}{ev.category ? ` · ${ev.category}` : ''}
          {ev.done && ev.place && <span style={{ color: 'var(--wbbq-slime)', marginLeft: 10 }}>🏆 {formatPlace(ev.place)}{ev.teams ? ` / ${ev.teams}` : ''}{ev.score && ev.score !== '—' ? ` · ${ev.score}` : ''}</span>}
        </div>
      </div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.12em', padding: '5px 10px', border: `2px solid ${statusColor}`, color: statusColor }}>
        {ev.done ? 'DONE' : ev.status}
      </div>
    </div>
  );
};
window.AdminEventRow = AdminEventRow;

const EventEditor = ({ ev, isNew, onClose, onSaved, onError }) => {
  const [form, setForm] = useState(ev);
  const [saving, setSaving] = useState(false);
  const set = (k, v) => setForm({ ...form, [k]: v });

  const save = async () => {
    setSaving(true);
    try {
      const payload = { ...form };
      delete payload._new;
      if (isNew) {
        await window.EventsStore.add(payload);
        onSaved('Event added.');
      } else {
        await window.EventsStore.update(payload);
        onSaved('Event updated.');
      }
    } catch (e) {
      onError(String(e.message || e));
    } finally {
      setSaving(false);
    }
  };
  const remove = async () => {
    if (!confirm('Delete this event? Cannot be undone.')) return;
    setSaving(true);
    try {
      await window.EventsStore.remove(form.id);
      onSaved('Event deleted.');
    } catch (e) {
      onError(String(e.message || e));
    } finally {
      setSaving(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 150,
      background: 'rgba(11,11,12,0.85)',
      display: 'grid', placeItems: 'center', padding: 20, overflowY: 'auto',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: 'var(--wbbq-ink)', border: '3px solid var(--wbbq-flame)',
        boxShadow: '10px 10px 0 var(--wbbq-blue)',
        padding: 28, width: '100%', maxWidth: 640, maxHeight: '90vh', overflowY: 'auto',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 24, color: 'var(--wbbq-flame)', margin: 0, letterSpacing: '0.02em' }}>
            {isNew ? 'NEW EVENT' : 'EDIT EVENT'}
          </h3>
          <button onClick={onClose} style={{ background: 'transparent', border: 0, color: 'var(--fg1)', fontSize: 24, cursor: 'pointer' }}>✕</button>
        </div>

        <div style={{ display: 'grid', gap: 14 }}>
          <div className="editor-2col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <AdminInput label="Date" value={form.date} onChange={(v) => set('date', v)} placeholder="APR 25" />
            <AdminInput label="Year" value={form.year} onChange={(v) => set('year', v)} placeholder="2026" />
          </div>
          <AdminInput label="Event Name" value={form.name} onChange={(v) => set('name', v)} placeholder="Harpoon NE Championship" />
          <div className="editor-2col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <AdminInput label="Location" value={form.location} onChange={(v) => set('location', v)} placeholder="Windsor, VT" />
            <AdminInput label="Category" value={form.category} onChange={(v) => set('category', v)} placeholder="KCBS · 4-Meat" />
          </div>
          <div>
            <AdminLabel>Status</AdminLabel>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {['LOCKED IN', 'TENTATIVE', 'DONE'].map(s => (
                <button type="button" key={s} onClick={() => set('status', s)} style={{
                  padding: '10px 14px',
                  background: form.status === s ? 'var(--wbbq-flame)' : 'transparent',
                  color: form.status === s ? 'var(--wbbq-black)' : 'var(--fg1)',
                  border: '2px solid ' + (form.status === s ? 'var(--wbbq-flame)' : 'var(--border)'),
                  fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.08em',
                  cursor: 'pointer',
                }}>{s}</button>
              ))}
            </div>
          </div>
          <AdminInput label="Event URL (optional)" value={form.url} onChange={(v) => set('url', v)} placeholder="https://..." />
          <div>
            <AdminLabel>Private Notes (admin only)</AdminLabel>
            <textarea rows={2} value={form.notes} onChange={(e) => set('notes', e.target.value)} style={editorInputStyle()} />
          </div>

          <div style={{ paddingTop: 16, marginTop: 6, borderTop: '2px dashed var(--border)' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', userSelect: 'none' }}>
              <input type="checkbox" checked={!!form.done} onChange={(e) => set('done', e.target.checked)} style={{ width: 20, height: 20, accentColor: 'var(--wbbq-slime)' }} />
              <span style={{ fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--wbbq-slime)', letterSpacing: '0.06em' }}>◉ MARK AS DONE (shows on Trophies page)</span>
            </label>
          </div>

          {form.done && (
            <div style={{ display: 'grid', gap: 12, padding: 14, background: 'var(--wbbq-black)', border: '2px solid var(--wbbq-slime)' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, color: 'var(--wbbq-slime)', letterSpacing: '0.08em' }}>OVERALL</div>
              <div className="editor-3col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                <AdminInput label="Place (just #)" value={form.place} onChange={(v) => set('place', v)} placeholder="23" />
                <AdminInput label="Total Teams" value={form.teams} onChange={(v) => set('teams', v)} placeholder="35" />
                <AdminInput label="Overall Score" value={form.score} onChange={(v) => set('score', v)} placeholder="684.1" />
              </div>

              <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, color: 'var(--wbbq-slime)', letterSpacing: '0.08em', marginTop: 6 }}>MEAT BREAKDOWN <span style={{ color: 'var(--fg3)', fontSize: 10, letterSpacing: '0.1em' }}>(OPTIONAL — FILL IN WHAT YOU HAVE)</span></div>
              {['chicken','ribs','pork','brisket'].map(meat => {
                const r = (form.results && form.results[meat]) || { place: '', score: '' };
                const setMeat = (k, v) => set('results', { ...(form.results || {}), [meat]: { ...r, [k]: v } });
                return (
                  <div key={meat} className="meat-edit-row" style={{ display: 'grid', gridTemplateColumns: '100px 1fr 1fr', gap: 10, alignItems: 'center' }}>
                    <div style={{ fontFamily: 'var(--font-display)', fontSize: 14, color: 'var(--wbbq-flame)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{meat}</div>
                    <input value={r.place || ''} onChange={(e) => setMeat('place', e.target.value)} placeholder="Place" style={editorInputStyle()} />
                    <input value={r.score || ''} onChange={(e) => setMeat('score', e.target.value)} placeholder="Score" style={editorInputStyle()} />
                  </div>
                );
              })}

              <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, color: 'var(--wbbq-slime)', letterSpacing: '0.08em', marginTop: 6, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>ANCILLARY <span style={{ color: 'var(--fg3)', fontSize: 10, letterSpacing: '0.1em' }}>(WINGS, DESSERT, ETC)</span></span>
                <button type="button" onClick={() => set('ancillary', [...(form.ancillary || []), { name: '', place: '', teams: '', score: '' }])} style={{
                  background: 'transparent', border: '2px solid var(--wbbq-slime)', color: 'var(--wbbq-slime)',
                  fontFamily: 'var(--font-display)', fontSize: 10, letterSpacing: '0.1em',
                  padding: '5px 10px', cursor: 'pointer',
                }}>+ ADD</button>
              </div>
              {(form.ancillary || []).map((a, i) => (
                <div key={i} className="ancillary-row" style={{ display: 'grid', gridTemplateColumns: '1fr 80px 80px 90px auto', gap: 8, alignItems: 'center' }}>
                  <input value={a.name || ''} onChange={(e) => {
                    const next = [...form.ancillary]; next[i] = { ...a, name: e.target.value }; set('ancillary', next);
                  }} placeholder="Name (e.g. Wings)" style={editorInputStyle()} />
                  <input value={a.place || ''} onChange={(e) => {
                    const next = [...form.ancillary]; next[i] = { ...a, place: e.target.value }; set('ancillary', next);
                  }} placeholder="Place" style={editorInputStyle()} />
                  <input value={a.teams || ''} onChange={(e) => {
                    const next = [...form.ancillary]; next[i] = { ...a, teams: e.target.value }; set('ancillary', next);
                  }} placeholder="Teams" style={editorInputStyle()} />
                  <input value={a.score || ''} onChange={(e) => {
                    const next = [...form.ancillary]; next[i] = { ...a, score: e.target.value }; set('ancillary', next);
                  }} placeholder="Score" style={editorInputStyle()} />
                  <button type="button" onClick={() => {
                    const next = [...form.ancillary]; next.splice(i, 1); set('ancillary', next);
                  }} style={{ background: 'transparent', border: 0, color: 'var(--wbbq-blood)', cursor: 'pointer', fontSize: 20, padding: '0 6px' }}>✕</button>
                </div>
              ))}
              {(!form.ancillary || form.ancillary.length === 0) && (
                <div style={{ fontSize: 12, color: 'var(--fg3)', fontStyle: 'italic' }}>No ancillary entries. Hit + ADD if you entered a side category.</div>
              )}
            </div>
          )}

          <div style={{ display: 'flex', gap: 10, marginTop: 14, flexWrap: 'wrap' }}>
            <button onClick={save} disabled={saving} className="btn btn-primary" style={{ fontSize: 13, opacity: saving ? 0.6 : 1 }}>
              {saving ? 'Saving…' : (isNew ? 'Add Event →' : 'Save Changes →')}
            </button>
            {!isNew && <button onClick={remove} disabled={saving} className="btn" style={{ fontSize: 13, background: 'transparent', color: 'var(--wbbq-blood)', border: '2px solid var(--wbbq-blood)' }}>Delete</button>}
            <button onClick={onClose} className="btn btn-ghost" style={{ fontSize: 13 }}>Cancel</button>
          </div>
        </div>
      </div>
    </div>
  );
};
window.EventEditor = EventEditor;
