/**
 * The join page's view of GET /rooms/:roomId/public on the game server, and the idle copy it
 * implies. Pure so the copy rules can be unit-tested.
 */
import { formatShowTime } from './format';

export interface RoomStatus {
  active: boolean;
  kind: 'ALWAYS_ON' | 'CHAMPIONSHIP' | null;
  name: string | null;
  /** Tonight's always-on game is switched on and the bar is inside its opening hours. */
  roundsRunAutomatically: boolean;
  nextChampionship: { name: string; scheduledAt: number } | null;
  /** Phone clock when this status was read (for the 'Today' / 'Fri' wording). */
  checkedAt: number;
}

/** Unknown or malformed fields fall back to the safe reading (inactive, nothing scheduled). */
export function parseRoomStatus(body: Record<string, unknown>, checkedAt: number): RoomStatus {
  const kind = body.activeEventKind === 'ALWAYS_ON' || body.activeEventKind === 'CHAMPIONSHIP' ? body.activeEventKind : null;
  const next = body.nextChampionship as { name?: unknown; scheduledAt?: unknown } | null | undefined;
  return {
    active: body.active === true,
    kind,
    name: typeof body.activeEventName === 'string' ? body.activeEventName : null,
    roundsRunAutomatically: body.alwaysOnEnabled === true && body.openNow === true,
    nextChampionship:
      next && typeof next.name === 'string' && typeof next.scheduledAt === 'number' ? { name: next.name, scheduledAt: next.scheduledAt } : null,
    checkedAt,
  };
}

export interface IdleCopy {
  title: string;
  /** "Next: Friday Night Championship, Fri 9:00 PM", when one is scheduled. */
  next: string | null;
  detail: string;
}

/** What the join page says while no game is running: only promise what will actually happen. */
export function idleCopy(status: RoomStatus | null, timeZone?: string): IdleCopy {
  if (status?.roundsRunAutomatically) {
    return {
      title: 'No game running right now',
      next: null,
      detail: 'Rounds start automatically while the bar is open. Keep this page open — the Join button wakes up as soon as a game starts.',
    };
  }
  if (!status) {
    // Status unknown (game server unreachable): promise nothing about schedules.
    return { title: 'No game running right now', next: null, detail: 'Keep this page open — the Join button wakes up as soon as a game starts.' };
  }
  const n = status.nextChampionship;
  return n
    ? {
        title: 'No games running right now',
        next: `Next: ${n.name}, ${formatShowTime(n.scheduledAt, status.checkedAt, timeZone)}`,
        detail: 'The Join button wakes up when the game opens.',
      }
    : { title: 'No games running right now', next: null, detail: 'Nothing is scheduled here yet — check back on game night.' };
}
