/* global React, GAMES, COLLECTIONS, Icon, GameCard, Shelf, t, PATREON_LOGIN_URL, useGameProgress */

function GamesPage({ auth, setPage }) {
  const [filter, setFilter] = React.useState('all');
  const { data: gameProgressData } = useGameProgress();

  const progressBySlug = React.useMemo(() => {
    const rows = Array.isArray(gameProgressData)
      ? gameProgressData
      : Array.isArray(gameProgressData && gameProgressData.items)
        ? gameProgressData.items
        : [];

    return rows.reduce((acc, row) => {
      if (!row || !row.slug) return acc;
      const value = Math.max(0, Math.min(1, Number(row.progress) || 0));
      acc[row.slug] = value;
      return acc;
    }, {});
  }, [gameProgressData]);

  const games = React.useMemo(() => (
    GAMES.map((g) => ({ ...g, progress: progressBySlug[g.slug] ?? 0 }))
  ), [progressBySlug]);

  const filtered = games.filter(g => filter==='all' ? true : g.collection === filter);
  const isGuest = !auth || auth.name === '';
  // Only show the Patreon upsell to users who would actually benefit (guests or
  // logged-in users who aren't yet supporters with the coin multiplier).
  const showPatreonUpsell = isGuest || (auth && auth.supporter === 'none');

  return (
    <div className="container fade-in">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginTop: 12, marginBottom: 20, flexWrap: 'wrap', gap: 16 }}>
        <div>
          <div className="eyebrow">{t('games.library')}</div>
          <h1 className="h-display" style={{ fontSize: 'clamp(36px, 4.5vw, 52px)', marginTop: 6 }}>{t('games.title')}</h1>
          <p style={{ color: 'var(--muted)', margin: '10px 0 0', maxWidth: 560 }}>
            {t('games.desc')}
          </p>
        </div>
        <div className="tabs" style={{ margin: 0 }}>
          {[['all',t('games.filter_all')],['vorenka',t('games.filter_vorenka')],['velvet',t('games.filter_velvet')]].map(([id, label]) => (
            <button key={id} onClick={()=>setFilter(id)} className={`tab ${filter===id?'tab--active':''}`}>{label}</button>
          ))}
        </div>
      </div>

      {filter === 'all' ? (
        <>
          <Shelf collection="vorenka" title={t('coll.vorenka')} sub={t('coll.vorenka_sub')} setPage={setPage} games={games} />
          <Shelf collection="velvet" title={t('coll.velvet')} sub={t('coll.velvet_sub')} setPage={setPage} games={games} />
        </>
      ) : (
        <div className="shelf" style={{ marginTop: 24 }}>
          {filtered.map(g => <GameCard key={g.slug} g={g} progress={g.progress} />)}
        </div>
      )}

      {/* Patreon upsell at end, hidden for users who already have supporter benefits */}
      {showPatreonUpsell && (
        <div className="upsell upsell--patreon" style={{ marginTop: 48 }}>
          <div className="upsell__ic"><Icon name="support" size={22}/></div>
          <div>
            <p className="upsell__ttl">
              {isGuest ? t('games.patreon_title') : t('games.patreon_title_loggedin')}
            </p>
            <p className="upsell__sub">{t('games.patreon_sub')}</p>
          </div>
          {isGuest ? (
            <button className="btn btn--primary" onClick={()=>{ window.location.href = PATREON_LOGIN_URL; }}>
              {t('games.login_patreon')}<Icon name="arrow" size={14}/>
            </button>
          ) : (
            <button className="btn btn--primary" onClick={()=>setPage('support')}>
              {t('action.support')}<Icon name="arrow" size={14}/>
            </button>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { GamesPage });
