// Events page — events from Supabase: details, online registration, public competitor list
const { useState: useStateE, useEffect: useEffectE } = React;

const inputStyleE = {
  width: '100%', padding: '14px 16px', background: 'var(--bg)',
  color: 'var(--fg)', border: '1px solid var(--border)',
  fontFamily: 'JetBrains Mono, monospace', fontSize: 14, outline: 'none',
};

function fmtDate(ev, lang) {
  if (!ev.event_date) return 'TBA';
  const months = lang === 'ro'
    ? ['IAN', 'FEB', 'MAR', 'APR', 'MAI', 'IUN', 'IUL', 'AUG', 'SEP', 'OCT', 'NOI', 'DEC']
    : ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
  const d = new Date(ev.event_date + 'T00:00:00');
  return `${String(d.getDate()).padStart(2, '0')} ${months[d.getMonth()]} ${d.getFullYear()}${ev.event_time ? ' · ' + ev.event_time : ''}`;
}

function EventDetail({ ev, lang, onBack }) {
  const t = window.CONTENT[lang].events;
  const [competitors, setCompetitors] = useStateE(null);
  const [form, setForm] = useStateE({ full_name: '', phone: '', email: '', bike: '', category: '' });
  const [status, setStatus] = useStateE('idle'); // idle | sending | ok | error

  const loadCompetitors = () => db.fetchCompetitors(ev.id).then(setCompetitors);
  useEffectE(() => { loadCompetitors(); }, [ev.id]);

  const categories = (ev.categories || '').split(',').map(s => s.trim()).filter(Boolean);

  const submit = async e => {
    e.preventDefault();
    setStatus('sending');
    const res = await db.registerForEvent({ ...form, event_id: ev.id, event_title: undefined });
    if (res.ok) {
      setStatus('ok');
      setForm({ full_name: '', phone: '', email: '', bike: '', category: '' });
      loadCompetitors();
    } else {
      setStatus('error');
    }
  };

  const label = (txt, i) => (
    <label className="mono" style={{ display: 'block', fontSize: 10, color: 'var(--fg-dim)', letterSpacing: '0.18em', marginBottom: 8 }}>
      {String(i).padStart(2, '0')} · {txt.toUpperCase()}
    </label>
  );

  return (
    <div>
      <section style={{ padding: '60px 0 50px', borderBottom: '1px solid var(--border)' }}>
        <div className="container">
          <button className="mono" onClick={onBack} style={{ fontSize: 12, color: 'var(--fg-dim)', letterSpacing: '0.12em', marginBottom: 30, display: 'inline-block' }}>{t.back}</button>
          <div style={{ display: 'flex', gap: 18, alignItems: 'center', flexWrap: 'wrap', marginBottom: 20 }}>
            <span style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11, fontWeight: 700,
              padding: '6px 12px', letterSpacing: '0.14em',
              color: ev.event_type === 'COMP' ? '#fff' : 'var(--accent)',
              background: ev.event_type === 'COMP' ? 'var(--accent)' : 'transparent',
              border: '1px solid var(--accent)',
            }}>{ev.event_type === 'COMP' ? t.comp : ev.event_type === 'MEMBERS' ? t.members : t.open}</span>
            <span className="mono" style={{ fontSize: 13, color: 'var(--fg-dim)', letterSpacing: '0.1em' }}>{fmtDate(ev, lang)}</span>
          </div>
          <h1 className="display display-xl" style={{ marginBottom: 20 }}>{ev.title}</h1>
          {ev.location && <div className="mono" style={{ fontSize: 14, color: 'var(--fg-dim)', letterSpacing: '0.08em' }}>📍 {ev.location}</div>}
        </div>
      </section>

      {/* DETAILS */}
      <section className="section" style={{ paddingTop: 70, paddingBottom: 70 }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 20 }}>/ {t.details_title.toLowerCase()}</div>
          {ev.description && <p style={{ fontSize: 18, color: 'var(--fg-dim)', maxWidth: 780, lineHeight: 1.65, whiteSpace: 'pre-line', marginBottom: 36 }}>{ev.description}</p>}
          <div style={{ display: 'flex', gap: 40, flexWrap: 'wrap' }}>
            {[
              [lang === 'ro' ? 'DATA' : 'DATE', fmtDate(ev, lang)],
              [lang === 'ro' ? 'LOC' : 'LOCATION', ev.location],
              [lang === 'ro' ? 'DISTANȚĂ' : 'DISTANCE', ev.distance],
              [lang === 'ro' ? 'CATEGORII' : 'CATEGORIES', ev.categories],
            ].filter(([, v]) => v).map(([k, v]) => (
              <div key={k}>
                <div className="mono" style={{ fontSize: 10, color: 'var(--fg-dimmer)', letterSpacing: '0.18em', marginBottom: 6 }}>{k}</div>
                <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 700, fontSize: 20 }}>{v}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* REGISTRATION */}
      <section className="section" style={{ background: 'var(--bg-2)', paddingTop: 70, paddingBottom: 70 }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 20 }}>/ {t.reg_title.toLowerCase()}</div>
          {!ev.registration_open ? (
            <p style={{ fontSize: 18, color: 'var(--fg-dim)' }}>{t.reg_closed}</p>
          ) : (
            <div style={{ maxWidth: 720 }}>
              <p style={{ fontSize: 15, color: 'var(--fg-dim)', marginBottom: 28 }}>{t.reg_note}</p>
              <form onSubmit={submit} style={{ background: 'var(--bg)', padding: '36px', border: '1px solid var(--border)' }}>
                <div className="form-2col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 20 }}>
                  <div>
                    {label(t.fields.name, 1)}
                    <input required value={form.full_name} onChange={e => setForm({ ...form, full_name: e.target.value })} style={inputStyleE} />
                  </div>
                  <div>
                    {label(t.fields.phone, 2)}
                    <input required value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} style={inputStyleE} />
                  </div>
                </div>
                <div className="form-2col" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 28 }}>
                  <div>
                    {label(t.fields.bike, 3)}
                    <input value={form.bike} onChange={e => setForm({ ...form, bike: e.target.value })} placeholder="KTM / Husqvarna / Beta..." style={inputStyleE} />
                  </div>
                  <div>
                    {label(t.fields.category, 4)}
                    {categories.length > 0 ? (
                      <select required value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} style={{ ...inputStyleE, appearance: 'none' }}>
                        <option value="" disabled>—</option>
                        {categories.map(c => <option key={c} value={c}>{c}</option>)}
                      </select>
                    ) : (
                      <input value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} style={inputStyleE} />
                    )}
                  </div>
                </div>
                <button type="submit" disabled={status === 'sending'} className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', opacity: status === 'sending' ? 0.7 : 1 }}>
                  {t.fields.submit} <span className="arrow">→</span>
                </button>
                {status === 'error' && <p style={{ color: 'var(--accent-bright)', marginTop: 14, fontSize: 14 }}>{window.CONTENT[lang].membership.error}</p>}
              </form>
              <SuccessModal open={status === 'ok'} onClose={() => setStatus('idle')}
                title={t.reg_success_title} body={t.reg_success_body} cta={t.reg_success_cta} />
            </div>
          )}
        </div>
      </section>

      {/* COMPETITORS */}
      <section className="section" style={{ paddingTop: 70 }}>
        <div className="container">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 36 }}>
            <div>
              <div className="eyebrow" style={{ marginBottom: 16 }}>/ concurenți</div>
              <h2 className="display display-md">{t.competitors_title}</h2>
            </div>
            <div className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)', letterSpacing: '0.12em' }}>
              [ {(competitors || []).length} ]
            </div>
          </div>
          {competitors === null ? null : competitors.length === 0 ? (
            <p style={{ color: 'var(--fg-dim)', fontSize: 16 }}>{t.no_competitors}</p>
          ) : (
            <div style={{ overflowX: 'auto' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 1, background: 'var(--border)', minWidth: 560 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '60px 1fr 1fr 140px', gap: 20, padding: '14px 24px', background: 'var(--bg-3)' }}>
                  {['#', t.fields.name, t.fields.bike, t.fields.category].map(h => (
                    <div key={h} className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)', letterSpacing: '0.18em' }}>{h.toUpperCase()}</div>
                  ))}
                </div>
                {competitors.map((c, i) => (
                  <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '60px 1fr 1fr 140px', gap: 20, padding: '16px 24px', background: 'var(--bg)', alignItems: 'center' }}>
                    <div className="mono" style={{ fontSize: 13, color: 'var(--accent)', fontWeight: 700 }}>{String(i + 1).padStart(2, '0')}</div>
                    <div style={{ fontFamily: 'Barlow Condensed', fontWeight: 700, fontSize: 19, textTransform: 'uppercase' }}>{c.full_name}</div>
                    <div className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)' }}>{c.bike || '—'}</div>
                    <div className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)' }}>{c.category || '—'}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

