/* screens/Group.jsx — predictions editor. window.GroupScreen */
function GroupScreen({ store, go }) {
  const { useState, useEffect, useRef } = React;
  const [filter, setFilter] = useState('all');
  const { results } = store.state;
  const groups = window.WC.groupOrder;
  const visible = filter === 'all' ? groups : [filter];
  const predicted = window.WC.fixtures.filter((f) => results[f.id] && results[f.id].o).length;

  // Fire bwcp_bracket_complete exactly once when all 72 group picks are done
  const completedRef = useRef(false);
  useEffect(() => {
    if (!completedRef.current && predicted === 72) {
      completedRef.current = true;
      window.bwcpTrack?.('bwcp_bracket_complete');
    }
  }, [predicted]);

  return (
    <div className="page">
      <header className="phead">
        <div>
          <div className="eyebrow">Step 01 · Group stage</div>
          <h1 className="section-h">Predict the groups</h1>
          <p className="muted phead__sub">72 matches across 12 groups. Pick a result — add a scoreline for the tie-breaks. Top two of each group, plus the eight best third-placed teams, advance.</p>
        </div>
        <div className="phead__side">
          <div className="bigprog">
            <div className="bigprog__n display tnum">{predicted}<span>/72</span></div>
            <div className="meter" style={{ width: 160 }}><i style={{ width: (predicted / 72 * 100) + '%' }} /></div>
          </div>
          <div className="row" style={{ gap: 8 }}>
            <Btn variant="quiet" size="sm" onClick={store.fillFavourites}>Fill favourites</Btn>
            <Btn size="sm" onClick={() => go('knockout')}>To bracket <IconArrow size={14} /></Btn>
          </div>
        </div>
      </header>

      <div className="gfilter">
        <button className="chip" data-on={filter === 'all' ? 1 : 0} onClick={() => setFilter('all')}>All groups</button>
        {groups.map((g) => (
          <button key={g} className="chip" data-on={filter === g ? 1 : 0} onClick={() => setFilter(g)}>{g}</button>
        ))}
      </div>

      <div className="ggrid">
        {visible.map((g) => (
          <GroupCard key={g} group={g} results={results} onSet={store.setResult} />
        ))}
      </div>
    </div>
  );
}
window.GroupScreen = GroupScreen;
