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

// Calendly-style booking flow for Nottingham Athletic.
// Steps: squad -> calendar (day picker + sessions) -> pay-choice modal ->
//        details -> pay (gocardless | stripe | cash) -> confirmation.

function SessionsPage({ setPage }) {
  const { SQUADS } = NA_DATA;
  const PER_SESSION = 6.50;

  const [step, setStep] = useState('squad');
  const [squadId, setSquadId] = useState(null);
  const [weekStart, setWeekStart] = useState(() => startOfWeek(new Date('2026-05-11')));
  const [selectedDay, setSelectedDay] = useState(null);
  const [selectedSession, setSelectedSession] = useState(null);
  const [payChoice, setPayChoice] = useState(null); // 'monthly' | 'payg' | 'cash'
  const [details, setDetails] = useState({});
  const [confirmRecord, setConfirmRecord] = useState(null);
  const [ddBusy, setDdBusy] = useState(null);   // squad id currently starting a mandate
  const [ddError, setDdError] = useState('');

  // Start a real GoCardless Direct Debit mandate for a monthly membership.
  // Hands the visitor to the GoCardless hosted page (which collects their
  // name, email and bank details), then returns them to #join-success.
  async function startDirectDebit(s) {
    setDdError('');
    setDdBusy(s.id);
    try {
      const res = await fetch('https://zpsfpgkkuromgihdcast.supabase.co/functions/v1/gocardless', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: 'create-redirect-flow',
          squad: s.id,
          plan: 'monthly',
          amount: s.monthly,
          description: `${s.name} — monthly membership (£${s.monthly}/mo)`,
          success_url: window.location.origin + window.location.pathname + '#join-success',
        }),
      });
      if (!res.ok) {
        const body = await res.text().catch(() => '');
        throw new Error(`GoCardless ${res.status}: ${body.slice(0, 140)}`);
      }
      const { redirect_url } = await res.json();
      if (redirect_url) { window.location.href = redirect_url; return; }
      throw new Error('No redirect URL returned.');
    } catch (err) {
      console.warn('GoCardless mandate failed:', err);
      setDdError('Could not start the Direct Debit setup. Please try again, or email admin@nottinghamathletic.com.');
      setDdBusy(null);
    }
  }

  // Live session capacity from the coach app (Supabase view: session_capacity)
  const [remoteCapacity, setRemoteCapacity] = useState([]);
  const [capacityState, setCapacityState] = useState('loading'); // 'loading'|'ok'|'empty'|'error'
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const rows = await naSupabase.fetchSessionCapacity();
        if (cancelled) return;
        setRemoteCapacity(rows.map(naSupabase.normaliseSession));
        setCapacityState(rows.length ? 'ok' : 'empty');
      } catch (e) {
        if (!cancelled) setCapacityState('error');
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const squad = SQUADS.find(s => s.id === squadId);

  // -------- Sessions for the visible week --------
  // Prefer real session_capacity rows when present. Fall back to generating
  // placeholder sessions from the squad training schedule when the coach
  // app hasn't published any yet.
  const sessionsByDay = useMemo(() => {
    if (!squad) return {};

    // Live data path: filter rows for this squad + visible week
    const weekEnd = new Date(weekStart.getTime() + 7 * 86400000);
    const live = remoteCapacity.filter(s =>
      s.squad === squad.id && s.date >= weekStart && s.date < weekEnd
    );
    if (live.length) {
      const map = {};
      live.forEach(s => {
        const key = s.date.toDateString();
        if (!map[key]) map[key] = [];
        map[key].push({
          ...s,
          endTime: addHour(s.time),
          type: 'practice',
        });
      });
      return map;
    }

    // Fallback: generate from training schedule
    const dayMap = { Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6, Sun: 0 };

    // Squads made up of several teams that each train at their own time
    // (e.g. the Junior Local League — U14 / U16 / U18 on Mondays) declare
    // them via `subTeams`. Each becomes its own bookable session, labelled.
    const slots = (squad.subTeams && squad.subTeams.length)
      ? squad.subTeams.map(t => {
          const [d, time] = t.slot.split(' ');
          return { day: dayMap[d], time: time || '18:00', label: t.label };
        }).filter(s => s.day !== undefined)
      : squad.training.split('·').map(s => s.trim()).map(s => {
          const [d, t] = s.split(' ');
          return { day: dayMap[d], time: t || '18:00' };
        }).filter(s => s.day !== undefined);

    const map = {};
    for (let i = 0; i < 7; i++) {
      const d = new Date(weekStart.getTime() + i * 86400000);
      const key = d.toDateString();
      slots.forEach(slot => {
        if (d.getDay() === slot.day) {
          if (!map[key]) map[key] = [];
          const taken = 4 + Math.floor(seedRand(squad.id + key + slot.time + (slot.label || '')) * 11);
          map[key].push({
            id: `${squad.id}-${d.toISOString().slice(0,10)}-${slot.time}-${(slot.label || '').replace(/\s+/g,'')}`,
            date: d,
            time: slot.time,
            endTime: addHour(slot.time),
            venue: squad.venue,
            type: 'practice',
            label: slot.label || null,
            capacity: 16,
            taken,
          });
        }
      });
    }
    // Sort each day's sessions by start time so teams read top-to-bottom.
    Object.values(map).forEach(arr => arr.sort((a, b) => a.time.localeCompare(b.time)));
    return map;
  }, [squadId, weekStart, remoteCapacity]);

  const goToSquad = () => setStep('squad');
  const goToCalendar = () => setStep('calendar');

  // ============ STEP 1 — SQUAD ============
  if (step === 'squad') {
    // Bookable = open Local League teams (£20/mo) + U12 (£15/mo).
    // Invite only = National League squads (selected at trials).
    // YBL teams have open registration but prices are still TBC, so they
    // aren't bookable here yet — they live on the Teams page.
    const bookable = SQUADS.filter(s => s.bookable);
    const inviteOnly = SQUADS.filter(s => s.inviteOnly);

    return (
      <main className="book-stage">
        <div className="book-head">
          <div className="wrap">
            <div className="crumb">Step 1 of 4 · Pick your squad</div>
            <h1>Book a session.</h1>
            <p className="lede">Open booking is available for our U12 squad and our Local League teams — U14, U16, U18 and Mens, all training Monday nights. National League squads are invite only; speak to a coach about trialling.</p>
          </div>
        </div>

        <section className="section">
          <div className="wrap">
            <div className="squad-grid">
              {bookable.map(s => (
                <div key={s.id} className="squad-pick squad-pick-static" style={{ '--squad-color': s.barColor }}>
                  <div className="squad-pick-head">
                    <span className={`dot ${s.dotClass}`} style={{ width: 12, height: 12 }}></span>
                    <span className="squad-pick-tag">{s.tag}</span>
                  </div>
                  <div className="squad-pick-name">{s.name}</div>
                  <div className="squad-pick-meta">{summarise(s.training)} · {s.venue}</div>
                  <div className="squad-pick-foot">
                    <span className="squad-pick-mini">£6.50/session · or £{s.monthly}/mo unlimited</span>
                  </div>
                  <div className="squad-pick-actions">
                    <button className="btn btn-soft" onClick={() => { setSquadId(s.id); setStep('calendar'); }}>
                      Book a session →
                    </button>
                    <button className="btn btn-accent" disabled={ddBusy === s.id} onClick={() => startDirectDebit(s)}>
                      {ddBusy === s.id ? 'Starting…' : `Set up Direct Debit · £${s.monthly}/mo →`}
                    </button>
                  </div>
                </div>
              ))}
            </div>

            {ddError && (
              <div role="alert" style={{ marginTop: 16, fontSize: 13.5, color: 'var(--na-red-700)', background: 'var(--na-red-100)', padding: '12px 14px', borderRadius: 'var(--radius-sm)', border: '1px solid var(--na-red-200)' }}>
                {ddError}
              </div>
            )}

            {/* Invite-only callout — National League squads */}
            <div className="invite-only-card">
              <div className="invite-only-head">
                <div className="eyebrow eyebrow-orange">Invite only</div>
                <h3>National League squads — Senior, U23, U16 &amp; U14.</h3>
                <p className="ink-soft">
                  Players on the National League pathway are selected at trials and managed by the head coach. These squads aren't bookable online — your coach will add you to the schedule once you're on the roster. Want to trial? <a className="invite-only-link" onClick={() => setPage('teams')}>See teams &amp; trial info →</a>
                </p>
              </div>
              <div className="invite-only-grid">
                {inviteOnly.map(s => (
                  <div key={s.id} className="invite-only-row">
                    <span className={`dot ${s.dotClass}`} style={{ width: 10, height: 10 }}></span>
                    <span className="invite-only-name">{s.name}</span>
                    <span className="invite-only-meta ink-soft">{s.leagues[0] ? s.leagues[0].name : ''} · {s.venue}</span>
                    <span className="invite-only-tag">Invite only</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </section>
      </main>
    );
  }

  // ============ STEP 2 — CALENDAR ============
  if (step === 'calendar') {
    const days = [];
    for (let i = 0; i < 7; i++) {
      const d = new Date(weekStart.getTime() + i * 86400000);
      days.push(d);
    }
    const visibleDay = selectedDay || days.find(d => sessionsByDay[d.toDateString()]) || days[0];
    const todaySessions = sessionsByDay[visibleDay.toDateString()] || [];

    return (
      <main className="book-stage">
        <div className="book-head">
          <div className="wrap">
            <div className="crumb">
              <a className="crumb-link" onClick={goToSquad}>← {squad.name}</a> · Step 2 of 4 · Pick a session
            </div>
            <h1 className="book-h">When can you make it?</h1>
            <p className="lede">All sessions take place at {squad.venue}. Sessions go live four weeks ahead.</p>
          </div>
        </div>

        <section className="section">
          <div className="wrap">
            <div className="cal-layout">
              {/* WEEK NAV + DAY GRID */}
              <div>
                <div className="week-nav">
                  <button className="week-arrow" onClick={() => setWeekStart(d => new Date(d.getTime() - 7*86400000))} aria-label="Previous week">←</button>
                  <div className="week-label">{rangeLabel(weekStart)}</div>
                  <button className="week-arrow" onClick={() => setWeekStart(d => new Date(d.getTime() + 7*86400000))} aria-label="Next week">→</button>
                </div>

                <div className="week-grid">
                  {days.map(d => {
                    const has = !!sessionsByDay[d.toDateString()];
                    const isSelected = visibleDay.toDateString() === d.toDateString();
                    return (
                      <button key={d.toISOString()}
                              className={'day-cell ' + (isSelected ? 'selected ' : '') + (has ? 'has-session' : 'no-session')}
                              onClick={() => has && setSelectedDay(d)}
                              disabled={!has}>
                        <div className="day-name">{d.toLocaleDateString('en-GB', { weekday: 'short' }).toUpperCase()}</div>
                        <div className="day-num">{d.getDate()}</div>
                        {has && <span className="day-dot" style={{ background: squad.barColor }}></span>}
                      </button>
                    );
                  })}
                </div>

                <div className="cal-legend">
                  <span><span className="legend-dot" style={{ background: squad.barColor }}></span> Available</span>
                  <span><span className="legend-dot legend-empty"></span> No session</span>
                </div>
              </div>

              {/* RIGHT PANE — SESSIONS */}
              <div className="day-pane">
                <div className="day-pane-head">
                  <div>
                    <div className="eyebrow" style={{ color: 'var(--ink-mute)' }}>{visibleDay.toLocaleDateString('en-GB', { weekday: 'long' })}</div>
                    <div className="day-pane-date">{visibleDay.toLocaleDateString('en-GB', { day: 'numeric', month: 'long' })}</div>
                  </div>
                </div>

                {todaySessions.length === 0 ? (
                  <div className="empty-day">
                    No sessions on this day. Pick another from the week.
                  </div>
                ) : (
                  <div className="day-sessions">
                    {todaySessions.map(sx => {
                      const remaining = sx.capacity - sx.taken;
                      const soldOut = remaining <= 0;
                      const filling = remaining <= 4 && remaining > 0;
                      return (
                        <div key={sx.id} className={'session-row ' + (soldOut ? 'is-soldout' : '')}>
                          <div className="session-time">
                            <span className="session-time-main">{sx.time}</span>
                            <span className="session-time-end">— {sx.endTime}</span>
                          </div>
                          <div className="session-body">
                            <div className="session-title-row">
                              <span className="session-title">{sx.label ? `${sx.label}` : `${squad.name} training`}</span>
                              <span className={'cal-type cal-type-' + sx.type}>{sx.type}</span>
                            </div>
                            <div className="session-meta">{sx.venue}</div>
                            <div className={'session-cap ' + (filling ? 'filling' : '') + (soldOut ? ' filling' : '')}>
                              {soldOut ? 'Sold out' : <><span className="tabular">{sx.taken}</span> of <span className="tabular">{sx.capacity}</span> spots taken — <span className="tabular">{remaining}</span> left</>}
                            </div>
                          </div>
                          <div className="session-cta">
                            <div className="session-price">
                              <span className="tabular">£{PER_SESSION.toFixed(2)}</span>
                              <span className="session-price-or">or included monthly</span>
                            </div>
                            {soldOut ? (
                              <button className="btn btn-soft" disabled>Waitlist</button>
                            ) : (
                              <button className="btn btn-accent" onClick={() => { setSelectedSession(sx); setStep('pay-choice'); }}>Book →</button>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>
      </main>
    );
  }

  // ============ STEP 3 — PAY CHOICE MODAL ============
  if (step === 'pay-choice') {
    return (
      <main className="book-stage">
        <div className="book-head">
          <div className="wrap">
            <div className="crumb">
              <a className="crumb-link" onClick={goToCalendar}>← Back to sessions</a> · Step 3 of 4 · How will you pay?
            </div>
            <h1 className="book-h">How would you like to pay?</h1>
            <p className="lede">Most members go monthly — cheaper per session, and you don't have to remember each week.</p>
          </div>
        </div>

        <section className="section">
          <div className="wrap" style={{ maxWidth: 1080 }}>
            <div className="pay-choice-grid">
              <button className="pay-choice pay-choice-featured" onClick={() => { setPayChoice('monthly'); setStep('details'); }}>
                <div className="pay-choice-badge">Best value · Recommended</div>
                <div className="pay-choice-eyebrow">Monthly Direct Debit</div>
                <div className="pay-choice-price">
                  <span className="pay-choice-amount">£{squad.monthly}</span>
                  <span className="pay-choice-period">/ month — all {squad.short} sessions</span>
                </div>
                <p className="pay-choice-blurb">Cheaper per session, no booking needed each week, automatic via Direct Debit. Cancel any time, 30 days notice.</p>
                <ul className="pay-choice-perks">
                  <li><Tick /> All squad training, every week</li>
                  <li><Tick /> Auto-marked attended in registers</li>
                  <li><Tick /> Powered by GoCardless</li>
                </ul>
                <div className="pay-choice-cta">Choose monthly →</div>
              </button>

              <button className="pay-choice pay-choice-light" onClick={() => { setPayChoice('payg'); setStep('details'); }}>
                <div className="pay-choice-eyebrow">Pay for this session</div>
                <div className="pay-choice-price">
                  <span className="pay-choice-amount">£6.50</span>
                  <span className="pay-choice-period">one-off</span>
                </div>
                <p className="pay-choice-blurb">Best for trialists or one-offs. Card payment via Stripe.</p>
                <ul className="pay-choice-perks">
                  <li><Tick /> One session, one payment</li>
                  <li><Tick /> No subscription</li>
                  <li><Tick /> Receipt by email</li>
                </ul>
                <div className="pay-choice-cta pay-choice-cta-soft">Pay for your session — £6.50 →</div>
              </button>
            </div>

            <div className="pay-compare">
              <div className="pay-compare-icon">£</div>
              <div>
                <strong>Train 4× this month?</strong>
                <span className="ink-soft"> That's £{(PER_SESSION * 4).toFixed(2)} pay-as-you-go. Monthly Direct Debit covers unlimited training for £{squad.monthly} — saving you ~£{Math.max(0, (PER_SESSION * 4) - squad.monthly).toFixed(2)}.</span>
              </div>
            </div>

            <div className="pay-cash">
              <a className="cash-link" onClick={() => { setPayChoice('cash'); setStep('details'); }}>Skip — I'll pay cash on the door →</a>
            </div>
          </div>
        </section>
      </main>
    );
  }

  // ============ STEP 4 — DETAILS ============
  if (step === 'details') {
    const onSubmit = (e) => {
      e.preventDefault();
      const fd = new FormData(e.target);
      const data = Object.fromEntries(fd.entries());
      setDetails(data);
      if (payChoice === 'cash') {
        finalise({ provider: 'cash', providerRef: 'CASH-' + Math.random().toString(36).slice(2,10).toUpperCase() }, data);
      } else {
        setStep(payChoice === 'monthly' ? 'pay-mandate' : 'pay-card');
      }
    };

    const isUnder18 = (() => {
      if (!details.dob) return false;
      const dob = new Date(details.dob);
      const now = new Date('2026-05-05');
      return (now.getFullYear() - dob.getFullYear()) < 18;
    })();

    return (
      <main className="book-stage">
        <div className="book-head">
          <div className="wrap">
            <div className="crumb">
              <a className="crumb-link" onClick={() => setStep('pay-choice')}>← Back</a> · Step 4 of 4 · Player details
            </div>
            <h1 className="book-h">A few details.</h1>
            <p className="lede">{payChoice === 'monthly' ? `Setting up monthly Direct Debit for ${squad.name}.` : payChoice === 'cash' ? 'Booked, but pay cash on the door — coach will mark it off on the day.' : 'Paying £6.50 for this session by card.'}</p>
          </div>
        </div>

        <section className="section">
          <div className="wrap" style={{ maxWidth: 720 }}>
            <form className="checkout-card" onSubmit={onSubmit}>
              <div className="eyebrow mb-3">Player</div>
              <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div className="field"><label>Player name</label><input name="playerName" required /></div>
                <div className="field"><label>Date of birth</label>
                  <input name="dob" type="date" required onChange={e => setDetails(d => ({ ...d, dob: e.target.value }))} />
                </div>
              </div>

              {isUnder18 && (
                <div className="field" style={{ marginTop: 14 }}>
                  <label>Parent / guardian name</label>
                  <input name="parentName" required />
                </div>
              )}

              <div className="eyebrow mb-3" style={{ marginTop: 24 }}>Contact</div>
              <div className="field"><label>Email — for confirmation</label><input name="email" type="email" required /></div>
              <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 14 }}>
                <div className="field"><label>Phone</label><input name="phone" type="tel" required /></div>
                <div className="field">
                  <label>Emergency contact{isUnder18 && <span style={{ color: '#b91c1c' }}> *</span>}</label>
                  <input name="emergencyContact" required={isUnder18} />
                </div>
              </div>

              <label className="consent-row" style={{ marginTop: 20 }}>
                <input type="checkbox" required />
                <span>I agree to the <a href="#" onClick={e => e.preventDefault()} style={{ color: 'var(--na-navy-600)', fontWeight: 600 }}>Athletic Academy Code of Conduct</a> and the safeguarding policy. Bookings stored on Supabase, payments handled by {payChoice === 'monthly' ? 'GoCardless' : payChoice === 'cash' ? 'cash on the door' : 'Stripe'}.</span>
              </label>

              <button type="submit" className="btn btn-accent btn-lg btn-full" style={{ marginTop: 20 }}>
                {payChoice === 'cash' ? 'Confirm booking →' : 'Continue to pay →'}
              </button>
            </form>
          </div>
        </section>
      </main>
    );
  }

  // ============ STEP 5a — STRIPE-STYLE CARD ============
  if (step === 'pay-card') {
    return (
      <main className="book-stage">
        <div className="book-head">
          <div className="wrap">
            <div className="crumb">
              <a className="crumb-link" onClick={() => setStep('details')}>← Back</a> · Pay for your session
            </div>
            <h1 className="book-h">Pay £6.50 — Stripe Checkout.</h1>
            <p className="lede">Card details are sent securely to Stripe. We don't store them.</p>
          </div>
        </div>
        <section className="section">
          <div className="wrap" style={{ maxWidth: 540 }}>
            <form className="checkout-card" onSubmit={e => {
              e.preventDefault();
              finalise({ provider: 'stripe', providerRef: 'pi_' + Math.random().toString(36).slice(2,14) }, details);
            }}>
              <div className="checkout-line"><span>{squad.name} — {selectedSession.date.toLocaleDateString('en-GB', { weekday: 'short', day: '2-digit', month: 'short' })} · {selectedSession.time}</span><span className="tabular">£6.50</span></div>
              <div className="checkout-total"><span>Total</span><span className="tabular">£6.50</span></div>
              <div className="field" style={{ marginTop: 18 }}><label>Card number</label><input placeholder="1234 1234 1234 1234" required /></div>
              <div className="grid" style={{ gridTemplateColumns: '1fr 1fr 1fr', gap: 12, marginTop: 12 }}>
                <div className="field"><label>Expiry</label><input placeholder="MM/YY" required /></div>
                <div className="field"><label>CVC</label><input placeholder="CVC" required /></div>
                <div className="field"><label>Postcode</label><input required /></div>
              </div>
              <button type="submit" className="btn btn-accent btn-lg btn-full" style={{ marginTop: 18 }}>Pay for your session — £6.50 →</button>
              <div className="basket-secured" style={{ marginTop: 12 }}><Lock /> Stripe · 3D Secure if needed</div>
            </form>
          </div>
        </section>
      </main>
    );
  }

  // ============ STEP 5b — GOCARDLESS MANDATE ============
  if (step === 'pay-mandate') {
    return (
      <main className="book-stage">
        <div className="book-head">
          <div className="wrap">
            <div className="crumb">
              <a className="crumb-link" onClick={() => setStep('details')}>← Back</a> · Direct Debit setup
            </div>
            <h1 className="book-h">Set up your Direct Debit.</h1>
            <p className="lede">£{squad.monthly}/month for unlimited {squad.name} training. First charge on the 1st of next month. You'll finish setup securely on GoCardless.</p>
          </div>
        </div>
        <section className="section">
          <div className="wrap" style={{ maxWidth: 540 }}>
            <div className="checkout-card">
              <div className="checkout-line"><span>{squad.name} monthly</span><span className="tabular">£{squad.monthly}.00</span></div>
              <div className="checkout-line"><span>First charge</span><span>1st of next month</span></div>
              <div className="checkout-total"><span>Today</span><span className="tabular">£0.00</span></div>
              <p className="ink-soft" style={{ fontSize: 13.5, lineHeight: 1.55, marginTop: 16 }}>
                Tap below to set up your Direct Debit securely with GoCardless. They'll collect your name, email and bank details on their FCA-regulated page — we never see or store your bank information. Protected by the Direct Debit Guarantee; cancel any time with 30 days' notice.
              </p>
              {ddError && (
                <div role="alert" style={{ marginTop: 14, fontSize: 13, color: 'var(--na-red-700)', background: 'var(--na-red-100)', padding: '10px 12px', borderRadius: 'var(--radius-sm)', border: '1px solid var(--na-red-200)' }}>
                  {ddError}
                </div>
              )}
              <button type="button" className="btn btn-accent btn-lg btn-full" disabled={ddBusy === squad.id} style={{ marginTop: 18 }} onClick={() => startDirectDebit(squad)}>
                {ddBusy === squad.id ? 'Redirecting…' : 'Set up Direct Debit →'}
              </button>
              <div className="basket-secured" style={{ marginTop: 12 }}><Lock /> GoCardless · FCA-regulated</div>
            </div>
          </div>
        </section>
      </main>
    );
  }

  // ============ CONFIRMATION ============
  if (step === 'done' && confirmRecord) {
    const c = confirmRecord;
    return (
      <main className="book-stage">
        <div className="book-head">
          <div className="wrap" style={{ textAlign: 'center' }}>
            <div className="success-tick" style={{ margin: '0 auto 24px' }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" width="32" height="32"><path d="M20 6L9 17l-5-5" /></svg>
            </div>
            <div className="crumb">Confirmed</div>
            <h1 className="book-h">{c.plan === 'monthly' ? "You're a member." : "You're booked."}</h1>
            <p className="lede" style={{ margin: '0 auto' }}>
              {c.plan === 'monthly'
                ? <>You're set up on {c.squadName} monthly membership. First Direct Debit on {c.firstChargeDate}, then monthly. Confirmation in your inbox.</>
                : <>{c.squadName} on {c.sessionDate} · {c.sessionTime} at {c.sessionVenue}. Confirmation emailed.</>}
            </p>
          </div>
        </div>

        <section className="section">
          <div className="wrap" style={{ maxWidth: 720 }}>
            <div className="confirm-card">
              <div className="eyebrow mb-3">Add to your calendar</div>
              <div className="cal-buttons">
                <button className="cal-btn"><span>G</span> Google Calendar</button>
                <button className="cal-btn"><span></span> Apple Calendar</button>
                <button className="cal-btn"><span>O</span> Outlook</button>
              </div>

              <div className="eyebrow mb-3" style={{ marginTop: 28 }}>What happens next</div>
              <div className="confirm-steps">
                {c.plan === 'monthly' ? (
                  <>
                    <div className="confirm-step"><span className="confirm-step-num">01</span><div><strong>Welcome email — within an hour.</strong><span className="ink-soft"> Includes safeguarding pack and your first training date.</span></div></div>
                    <div className="confirm-step"><span className="confirm-step-num">02</span><div><strong>Auto-marked in registers.</strong><span className="ink-soft"> Coaches see you as paid in the coach app — no need to bring cash.</span></div></div>
                    <div className="confirm-step"><span className="confirm-step-num">03</span><div><strong>First Direct Debit on {c.firstChargeDate}.</strong><span className="ink-soft"> £{c.monthlyAmount}.00, monthly. Cancel any time.</span></div></div>
                  </>
                ) : c.plan === 'cash' ? (
                  <>
                    <div className="confirm-step"><span className="confirm-step-num">01</span><div><strong>Booked — pay cash on arrival.</strong><span className="ink-soft"> Coach will collect £6.50 before tip-off and mark you in.</span></div></div>
                    <div className="confirm-step"><span className="confirm-step-num">02</span><div><strong>Reminder 24h before.</strong><span className="ink-soft"> Time, venue, and what to bring.</span></div></div>
                    <div className="confirm-step"><span className="confirm-step-num">03</span><div><strong>Liked it? Set up monthly →</strong><span className="ink-soft"> Cheaper per session if you train more than 3× a month.</span></div></div>
                  </>
                ) : (
                  <>
                    <div className="confirm-step"><span className="confirm-step-num">01</span><div><strong>Receipt emailed now.</strong><span className="ink-soft"> Reference {c.providerRef}.</span></div></div>
                    <div className="confirm-step"><span className="confirm-step-num">02</span><div><strong>Synced to registers on the day.</strong><span className="ink-soft"> Coach app marks you paid right before tip-off.</span></div></div>
                    <div className="confirm-step"><span className="confirm-step-num">03</span><div><strong>Reminder 24h before.</strong><span className="ink-soft"> Includes venue, time, and what to bring.</span></div></div>
                  </>
                )}
              </div>

              {c.plan !== 'monthly' && (
                <div className="upsell">
                  <div>
                    <strong>Liked this?</strong>
                    <p>Set up monthly Direct Debit for unlimited training — cheaper per session.</p>
                  </div>
                  <button className="btn btn-accent" onClick={() => { setPayChoice('monthly'); setStep('pay-mandate'); }}>Set up monthly DD →</button>
                </div>
              )}

              <details className="coach-trace">
                <summary>Coach-app sync record (Supabase POST payload)</summary>
                <pre>{JSON.stringify(c, null, 2)}</pre>
              </details>

              <div className="flex gap-3" style={{ marginTop: 24, justifyContent: 'center', flexWrap: 'wrap' }}>
                <button className="btn btn-soft" onClick={() => { setPage('home'); reset(); }}>Back to home</button>
                <button className="btn btn-soft" onClick={reset}>Book another →</button>
              </div>
            </div>
          </div>
        </section>
      </main>
    );
  }

  function reset() {
    setStep('squad'); setSquadId(null); setSelectedSession(null);
    setPayChoice(null); setDetails({}); setConfirmRecord(null); setSelectedDay(null);
  }

  function finalise(payProvider, det) {
    const isMonthly = payChoice === 'monthly';
    const record = {
      // Player data
      playerName: det.playerName,
      dob: det.dob,
      parentName: det.parentName || null,
      email: det.email,
      phone: det.phone,
      emergencyContact: det.emergencyContact || null,

      // Squad / session
      squad: squad.id,
      squadName: squad.name,
      sessionId: !isMonthly && selectedSession ? selectedSession.id : null,
      sessionDate: !isMonthly && selectedSession ? selectedSession.date.toLocaleDateString('en-GB', { weekday: 'short', day: '2-digit', month: 'short' }) : null,
      sessionTime: !isMonthly && selectedSession ? selectedSession.time : null,
      sessionVenue: !isMonthly && selectedSession ? selectedSession.venue : squad.venue,

      // Payment
      plan: payChoice, // 'monthly' | 'payg' | 'cash'
      provider: payProvider.provider,
      providerRef: payProvider.providerRef,
      stripePaymentIntentId: payProvider.provider === 'stripe' ? payProvider.providerRef : null,
      goCardlessMandateId: payProvider.provider === 'gocardless' ? payProvider.providerRef : null,
      amount: isMonthly ? squad.monthly : 6.50,
      currency: 'GBP',
      monthlyAmount: isMonthly ? squad.monthly : null,
      firstChargeDate: payProvider.firstChargeDate || null,

      // Coach-app status hint
      coachAppStatus: isMonthly ? 'PAID — auto-marked attended on every session'
                     : payChoice === 'cash' ? 'CASH PENDING — collect on the door'
                     : 'PAID — sync to register on session day',

      capturedAt: new Date().toISOString(),
    };
    setConfirmRecord(record);
    setStep('done');
  }
}

// ----------------- Helpers -----------------
function Tick() { return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" width="14" height="14"><path d="M20 6L9 17l-5-5" /></svg>; }
function Lock() { return <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" width="13" height="13"><path d="M12 11V7a4 4 0 0 1 8 0v4M5 11h14v9H5z" /></svg>; }

function startOfWeek(date) {
  const d = new Date(date);
  const day = d.getDay();
  const diff = day === 0 ? 6 : day - 1; // Monday-start
  d.setDate(d.getDate() - diff);
  d.setHours(0,0,0,0);
  return d;
}
function rangeLabel(weekStart) {
  const end = new Date(weekStart.getTime() + 6 * 86400000);
  const o = { day: 'numeric', month: 'short' };
  return `${weekStart.toLocaleDateString('en-GB', o)} – ${end.toLocaleDateString('en-GB', o)}`;
}
function addHour(time) {
  const [h, m] = time.split(':').map(Number);
  const nh = (h + 1) % 24;
  return `${String(nh).padStart(2,'0')}:${String(m||0).padStart(2,'0')}`;
}
function summarise(training) {
  const parts = training.split('·').map(s => s.trim());
  if (parts.length <= 2) return parts.join(' + ');
  return parts.slice(0, 2).join(' + ') + ' + more';
}
function seedRand(str) {
  let h = 0;
  for (let i = 0; i < str.length; i++) h = (h * 31 + str.charCodeAt(i)) & 0xffffffff;
  return ((h >>> 0) % 1000) / 1000;
}

window.SessionsPage = SessionsPage;
