import type { Card, Session } from './types' const SESSION_KEY = 'sapbg-session' async function post(path: string, body: unknown): Promise { const res = await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }) const data = await res.json() if (!res.ok) throw new Error(data.error ?? 'request failed') return data as Session } export type BotDifficulty = 'easy' | 'medium' | 'hard' export function createGame(name: string): Promise { return post('/api/games', { name }) } export function joinGame(code: string, name: string): Promise { return post('/api/join', { code, name }) } export async function fetchCatalog(pack?: string): Promise { const url = pack ? `/api/catalog?pack=${encodeURIComponent(pack)}` : '/api/catalog' const res = await fetch(url) if (!res.ok) throw new Error('failed to load catalog') return (await res.json()) as Card[] } export function loadSession(): Session | null { try { const raw = localStorage.getItem(SESSION_KEY) return raw ? (JSON.parse(raw) as Session) : null } catch { return null } } export function saveSession(s: Session) { localStorage.setItem(SESSION_KEY, JSON.stringify(s)) } export function clearSession() { localStorage.removeItem(SESSION_KEY) }