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

// ============== TEAM ENQUIRY MODAL ==============
function TeamEnquiryModal({ squad, onClose }) {
  const [status, setStatus] = useState('idle'); // 'idle' | 'sending' | 'sent' | 'error'
  const [errMsg, setErrMsg] = useState('');
  const [form, setForm] = useState({ first_name: '', last_name: '', email: '', player_info: '', message: '' });
  const [hp, setHp] = useState(''); // honeypot — must stay empty
  const startedAt = React.useRef(Date.now());
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  if (!squad) return null;

  const submit = async (e) => {
    e.preventDefault();
    setStatus('sending');
    setErrMsg('');
    // Spam guard — silently succeed without writing or starting a mandate.
    if (naSupabase.looksLikeSpam({ honeypot: hp, startedAt: startedAt.current })) {
      setStatus('sent');
      return;
    }
    try {
      // Save the trial enquiry to Supabase so the coach app sees it.
      // No payment / Direct Debit at this stage — this is just an enquiry;
      // the coach follows up and sets up payment separately if it goes ahead.
      await naSupabase.submitEnquiry({
        source: 'team_trial',
        squad_id: squad.id,
        first_name: form.first_name.trim(),
        last_name: form.last_name.trim(),
        email: form.email.trim(),
        player_info: form.player_info.trim(),
        message: form.message.trim(),
      });
      setStatus('sent');
    } catch (err) {
      console.warn('Trial enquiry 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' }}>Message sent.</h3>
            <p className="ink-soft" style={{ fontSize: 15, lineHeight: 1.5, maxWidth: '40ch', margin: '0 auto 20px' }}>
              {squad.coach} will be in touch within a few days about trying out for {squad.name}.
            </p>
            <button className="btn btn-soft" onClick={onClose}>Close</button>
          </div>
        ) : (
          <>
            <div className="eyebrow eyebrow-orange">Enquire · {squad.name}</div>
            <h3 style={{ fontFamily: 'var(--font-serif)', fontWeight: 600, fontSize: 28, letterSpacing: '-0.01em', margin: '8px 0 6px' }}>
              Message {squad.coach}.
            </h3>
            <p className="ink-soft" style={{ fontSize: 14, marginBottom: 20 }}>
              Trials, late entry, or just a question — drop a line and the head coach will come back to you.
            </p>
            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {/* Honeypot — hidden from humans, bots fill it. Leave empty. */}
              <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }}>
                <label>Company<input type="text" tabIndex="-1" autoComplete="off" value={hp} onChange={e => setHp(e.target.value)} /></label>
              </div>
              <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div className="field"><label>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="field"><label>Email</label><input type="email" required value={form.email} onChange={e => set('email', e.target.value)} disabled={sending} /></div>
              <div className="field"><label>Player age &amp; position</label><input placeholder="e.g. 13, guard" value={form.player_info} onChange={e => set('player_info', e.target.value)} disabled={sending} /></div>
              <div className="field"><label>Message</label><textarea rows="3" placeholder="A bit about yourself or your child..." 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…' : <>Send enquiry →</>}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

