/* global React, NA_DATA, NASite, naSupabase */
const { useState, useEffect } = React;

/* ============================================================
   CAMPS PAGE
   ============================================================
   Lists published camps from Supabase (`public_camps` view).
   Each card has an "Apply" button that opens an application form;
   submitting writes to `enquiries` with source='camp_application'.
   ============================================================ */

function CampsPage({ setPage }) {
  const [camps, setCamps] = useState([]);
  const [loadState, setLoadState] = useState('loading'); // 'loading' | 'ok' | 'empty' | 'error'
  const [errMsg, setErrMsg] = useState('');
  const [applyTo, setApplyTo] = useState(null); // a camp object, or null

  // Fetch published camps on mount.
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const rows = await naSupabase.fetchCamps();
        if (cancelled) return;
        setCamps(rows);
        setLoadState(rows.length === 0 ? 'empty' : 'ok');
      } catch (e) {
        if (cancelled) return;
        console.warn('Supabase fetchCamps failed:', e);
        setErrMsg(e.message || 'Could not reach Supabase');
        setLoadState('error');
      }
    })();
    return () => { cancelled = true; };
  }, []);

  return (
    <main>
      <div className="page-head">
        <div className="wrap">
          <div className="crumb">Programme / Camps</div>
          <h1>Camps.</h1>
          <p className="lede">
            Multi-day skills camps — open to club members and outside players. Run during school holidays at our partner venues across Nottingham. Coaches publish each camp here as soon as dates are confirmed.
          </p>
        </div>
      </div>

      <section className="section">
        <div className="wrap">
          {loadState === 'loading' && (
            <div className="card card-pad" style={{ textAlign: 'center', padding: '48px 24px' }}>
              <div className="ink-soft" style={{ fontSize: 14 }}>Loading camps…</div>
            </div>
          )}

          {loadState === 'error' && (
            <div className="card card-pad" style={{ textAlign: 'center', padding: '48px 24px' }}>
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22, fontWeight: 600, marginBottom: 8 }}>
                Could not load camps.
              </div>
              <p className="ink-soft" style={{ fontSize: 14, marginBottom: 16 }}>
                {errMsg}
              </p>
              <button className="btn btn-soft" onClick={() => setPage('contact')}>Get in touch</button>
            </div>
          )}

          {loadState === 'empty' && (
            <div className="card card-pad" style={{ textAlign: 'center', padding: '56px 28px' }}>
              <div style={{ fontFamily: 'var(--font-serif)', fontSize: 28, fontWeight: 600, letterSpacing: '-0.01em', marginBottom: 10 }}>
                No camps published right now.
              </div>
              <p className="ink-soft" style={{ fontSize: 15, lineHeight: 1.5, maxWidth: '42ch', margin: '0 auto 18px' }}>
                We run camps in the school holidays — Christmas, February half-term, Easter, and across summer. When dates are confirmed they appear here. Drop us a line and we'll let you know.
              </p>
              <button className="btn btn-accent" onClick={() => setPage('contact')}>Get in touch →</button>
            </div>
          )}

          {loadState === 'ok' && (
            <div className="grid" style={{ gridTemplateColumns: 'repeat(2, 1fr)', gap: 20 }}>
              {camps.map((c, i) => (
                <CampCard key={c.id} camp={c} index={i} onApply={() => setApplyTo(c)} />
              ))}
            </div>
          )}
        </div>
      </section>

      {applyTo && (
        <CampApplicationModal camp={applyTo} onClose={() => setApplyTo(null)} />
      )}
    </main>
  );
}

/* ---- One camp card ---- */
function CampCard({ camp, index, onApply }) {
  const dateLabel = formatCampDates(camp.starts_on, camp.ends_on);
  const priceLabel = !camp.price_pence
    ? 'Free'
    : '£' + (camp.price_pence / 100).toFixed(camp.price_pence % 100 === 0 ? 0 : 2);

  return (
    <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column', gap: 16, position: 'relative' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12 }}>
        <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 700 }} className="tabular">
          Camp 0{index + 1} · {dateLabel.month}
        </div>
        {camp.is_open_for_applications ? (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 700,
            background: 'var(--na-green-100)', color: 'var(--na-green-700)',
            textTransform: 'uppercase', letterSpacing: '0.05em',
          }}>Open for applications</span>
        ) : (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            padding: '3px 9px', borderRadius: 999, fontSize: 11, fontWeight: 700,
            background: 'var(--surface-2)', color: 'var(--ink-mute)',
            textTransform: 'uppercase', letterSpacing: '0.05em',
            border: '1px solid var(--line)',
          }}>Full</span>
        )}
      </div>

      <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 600, fontSize: 24, letterSpacing: '-0.015em', margin: 0, lineHeight: 1.15 }}>
        {camp.title}
      </h3>

      {camp.blurb && <p className="ink-soft" style={{ fontSize: 14, lineHeight: 1.55, margin: 0 }}>{camp.blurb}</p>}

      <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 16, paddingTop: 14, borderTop: '1px solid var(--line)', marginTop: 'auto' }}>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Dates</div>
          <div className="tabular" style={{ fontSize: 13, fontWeight: 600, marginTop: 3 }}>{dateLabel.range}</div>
          {(camp.start_time || camp.end_time) && (
            <div style={{ fontSize: 12, color: 'var(--ink-mute)', marginTop: 2 }} className="tabular">
              {camp.start_time}{camp.end_time ? ' – ' + camp.end_time : ''}
            </div>
          )}
        </div>
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Venue</div>
          <div style={{ fontSize: 13, fontWeight: 600, marginTop: 3 }}>{camp.venue || 'TBA'}</div>
        </div>
        {camp.eligibility && (
          <div>
            <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Eligible</div>
            <div style={{ fontSize: 13, fontWeight: 600, marginTop: 3 }}>{camp.eligibility}</div>
          </div>
        )}
        <div>
          <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Price</div>
          <div className="tabular" style={{ fontSize: 13, fontWeight: 600, marginTop: 3 }}>{priceLabel}</div>
        </div>
      </div>

      <div style={{ marginTop: 4 }}>
        <button
          className="btn btn-accent"
          onClick={onApply}
          disabled={!camp.is_open_for_applications}>
          {camp.is_open_for_applications ? <>Apply for this camp →</> : 'Camp full'}
        </button>
      </div>
    </div>
  );
}