function PageEvents({ lang }) {
  const t = window.CONTENT[lang].events;
  const events = useFetch(db.fetchEvents);
  const [selected, setSelected] = useStateE(null);
  const today = new Date().toISOString().slice(0, 10);
  const all = events.data || [];
  const upcoming = all.filter(ev => !ev.event_date || ev.event_date >= today);
  const past = all.filter(ev => ev.event_date && ev.event_date < today).reverse();

  if (selected) {
    return <EventDetail ev={selected} lang={lang} onBack={() => setSelected(null)} />;
  }

  return (
    <div>
      <section style={{ padding: '80px 0 60px', borderBottom: '1px solid var(--border)' }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 28 }}>{t.eyebrow}</div>
          <h1 className="display display-xxl" style={{ marginBottom: 40 }}>
            <div>{t.title_1}</div>
            <div style={{ color: 'var(--accent)' }}>{t.title_2}</div>
          </h1>
          <p style={{ fontSize: 20, maxWidth: 680, color: 'var(--fg-dim)', lineHeight: 1.55 }}>{t.sub}</p>
        </div>
      </section>

      <section className="section">
        <div className="container">
          {events.loading ? null : upcoming.length === 0 && past.length === 0 ? (
            <ComingSoon note={t.coming_note} label="TURURI · COMPETIȚII · VALEA JIULUI" />
          ) : (
            <>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40 }}>
                <h2 className="display display-lg">{t.up_title}</h2>
                <div className="mono" style={{ fontSize: 12, color: 'var(--fg-dim)' }}>[ {upcoming.length} ]</div>
              </div>
              {upcoming.length === 0 ? (
                <p style={{ color: 'var(--fg-dim)', fontSize: 16, marginBottom: 60 }}>{t.coming_note}</p>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 1, background: 'var(--border)', marginBottom: 80 }}>
                  {upcoming.map(ev => (
                    <EventRow key={ev.id} ev={ev} lang={lang} onClick={() => setSelected(ev)} />
                  ))}
                </div>
              )}

              {past.length > 0 && (
                <>
                  <h2 className="display display-lg" style={{ marginBottom: 40 }}>{t.past_title}</h2>
                  <div className="cards-3" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
                    {past.map(ev => (
                      <div key={ev.id} style={{ background: 'var(--bg-2)', border: '1px solid var(--border)', padding: '24px', cursor: 'pointer' }}
                        onClick={() => setSelected(ev)}>
                        <div className="mono" style={{ fontSize: 11, color: 'var(--accent)', letterSpacing: '0.18em', marginBottom: 8 }}>{fmtDate(ev, lang)}</div>
                        <h3 style={{ fontFamily: 'Barlow Condensed', fontStyle: 'italic', fontWeight: 800, fontSize: 20, textTransform: 'uppercase', lineHeight: 1.1 }}>{ev.title}</h3>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </>
          )}
        </div>
      </section>
    </div>
  );
}
window.PageEvents = PageEvents;