// ============== TEAMS PAGE ==============
function TeamsPage({ setPage }) {
  const { Photo, FilterBar } = NASite;
  const { SQUADS, COACHES } = NA_DATA;

  const [active, setActive] = useState('all');
  const [enquireSquad, setEnquireSquad] = useState(null);
  const [rosters, setRosters] = useState({}); // { squad_id: [players] }
  const [fixturesBySquad, setFixturesBySquad] = useState({});
  const [rosterStatus, setRosterStatus] = useState('loading'); // 'loading' | 'ok' | 'error' | 'empty'

  // Pull rosters + upcoming fixtures from Supabase on mount.
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const [roster, fixtures] = await Promise.all([
          naSupabase.fetchRosters(),
          naSupabase.fetchFixtures(),
        ]);
        if (cancelled) return;
        setRosters(naSupabase.groupBy(roster, 'squad_id'));
        const upcoming = {};
        fixtures
          .map(naSupabase.normaliseFixture)
          .filter(f => f.status === 'upcoming')
          .forEach(f => { if (!upcoming[f.squad]) upcoming[f.squad] = f; });
        setFixturesBySquad(upcoming);
        setRosterStatus(roster.length ? 'ok' : 'empty');
      } catch (e) {
        if (!cancelled) setRosterStatus('error');
        console.warn('Supabase rosters/fixtures fetch failed:', e);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const TIERS = [
    { id: 'national', title: 'National League', sub: 'Invite only — players are selected at trials.' },
    { id: 'ybl', title: 'YBL', sub: 'Registration open — prices coming soon.' },
    { id: 'local', title: 'Local League', sub: 'Open to all · sign up online and pay monthly by Direct Debit.' },
  ];
  // U12 (tier 'open') is shown alongside the Local League teams.
  const groupFor = (id) => (id === 'open' ? 'local' : id);

  const levelColor = (lvl) => {
    if (lvl === 'National') return { bg: '#FCD53A', fg: '#0A1626' };
    if (lvl === 'Regional') return { bg: '#1E4FA8', fg: '#fff' };
    if (lvl === 'University') return { bg: '#2d65c9', fg: '#fff' };
    return { bg: '#e5ebfa', fg: '#0A1626' };
  };

  return (
    <main>
      <div className="page-head">
        <div className="wrap">
          <div className="crumb">Club / Teams</div>
          <h1>The squads.</h1>
          <p className="lede">Eleven teams across three tiers — National League (invite only), YBL, and our open Local League. Local League and U12 are open to all; click a team to sign up or message the coach.</p>
        </div>
      </div>

      <section className="section">
        <div className="wrap">
          {TIERS.map(tier => {
            const squadsInTier = SQUADS.filter(s => groupFor(s.tier) === tier.id);
            if (!squadsInTier.length) return null;
            return (
              <div key={tier.id} className="teams-tier">
                <div className="teams-tier-head">
                  <div className="eyebrow eyebrow-orange">{tier.title}</div>
                  <p className="teams-tier-sub ink-soft">{tier.sub}</p>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                  {squadsInTier.map(s => {
              const coach = COACHES.find(c => c.squad === s.id);
              const upcoming = fixturesBySquad[s.id];
              const roster = rosters[s.id] || [];
              return (
                <div key={s.id} className="card team-card" style={{ padding: 0, overflow: 'hidden' }}>
                  <div className="team-card-grid">
                    <Photo variant={`photo-v${(SQUADS.indexOf(s) % 6) + 1}`} tag={s.tag}
                           src={s.photo} focal={s.focal}
                           style={{ borderRadius: 0, minHeight: 320 }} />
                    <div style={{ padding: 28, display: 'flex', flexDirection: 'column' }}>
                      <div className="flex aic gap-3" style={{ marginBottom: 10 }}>
                        <span className={`dot ${s.dotClass}`} style={{ width: 14, height: 14 }}></span>
                        <span className="eyebrow">{s.tag}</span>
                      </div>
                      <h2 style={{ fontFamily: 'var(--font-serif)', fontWeight: 600, fontSize: 40, letterSpacing: '-0.02em', margin: 0 }}>
                        {s.name}
                      </h2>
                      <p style={{ fontSize: 15, color: 'var(--ink-soft)', marginTop: 10, maxWidth: '52ch' }}>{s.blurb}</p>

                      {/* Leagues — multi-entry */}
                      <div style={{ marginTop: 16 }}>
                        <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 700, marginBottom: 10 }}>Competing in</div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                          {s.leagues.map((lg, i) => {
                            const c = levelColor(lg.level);
                            return (
                              <div key={i} className="league-row">
                                <span className="league-badge" style={{ background: c.bg, color: c.fg }}>{lg.level}</span>
                                <span className="league-name">{lg.name}</span>
                                <span className="league-record tabular ink-soft">{lg.record}</span>
                                <span className="league-pos tabular">{lg.position}</span>
                              </div>
                            );
                          })}
                        </div>
                      </div>

                      {/* Roster — only published for adult squads (Senior, U23).
                          Junior rosters stay private for safeguarding. */}
                      {roster.length > 0 && ['senior','u23'].includes(s.id) && (
                        <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
                            <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 700 }}>Roster · {roster.length}</div>
                            <div className="ink-soft" style={{ fontSize: 12 }}>Live from coach app</div>
                          </div>
                          <div className="roster-chips">
                            {roster.map((p, i) => (
                              <span key={i} className="roster-chip">
                                {p.jersey_no != null && <span className="roster-chip-no tabular">#{p.jersey_no}</span>}
                                <span>{p.first_name} {p.last_initial}.</span>
                              </span>
                            ))}
                          </div>
                        </div>
                      )}

                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20, marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
                        <div>
                          <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Coach</div>
                          <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{coach ? coach.name : s.coach}</div>
                        </div>
                        <div>
                          <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Training</div>
                          <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{s.training}</div>
                        </div>
                        <div>
                          <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Home venue</div>
                          <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>{s.venue}</div>
                        </div>
                        <div>
                          <div style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-mute)', fontWeight: 600 }}>Monthly</div>
                          <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }} className="tabular">
                            {s.inviteOnly ? 'Invite only' : s.priceTBC ? 'Coming soon' : `£${s.monthly}/mo`}
                          </div>
                        </div>
                      </div>
                      <div className="flex aic jcs gap-3" style={{ marginTop: 18 }}>
                        {s.bookable ? (
                          <button className="btn btn-accent" onClick={() => setPage('sessions')}>
                            Sign up &amp; pay · £{s.monthly}/mo →
                          </button>
                        ) : (
                          <button className="btn btn-accent" onClick={() => setEnquireSquad(s)}>
                            {s.inviteOnly ? `Enquire about ${s.short} →` : `Register interest →`}
                          </button>
                        )}
                      </div>
                    </div>
                    <div className="team-next">
                      <div className="team-next-label">Next fixture</div>
                      {upcoming ? (
                        <>
                          <div className="team-next-date tabular">{upcoming.fullDate.replace(/^[A-Za-z]+ /, '')}</div>
                          <div className="team-next-day">{upcoming.fullDate.split(' ')[0]}</div>
                          <div className="team-next-vs">
                            <span className="team-next-prep">{upcoming.home ? 'vs' : 'at'}</span>{' '}
                            <span className="team-next-opp">{upcoming.opponent}</span>
                          </div>
                          <div className="team-next-meta">
                            <div><span className="lbl">Tip-off</span><span className="val tabular">{upcoming.tipoff}</span></div>
                            <div><span className="lbl">Venue</span><span className="val">{upcoming.venue || 'TBC'}</span></div>
                          </div>
                        </>
                      ) : (
                        <>
                          <div className="team-next-date" style={{ fontStyle: 'italic', color: 'var(--ink-mute)' }}>TBC</div>
                          <div className="team-next-vs" style={{ color: 'var(--ink-soft)', fontSize: 14 }}>
                            Next fixture to be confirmed.
                          </div>
                          <div className="team-next-meta">
                            <div><span className="lbl">Home venue</span><span className="val">{s.venue}</span></div>
                          </div>
                        </>
                      )}
                    </div>
                  </div>
                </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
        </div>
      </section>

      <TeamEnquiryModal squad={enquireSquad} onClose={() => setEnquireSquad(null)} />
    </main>
  );
}

// ============== FIXTURES PAGE ==============
// Reads from Supabase view `fixtures`. Falls back to in-code FIXTURES if empty
// or unreachable. No code editing — fixtures are added via the coach app.
function FixturesPage() {
  const { FixtureRow, FilterBar } = NASite;
  const { FIXTURES, SQUADS } = NA_DATA;

  const [tab, setTab] = useState('upcoming');
  const [squad, setSquad] = useState('all');
  const [expanded, setExpanded] = useState(null);
  const [remoteFixtures, setRemoteFixtures] = useState(null);
  const [loadState, setLoadState] = useState('loading'); // 'loading' | 'ok' | 'empty' | 'error'
  const [loadMsg, setLoadMsg] = useState('');

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const rows = await naSupabase.fetchFixtures();
        if (cancelled) return;
        const parsed = rows.map(naSupabase.normaliseFixture);
        setRemoteFixtures(parsed);
        if (parsed.length === 0) {
          setLoadState('empty');
        } else {
          setLoadState('ok');
          setLoadMsg(`${parsed.length} fixture${parsed.length === 1 ? '' : 's'} live from the coach app.`);
        }
      } catch (e) {
        if (cancelled) return;
        setLoadState('error');
        setLoadMsg(e.message || 'Could not reach Supabase');
      }
    })();
    return () => { cancelled = true; };
  }, []);

  // Only ever render REAL fixtures from the coach app. Never fall back to
  // placeholder games — an unpublished schedule shows "to be announced".
  const sourceFixtures = remoteFixtures || [];

  const tabs = [
    { id: 'upcoming', label: 'Upcoming' },
    { id: 'past', label: 'Results' },
  ];
  const squadFilters = [
    { id: 'all', label: 'All' },
    ...SQUADS.map(s => ({ id: s.id, label: s.short, dotClass: s.dotClass })),
  ];

  const filtered = sourceFixtures.filter(f =>
    f.status === tab && (squad === 'all' || f.squad === squad)
  );

  return (
    <main>
      <div className="page-head">
        <div className="wrap">
          <div className="crumb">Club / Fixtures</div>
          <h1>Fixtures &amp; results.</h1>
          <p className="lede">Every match across the club, published by the coaches. Filter by squad. Tap any row for venue, tip-off, and travel notes.</p>
        </div>
      </div>

      <section className="section">
        <div className="wrap">

          {/* Live-data banner */}
          <div className={'sheet-banner sheet-' + (loadState === 'empty' ? 'idle' : loadState)}>
            <div className="sheet-banner-icon">
              {loadState === 'ok' ? '✓' : loadState === 'loading' ? '…' : loadState === 'error' ? '!' : '✎'}
            </div>
            <div className="sheet-banner-body">
              <strong>
                {loadState === 'ok' && 'Live from the coach app'}
                {loadState === 'loading' && 'Loading fixtures…'}
                {loadState === 'error' && 'Couldn’t reach the coach app'}
                {loadState === 'empty' && 'Schedule to be announced'}
              </strong>
              <span className="ink-soft">
                {loadState === 'ok' && ` — ${loadMsg} Add or edit fixtures in the coach app and they appear here automatically.`}
                {loadState === 'loading' && ' — fetching live data from Supabase.'}
                {loadState === 'error' && ` — ${loadMsg}. Check back shortly.`}
                {loadState === 'empty' && ' — fixtures will appear here as soon as the coaches publish them.'}
              </span>
            </div>
          </div>

          <div className="flex aic jcs mb-6" style={{ flexWrap: 'wrap', gap: 16, marginTop: 24 }}>
            <FilterBar items={tabs} value={tab} onChange={setTab} />
            <FilterBar items={squadFilters} value={squad} onChange={setSquad} />
          </div>

          {filtered.length === 0 ? (
            <div className="card card-pad text-center" style={{ padding: 64, color: 'var(--ink-soft)' }}>
              {loadState === 'loading'
                ? 'Loading…'
                : tab === 'upcoming'
                  ? (squad === 'all'
                      ? 'Schedule to be announced — no fixtures published yet. Check back soon.'
                      : 'Schedule to be announced for this squad. Check back soon.')
                  : 'No results to show yet.'}
            </div>
          ) : (
            <div className="fixtures-table">
              {filtered.map(fx => (
                <FixtureRow key={fx.id} fx={fx}
                            expanded={expanded === fx.id}
                            onToggle={() => setExpanded(expanded === fx.id ? null : fx.id)} />
              ))}
            </div>
          )}
        </div>
      </section>
    </main>
  );
}

window.TeamsPage = TeamsPage;
window.FixturesPage = FixturesPage;