/* ---- Camp application modal ---- */
function CampApplicationModal({ camp, onClose }) {
  const [status, setStatus] = useState('idle'); // 'idle' | 'sending' | 'sent' | 'error'
  const [errMsg, setErrMsg] = useState('');
  const [form, setForm] = useState({ first_name: '', last_name: '', email: '', phone: '', player_info: '', message: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    setErrMsg('');
    try {
      await naSupabase.submitEnquiry({
        source: 'camp_application',
        camp_id: camp.id,
        first_name: form.first_name.trim(),
        last_name: form.last_name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        player_info: form.player_info.trim(),
        message: form.message.trim(),
      });
      setStatus('sent');
    } catch (err) {
      console.warn('submitEnquiry failed:', err);
      setErrMsg(err.message || 'Could not send. Try again or email admin@nottinghamathletic.com.');
      setStatus('error');
    }
  };

  const sent = status === 'sent';
  const sending = status === 'sending';

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} aria-label="Close">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" width="20" height="20">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        </button>

        {sent ? (
          <div style={{ padding: 16, textAlign: 'center' }}>
            <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 600, fontSize: 32, letterSpacing: '-0.02em', margin: '0 0 12px' }}>You're in the queue.</h3>
            <p className="ink-soft" style={{ fontSize: 15, lineHeight: 1.5, maxWidth: '40ch', margin: '0 auto 20px' }}>
              We'll confirm a place at <b style={{ color: 'var(--ink)' }}>{camp.title}</b> by email — including payment details and what to bring.
            </p>
            <button className="btn btn-soft" onClick={onClose}>Close</button>
          </div>
        ) : (
          <>
            <div className="eyebrow eyebrow-orange">Apply · {camp.title}</div>
            <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 600, fontSize: 26, letterSpacing: '-0.01em', margin: '8px 0 6px' }}>
              Sign up for this camp.
            </h3>
            <p className="ink-soft" style={{ fontSize: 13.5, marginBottom: 16 }}>
              We'll confirm a place by email within a couple of days.
            </p>

            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div className="field"><label>Player first name</label><input required value={form.first_name} onChange={e => set('first_name', e.target.value)} disabled={sending} /></div>
                <div className="field"><label>Last name</label><input required value={form.last_name} onChange={e => set('last_name', e.target.value)} disabled={sending} /></div>
              </div>
              <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div className="field"><label>Parent / contact email</label><input type="email" required value={form.email} onChange={e => set('email', e.target.value)} disabled={sending} /></div>
                <div className="field"><label>Phone (optional)</label><input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} disabled={sending} /></div>
              </div>
              <div className="field"><label>Player age &amp; experience</label><input placeholder="e.g. 13, school team for 2 years" value={form.player_info} onChange={e => set('player_info', e.target.value)} disabled={sending} /></div>
              <div className="field"><label>Anything we should know</label><textarea rows="3" placeholder="Medical, dietary, mobility, etc." value={form.message} onChange={e => set('message', e.target.value)} disabled={sending} /></div>
              {status === 'error' && (
                <div role="alert" style={{ fontSize: 13, color: 'var(--na-red-700)', background: 'var(--na-red-100)', padding: '8px 12px', borderRadius: 'var(--radius-sm)', border: '1px solid var(--na-red-200)' }}>
                  {errMsg}
                </div>
              )}
              <button type="submit" className="btn btn-accent" disabled={sending} style={{ alignSelf: 'flex-start', marginTop: 4 }}>
                {sending ? 'Sending…' : <>Apply for camp →</>}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

/* ---- Helpers ---- */
const MONTHS_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

function formatCampDates(starts, ends) {
  const s = starts ? new Date(starts) : null;
  const e = ends ? new Date(ends) : null;
  if (!s || isNaN(s.getTime())) return { range: 'TBA', month: '' };
  const sDay = s.getDate();
  const sMon = MONTHS_SHORT[s.getMonth()];
  const year = s.getFullYear();
  // Same day?
  if (!e || isNaN(e.getTime()) || (s.getTime() === e.getTime())) {
    return { range: sDay + ' ' + sMon + ' ' + year, month: sMon + ' ' + year };
  }
  const eDay = e.getDate();
  const eMon = MONTHS_SHORT[e.getMonth()];
  // Same month
  if (s.getMonth() === e.getMonth() && s.getFullYear() === e.getFullYear()) {
    return { range: sDay + ' – ' + eDay + ' ' + sMon, month: sMon + ' ' + year };
  }
  return { range: sDay + ' ' + sMon + ' – ' + eDay + ' ' + eMon, month: sMon + ' ' + year };
}

window.CampsPage = CampsPage;
