// Home page fixtures / results / table block — driven by live WLL data.
// During off-season the Fixtures tab shows an empty-state message.

const WRENS = 'Blackpool Wren Rovers';

// Collapse repeat scorers — "C King 10', 35'" instead of "C King 10', C King 35'".
const formatScorers = (scorers) => {
  if (!scorers || !scorers.length) return '';
  const byName = [];
  for (const s of scorers) {
    const last = byName[byName.length - 1];
    if (last && last.name === s.name) last.minutes.push(s.minute);
    else byName.push({ name: s.name, minutes: [s.minute] });
  }
  return byName.map(p => `${p.name} ${p.minutes.map(m => m + "'").join(', ')}`).join(' · ');
};

const ordinal = (n) => {
  if (!n) return '';
  const s = ['th','st','nd','rd'];
  const v = n % 100;
  return n + (s[(v - 20) % 10] || s[v] || s[0]);
};

const ResultRow = ({ r }) => {
  const usScore = r.wrensScore;
  const themScore = r.oppScore;
  const tag = r.result;
  const tagBg = tag === 'W' ? 'var(--pitch)' : tag === 'D' ? 'var(--gold)' : 'var(--red-deep)';
  const wrensScorers = formatScorers(r.wrensScorers);
  const oppScorers = formatScorers(r.oppScorers);
  return (
    <a href={r.matchUrl} target="_blank" rel="noopener noreferrer" data-result-row style={{
      display: 'grid', gridTemplateColumns: '110px 1fr auto 28px', gap: 16,
      alignItems: 'start', padding: '18px 22px',
      borderBottom: '1px solid var(--line-soft)',
      cursor: 'pointer', color: 'inherit', textDecoration: 'none',
    }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', color: 'var(--muted)', paddingTop: 2 }}>{r.date}</div>
      <div>
        <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--ink)' }}>
          {r.venue === 'home' ? 'vs ' : '@ '}{r.opponent}
        </div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.16em', marginTop: 4, textTransform: 'uppercase' }}>
          West Lancs Premier · {r.venue === 'home' ? 'Brews Park' : 'Away'}
        </div>
        {(wrensScorers || oppScorers) && (
          <div style={{ marginTop: 10, display: 'flex', flexWrap: 'wrap', gap: 16, alignItems: 'center' }}>
            {wrensScorers && (
              <span style={{ fontSize: 12.5, color: 'var(--ink)', fontWeight: 500 }}>
                <span style={{ color: 'var(--red)', marginRight: 6 }}>{'⚽'}</span>
                {wrensScorers}
              </span>
            )}
            {oppScorers && (
              <span style={{ fontSize: 12.5, color: 'var(--muted)' }}>
                <span style={{ marginRight: 6 }}>{'⚽'}</span>
                {r.opponent}: {oppScorers}
              </span>
            )}
          </div>
        )}
      </div>
      <div className="display" style={{ fontSize: 24, color: 'var(--ink)' }}>
        {usScore}-{themScore}
      </div>
      <div style={{
        width: 28, height: 28, background: tagBg, color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: 'Bebas Neue', fontSize: 16,
      }}>{tag}</div>
    </a>
  );
};

const OffSeasonNotice = () => (
  <div style={{ padding: '64px 32px', textAlign: 'center', background: '#fff' }}>
    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.22em', color: 'var(--red)', fontWeight: 700 }}>
      OFF-SEASON
    </div>
    <div className="display" style={{ fontSize: 36, margin: '12px 0 8px', lineHeight: 1 }}>
      Fixtures return in August
    </div>
    <p style={{ color: 'var(--muted)', fontSize: 14, maxWidth: 460, margin: '0 auto' }}>
      The 2025/26 season is over. The new West Lancashire League Premier Division fixtures will be published when the 2026/27 schedule lands.
    </p>
  </div>
);

