'use client';

import { useEffect, useState } from 'react';

/**
 * Tonight's Slate — anonymous-landing game-count strip (Session 17).
 *
 * Client component (the landing page is itself a client component
 * because it uses `useAuth` for the post-signin redirect). Fetches
 * game counts for NBA / WNBA / MLB through the existing Next.js
 * proxies on mount, dedupes by (away, home, time) triple, renders
 * "X NBA · Y WNBA · Z MLB games being graded right now." with a
 * signup CTA.
 *
 * Hides itself entirely when every sport returns zero — better
 * silent than misleading. The counts come from the same proxies The
 * Slate uses, so post-signup the user sees the same numbers.
 *
 * Co-exists with `LivePropsStrip` (which shows a few actual graded
 * props). This component is the executive-summary line above it.
 */

interface OddsResponse {
  sport?: string;
  props?: Array<{ home_team?: string; away_team?: string; game_time?: string }>;
}

const FETCH_TIMEOUT_MS = 4000;

async function countGamesForSport(sport: string): Promise<number> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
  try {
    const res = await fetch(`/api/odds/${sport}`, {
      signal: controller.signal,
      headers: { Accept: 'application/json' },
    });
    if (!res.ok) return 0;
    const body = (await res.json().catch(() => null)) as OddsResponse | null;
    if (!body || !Array.isArray(body.props)) return 0;
    const games = new Set<string>();
    for (const p of body.props) {
      if (!p.home_team || !p.away_team) continue;
      games.add(`${p.away_team}__${p.home_team}__${p.game_time || ''}`);
    }
    return games.size;
  } catch {
    return 0;
  } finally {
    clearTimeout(timer);
  }
}

export default function TonightsSlate() {
  const [counts, setCounts] = useState<{ nba: number; wnba: number; mlb: number } | null>(null);

  useEffect(() => {
    let alive = true;
    (async () => {
      const [nba, wnba, mlb] = await Promise.all([
        countGamesForSport('nba'),
        countGamesForSport('wnba'),
        countGamesForSport('mlb'),
      ]);
      if (alive) setCounts({ nba, wnba, mlb });
    })();
    return () => { alive = false; };
  }, []);

  if (!counts) return null;

  const total = counts.nba + counts.wnba + counts.mlb;
  if (total === 0) return null;

  const segments: string[] = [];
  if (counts.nba > 0)  segments.push(`${counts.nba} NBA`);
  if (counts.wnba > 0) segments.push(`${counts.wnba} WNBA`);
  if (counts.mlb > 0)  segments.push(`${counts.mlb} MLB`);

  return (
    <section
      style={{
        padding: '20px 24px',
        borderTop: '1px solid var(--border)',
        borderBottom: '1px solid var(--border)',
        background: 'var(--bg-surface)',
      }}
      aria-label="Tonight's slate summary"
    >
      <div
        style={{
          maxWidth: 1100,
          margin: '0 auto',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 16,
          flexWrap: 'wrap',
        }}
      >
        <div>
          <p
            className="mono"
            style={{
              fontSize: 10,
              color: 'var(--text-tertiary)',
              letterSpacing: '0.12em',
              textTransform: 'uppercase',
              marginBottom: 4,
            }}
          >
            Tonight&apos;s Slate
          </p>
          <p style={{ fontSize: 17, fontWeight: 600, color: 'var(--text-primary)' }}>
            {segments.join(' · ')} games being graded right now.
          </p>
        </div>
        <a
          href="/signup"
          className="btn-primary"
          style={{
            padding: '10px 18px',
            fontSize: 13,
            fontWeight: 700,
            textDecoration: 'none',
          }}
        >
          Sign up to grade these →
        </a>
      </div>
    </section>
  );
}
