/**
 * Global leaderboard client. Same-origin on partly.party via the /arcade-api/
 * nginx proxy → arcade-landing express. Every call is fire-and-forget with a
 * short timeout and silent failure — the game must never notice a dead server.
 * (In local dev there's no proxy; fetches just fail quietly.)
 */

export interface ScoreRow {
  name: string;
  score: number;
  date: string;
}

const API = '/arcade-api/sando/scores';
const TIMEOUT = 4000;

function withTimeout(ms: number): AbortSignal {
  const c = new AbortController();
  setTimeout(() => c.abort(), ms);
  return c.signal;
}

export async function fetchTop(week: 'omote' | 'ura'): Promise<ScoreRow[]> {
  try {
    const r = await fetch(`${API}?week=${week}`, { signal: withTimeout(TIMEOUT) });
    if (!r.ok) return [];
    const rows = (await r.json()) as ScoreRow[];
    return Array.isArray(rows) ? rows : [];
  } catch {
    return [];
  }
}

export async function submitScore(name: string, score: number, week: 'omote' | 'ura'): Promise<number | null> {
  try {
    const r = await fetch(API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, score, week }),
      signal: withTimeout(TIMEOUT),
    });
    if (!r.ok) return null;
    const j = (await r.json()) as { rank?: number };
    return j.rank ?? null;
  } catch {
    return null;
  }
}

/** The chef's name, remembered once. ponytail: window.prompt is the whole name
 *  entry UI — arcade-appropriate; build letter slots if anyone ever complains. */
export function chefName(): string | null {
  try {
    let n = localStorage.getItem('sandoniette.name');
    if (!n) {
      n = (window.prompt('Your chef name for the board? (3-12 letters)') ?? '').trim().slice(0, 12);
      if (n.length < 3) return null;
      localStorage.setItem('sandoniette.name', n);
    }
    return n;
  } catch {
    return null;
  }
}