const LeagueTable = ({ table }) => {
  if (!table || !table.length) {
    return <div style={{ padding: 32, color: 'var(--muted)' }}>Loading table...</div>;
  }
  return (
    <table data-league-table style={{ width: '100%', borderCollapse: 'collapse' }}>
      <thead>
        <tr style={{ background: 'var(--paper-2)' }}>
          {['#','Team','P','W','D','L','GD','PTS'].map(h => (
            <th key={h} className="mono" style={{
              textAlign: h === 'Team' ? 'left' : 'center', padding: '12px 12px',
              fontSize: 10, letterSpacing: '0.18em', color: 'var(--muted)', fontWeight: 700,
            }}>{h}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {table.map(t => (
          <tr key={t.team} style={{
            borderBottom: '1px solid var(--line-soft)',
            background: t.isWrens ? 'rgba(200,16,46,0.06)' : 'transparent',
          }}>
            <td className="display" style={{ padding: '14px 12px', fontSize: 22, textAlign: 'center', width: 50 }}>{t.position}</td>
            <td style={{ padding: '14px 12px', fontWeight: t.isWrens ? 800 : 500, fontSize: 14 }}>
              {t.isWrens && <span style={{ color: 'var(--red)', marginRight: 8 }}>{'●'}</span>}{t.team}
            </td>
            <td className="mono" style={{ padding: '14px 12px', textAlign: 'center', fontSize: 13 }}>{t.played}</td>
            <td className="mono" style={{ padding: '14px 12px', textAlign: 'center', fontSize: 13 }}>{t.won}</td>
            <td className="mono" style={{ padding: '14px 12px', textAlign: 'center', fontSize: 13 }}>{t.drawn}</td>
            <td className="mono" style={{ padding: '14px 12px', textAlign: 'center', fontSize: 13 }}>{t.lost}</td>
            <td className="mono" style={{ padding: '14px 12px', textAlign: 'center', fontSize: 13, color: t.goalDifference > 0 ? 'var(--pitch)' : t.goalDifference < 0 ? 'var(--red)' : 'var(--ink)' }}>
              {t.goalDifference > 0 ? '+' : ''}{t.goalDifference}
            </td>
            <td className="display" style={{ padding: '14px 12px', textAlign: 'center', fontSize: 22 }}>{t.points}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

const FixturesSection = ({ league, leagueError }) => {
  const [tab, setTab] = React.useState('results');
  const results = (league && league.latestResults) || [];
  const table = (league && league.table) || [];
  const wrens = league && league.wrens;
  const lastUpdated = league && league.lastUpdated;

  return (
    <section style={{ background: 'var(--paper)', padding: '96px 0' }} id="fixtures">
      <div className="container">
        <SectionHead
          kicker="Match Centre - 2025/26"
          title="Fixtures & Results"
          right={
            <div data-tab-row style={{ display: 'flex', gap: 0, border: '1.5px solid var(--ink)' }}>
              {['results','fixtures','table'].map(t => (
                <button key={t} onClick={() => setTab(t)} style={{
                  padding: '12px 20px', border: 'none', cursor: 'pointer',
                  background: tab === t ? 'var(--ink)' : 'transparent',
                  color: tab === t ? '#fff' : 'var(--ink)',
                  fontSize: 11, fontWeight: 700, letterSpacing: '0.18em', textTransform: 'uppercase',
                }}>{t}</button>
              ))}
            </div>
          }
        />

        <div style={{ background: '#fff', border: '1px solid var(--line-soft)' }}>
          <div style={{
            padding: '14px 22px', borderBottom: '2px solid var(--ink)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12,
          }}>
            <span className="display" style={{ fontSize: 22 }}>
              {tab === 'results' ? 'Recent Results' : tab === 'fixtures' ? 'Upcoming Fixtures' : 'West Lancs Premier - Standings'}
            </span>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.18em', color: 'var(--muted)' }}>
              {wrens ? (ordinal(wrens.position) + ' · ' + wrens.points + ' PTS · ' + wrens.played + ' PLAYED') : 'LOADING...'}
            </span>
          </div>

          {leagueError && (
            <div style={{ padding: 24, color: 'var(--red)', fontSize: 13 }}>
              Could not reach the league data feed right now - please try again shortly.
            </div>
          )}

          {!leagueError && tab === 'results' && (
            results.length
              ? results.map((r, i) => <ResultRow key={i} r={r} />)
              : <div style={{ padding: 32, color: 'var(--muted)' }}>Loading results...</div>
          )}

          {!leagueError && tab === 'fixtures' && <OffSeasonNotice />}

          {!leagueError && tab === 'table' && <LeagueTable table={table} />}
        </div>

        {lastUpdated && (
          <div className="mono" style={{
            marginTop: 16, fontSize: 10, letterSpacing: '0.18em', color: 'var(--muted)', textAlign: 'right',
          }}>
            LIVE DATA FROM WESTLANCASHIRELEAGUE.CO.UK · UPDATED {new Date(lastUpdated).toLocaleString('en-GB', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' }).toUpperCase()}
          </div>
        )}
      </div>
    </section>
  );
};

Object.assign(window, { FixturesSection });
