// Type definitions for the press5 Play browser SDK (protocol v2).
// SDK:   https://play.press5.xyz/sdk/v1/press5-play.js  (global Press5Play)  or  .mjs (ES module)
// Types: https://play.press5.xyz/sdk/v1/press5-play.d.ts
// Docs:  https://my.press5.xyz/docs/multiplayer   Errors: https://my.press5.xyz/docs/multiplayer/errors
//
// Two kinds of room:
//   relay rooms   (no "server" block in press5.game.json): players share state and messages, the host
//                 player's browser runs the rules. Hold them to fair limits with a "guard" block.
//   server rooms  ("server": { "engine": "arena" | "turns" | "party" }): press5's engine runs the rules;
//                 the game sends inputs (arena) or actions (turns, party) and draws what comes back.
//
// Quick start:
//   const play = await Press5Play.connect({ name: 'Ada' });
//   const room = await play.quickMatch();
//   room.setMyState({ x: 10, y: 20 });                  // relay: your own state
//   for (const p of room.others()) draw(room.smoothState(p.id));

export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
export type State = { [key: string]: Json };
export type Unsubscribe = () => void;

/** An error from press5 Play. `code` is stable; `fix` says what to change; `docs` links to it. */
export interface PlayError extends Error {
  code: string;
  fix?: string;
  docs?: string;
  /** How long until it may work, in ms (guard_locked: the lockout left). */
  retryMs?: number;
}

/** room.guardSmooth(target): press5 Guard corrections applied to `target` at once, drawn easing in. */
export interface GuardSmoother {
  /** The value to draw for one key (the corrected value plus what is left of the ease). */
  get(key: string): any;
  /** A copy of the target with the eases applied: draw from this. */
  view(out?: { [key: string]: any }): { [key: string]: any };
  /** What is left of the ease for one key (0 when settled). */
  offset(key: string): number;
  /** True while any key is still easing. */
  easing(): boolean;
  /** Stop listening for corrections. */
  off: Unsubscribe;
}

/** Press5Play.guardNotice(...): what to tell a player press5 Guard (or the game's owner) took out. */
export interface GuardNotice {
  /** "guard" (removed from the room), "guard_locked" (locked out for a while), "banned" / "guard_banned" (by the game's owner). */
  code: 'guard' | 'guard_locked' | 'banned' | 'guard_banned';
  banned: boolean;
  /** Date.now() when they may play again; 0 when not known (or banned). */
  until: number;
  /** ms left of the lockout. */
  left(): number;
  /** The line to show right now, with the countdown ("... You can play again in 1:42."). */
  text(): string;
}

export interface ConnectOptions {
  /** The player's name (1-24 characters; HTML characters are removed). */
  name?: string;
  /** Server URL. Default wss://play.press5.xyz/v1. On localhost pages only, ?play=ws://... overrides it. */
  url?: string;
  /** A game key (p5g_...) for native builds and local testing. Web pages on the launch pad need none. */
  key?: string;
  /** The game's site name, for local development only. */
  game?: string;
  /** How far smoothState/entities run behind, in ms (default 100). */
  interpDelay?: number;
  /** Use UDP/WebTransport datagrams for arena games when the browser can (default true). */
  datagrams?: boolean;
  /** A WebSocket implementation, outside browsers. */
  WebSocket?: unknown;
}

export interface Limits {
  msgPerSec: number;
  bytesPerSec: number;
  maxMessage: number;
  roomState: number;
  playerState: number;
  roomPlayers: number;
}

export interface GameInfo {
  id: string;
  kind: 'site' | 'native';
  title: string;
  maxPlayers: number;
  modes: string[];
  tickRate: number;
}

export interface RoomOptions {
  /** Room size (2-64, at most the game's maxPlayers). */
  maxPlayers?: number;
  /** One of the game's "modes" in press5.game.json. */
  mode?: string;
  /** Up to 8 short keys; quick match only joins rooms with the same filters. Keys may not start with "_". */
  filters?: { [key: string]: string | number | boolean };
}

export interface CreateRoomOptions extends RoomOptions {
  /** Only joinable by code (room.code): party games, playing with friends. */
  private?: boolean;
  /** Room meta (up to 2 KB), visible to players in the room. */
  meta?: State;
  /** Starting room state (relay rooms only). */
  state?: State;
}

export interface RoomSummary {
  code: string;
  mode: string;
  players: number;
  maxPlayers: number;
  createdAt: number;
  meta?: State;
}

export interface LeaderboardEntry {
  rank: number;
  name: string;
  score: number;
  wins: number;
  games: number;
  best?: number;
  /** Elo, for games with "rated": true. */
  rating?: number;
}

export interface Player {
  id: string;
  name: string;
  seat: number;
  /** This player's own state (relay rooms): what they set with setMyState. */
  state: State;
  /** Disconnected, holding their place while they reconnect. */
  away: boolean;
  joinedAt: number;
}

// ---- server rooms ---------------------------------------------------------------------------------

/** arena controls, sent once a tick by the SDK. */
export interface ArenaInput {
  /** Move, -1..1 each. */
  mx?: number;
  my?: number;
  /** Aim direction (any length). */
  ax?: number;
  ay?: number;
  /** true for the first weapon, or a weapon number. */
  fire?: boolean | number;
  /** Platformers (world.gravity > 0). */
  jump?: boolean;
}

export interface ArenaPlayer {
  id: string;
  name?: string;
  x: number;
  y: number;
  vx?: number;
  vy?: number;
  ax: number;
  ay: number;
  hp: number;
  dead: boolean;
  team: number;
  ground?: boolean;
  score: number;
}

export interface ArenaPickup { id: string; x: number; y: number; kind: string }
export interface ArenaShot { id: string; x: number; y: number; vx: number; vy: number; owner: string; weapon: number; until: number }
export interface ArenaRay { x: number; y: number; ax: number; ay: number; len: number; owner: string; hit: string | null; at: number }
export interface ArenaRound { phase: 'play' | 'end' | string; n: number; msLeft: number; teams?: number[] }

/** turns: room.view */
export interface TurnsView {
  ph: 'wait' | 'play' | 'end';
  rules: string;
  seats: string[];
  turn: number;
  /** Your seat (-1 when watching). */
  you: number;
  /** Server time the turn ends (0: no clock). */
  deadline: number;
  moves: number;
  result: 0 | { winner?: number; draw?: boolean; why: string };
  rematch: string[];
  /** The rule pack's view: board, last move, your hand (card-table), ... see engine_reference. */
  game: { [key: string]: Json };
}

/** party: room.view */
/** party quiz / poll / guess: room.view */
export interface PartyView {
  ph: 'lobby' | 'question' | 'reveal' | 'end';
  mode: 'quiz' | 'poll' | 'guess';
  n: number;
  of: number;
  /** Server time this phase ends. */
  until: number;
  /** quiz/poll: how many answered; guess: how many got it right. */
  answered: number;
  players: number;
  /** Scores by player id. */
  sc: { [id: string]: number };
  q?: string;
  /** quiz/poll only. */
  choices?: string[];
  /** quiz/poll: your choice (-1 none); guess: whether you got it and your tries so far. */
  mine?: number | { right: boolean; tries: number };
  /** After the reveal. quiz/poll: the right choice's index (-1 in a poll); guess: the first accepted answer. */
  answer?: number | string;
  /** Points each player gained this question, by id. */
  gained?: { [id: string]: number };
  counts?: number[];
}

/** party draw (a drawing and guessing game): room.view */
export interface DrawView {
  ph: 'lobby' | 'choose' | 'draw' | 'reveal' | 'end';
  mode: 'draw';
  /** This turn's number, and how many turns the game has. */
  n: number;
  of: number;
  /** Who draws this turn. */
  drawer: string | null;
  /** The drawer only, while choosing: the words to pick from (act('choose', { word })). */
  choices?: string[];
  /** The drawer while drawing; everyone after the reveal. */
  word?: string;
  /** While drawing: "_ _ a _ _" (letters show as time runs out). */
  hint?: string;
  /** Ids of players who have guessed it this turn. */
  guessed: string[];
  mine: { right: boolean; tries: number };
  until: number;
  players: number;
  sc: { [id: string]: number };
  gained?: { [id: string]: number };
}

/** party draw: one stroke segment (x, y from 0 to 1 of the canvas). */
export interface Stroke { s: [number, number][]; c: string; w: number; new: boolean }

export interface EngineInfo {
  name: 'arena' | 'turns' | 'party';
  version: number;
  tickRate: number;
  patchEvery: number;
  /** The engine settings players may see (secrets such as quiz answers are left out). */
  config: { [key: string]: Json };
}

// ---- events ---------------------------------------------------------------------------------------

export interface RoomEvents {
  /** Someone joined. */
  join: (player: Player) => void;
  /** Someone left (reason: "left", "kicked", "guard", "timeout", ...). */
  leave: (player: Player, reason: string) => void;
  away: (player: Player) => void;
  back: (player: Player) => void;
  name: (player: Player) => void;
  /** The host moved to another player. */
  host: (id: string, player: Player | undefined) => void;
  /** Relay: room state changed (keys changed, the patch). Server rooms: a new view. */
  state: (keysOrView: string[] | { [key: string]: Json }, patch?: State) => void;
  /** Relay: another player's state changed. */
  playerState: (player: Player, keys: string[], patch: State) => void;
  /** A message from room.send. */
  message: (data: Json, from: Player | { id: string }) => void;
  binary: (bytes: Uint8Array, from: Player | null) => void;
  meta: (meta: State, locked: boolean) => void;
  /**
   * press5 Guard corrected values that broke the game's "guard" limits: apply them, e.g.
   * room.on('guard', (me) => { if (me.x !== undefined) player.x = me.x; })
   * For your own player's position, room.guardSmooth(player) does this and eases the drawing in.
   */
  guard: (me: State, room: State) => void;
  /**
   * This client left the room (reason: "left", "kicked", "guard", "banned", "room_error", ...).
   * info.retryMs: after "guard", how long the lockout from the game lasts. Press5Play.guardNotice(reason, info)
   * gives the message to show.
   */
  end: (reason: string, info: { retryMs?: number }) => void;
  /** Any engine event (also emitted under its own name: hit, ko, spawn, pickup, round, shot, start, move, over, question, reveal, ...). */
  event: (type: string, data: { [key: string]: Json }) => void;
  /** party draw: the drawer drew (sent to everyone else). */
  stroke: (stroke: Stroke) => void;
  /** party draw: the drawing so far, for a player who joined mid-turn. */
  canvas: (data: { strokes: Stroke[] }) => void;
  /** party draw: a wrong guess (the chat). Right guesses arrive as "guessed", never with their text. */
  guess: (data: { id: string; name: string; text: string }) => void;
  /** party guess/draw: someone got it. */
  guessed: (data: { id: string; name: string }) => void;
  /** party draw: a letter was shown. */
  hint: (data: { hint: string }) => void;
  /** party draw: a new turn (the drawer now chooses a word). */
  turn: (data: { drawer: string; n: number; of: number }) => void;
  /** party draw: the drawer chose; drawing has started. */
  drawing: (data: { drawer: string; hint: string; len: number }) => void;
  [engineEvent: string]: (...args: any[]) => void;
}

export interface ClientEvents {
  error: (error: PlayError) => void;
  reconnecting: (info: { code: number; reason: string }) => void;
  reconnected: (info: { resumed: boolean }) => void;
  disconnected: (reason: string) => void;
  restart: () => void;
  /** Arena datagrams (UDP/WebTransport) came up (true) or fell back to the WebSocket (false). */
  datagrams: (live: boolean) => void;
}

export declare class Emitter<E> {
  on<K extends keyof E & string>(event: K, fn: E[K]): Unsubscribe;
  once<K extends keyof E & string>(event: K, fn: E[K]): Unsubscribe;
  off<K extends keyof E & string>(event: K, fn: E[K]): void;
}

export declare class Room extends Emitter<RoomEvents> {
  /** 6-letter code; show it so friends can joinRoom(code). */
  readonly code: string;
  readonly mode: string;
  readonly private: boolean;
  readonly locked: boolean;
  readonly maxPlayers: number;
  readonly filters: State;
  readonly meta: State;
  /** The host's player id. */
  readonly host: string;
  /** Relay rooms: the shared room state (only the host writes it). */
  readonly state: State;
  readonly players: { [id: string]: Player };
  readonly tickRate: number;
  /** Your player id. */
  readonly you: string;
  readonly id: string;
  readonly isHost: boolean;
  readonly me: Player | undefined;
  readonly ended: boolean;
  /** Server rooms only: which engine runs this room. */
  readonly engine?: EngineInfo;
  /** Server rooms only: the latest view from the engine (TurnsView, PartyView, or arena's raw view). */
  readonly view: TurnsView | PartyView | DrawView | { [key: string]: Json } | null;
  readonly client: Client;

  playerList(): Player[];
  others(): Player[];
  player(id: string): Player | null;
  playerBySeat(seat: number): Player | null;

  // relay rooms
  /** Your own state: merged and sent once a tick. Checked against the game's "guard" limits. */
  setMyState(patch: State): void;
  /** Room state, host only (throws not_host otherwise). */
  setState(patch: State): void;
  /** Another player's state about interpDelay ms in the past, smoothed between updates. */
  smoothState(id: string): State | null;
  /**
   * press5 Guard corrections without the jolt: each correction is applied to `target` (your own
   * player object) at once, and smoother.view() eases what you draw there over opts.ms (default 100).
   * Keys: opts.keys, else any the correction names that `target` has.
   */
  guardSmooth(target: { [key: string]: any }, opts?: { ms?: number; keys?: string[] }): GuardSmoother;
  /** To everyone, or to one player id or a list of ids (secrets go to one player). Counts against the guard "messages" limits. */
  send(data: Json, to?: string | string[]): void;
  sendBinary(bytes: Uint8Array | ArrayBuffer | number[], toSeat?: number): void;
  onMessage(fn: (data: Json, from: Player | { id: string }) => void): Unsubscribe;
  /** Messages whose data.type is `type`. */
  onMessage(type: string, fn: (data: any, from: Player | { id: string }) => void): Unsubscribe;
  onJoin(fn: RoomEvents['join']): Unsubscribe;
  onLeave(fn: RoomEvents['leave']): Unsubscribe;
  onHostChange(fn: RoomEvents['host']): Unsubscribe;
  onStateChange(fn: RoomEvents['state']): Unsubscribe;
  onEnd(fn: RoomEvents['end']): Unsubscribe;

  // host
  lock(): Promise<unknown>;
  unlock(): Promise<unknown>;
  kick(id: string): Promise<unknown>;
  makeHost(id: string): Promise<unknown>;
  setMeta(meta: State): Promise<unknown>;
  leave(): Promise<void>;

  // server rooms
  /** arena: your controls (merged; the SDK sends them once a tick and predicts your movement). */
  setInput(input: ArenaInput): void;
  /** turns / party: an engine action, e.g. act('move', { x: 3 }), act('answer', { choice: 1 }), act('start'). */
  act(type: string, data?: Json): Promise<Json | undefined>;
  /** arena: your player, predicted (instant). */
  mine(): ArenaPlayer | null;
  /** arena: everyone else, smoothed. */
  entities(): ArenaPlayer[];
  pickups(): ArenaPickup[];
  shots(): ArenaShot[];
  /** Hitscan rays from the last 200 ms, for drawing. */
  rays(): ArenaRay[];
  round(): ArenaRound;
  scores(): { [id: string]: number };
}

export declare class Client extends Emitter<ClientEvents> {
  readonly id: string | null;
  readonly name: string | null;
  readonly game: GameInfo | null;
  readonly limits: Limits | null;
  readonly room: Room | null;
  readonly connected: boolean;
  /** Round-trip time to the server, ms. */
  readonly rtt: number;
  /** This device's signed guest id (leaderboards know the player by it; random, not personal). */
  readonly guest?: string;

  /** Server clock in ms (use it for countdowns: deadlines and "until" are server times). */
  serverTime(): number;
  /** The fullest open room that fits, or a new one. */
  quickMatch(opts?: RoomOptions): Promise<Room>;
  createRoom(opts?: CreateRoomOptions): Promise<Room>;
  /** Join by 6-letter code (case does not matter). */
  joinRoom(code: string): Promise<Room>;
  listRooms(opts?: RoomOptions): Promise<RoomSummary[]>;
  setName(name: string): Promise<string>;
  /** This game's leaderboard (server-engine games only). */
  leaderboard(period?: 'all' | 'week' | 'day'): Promise<LeaderboardEntry[]>;
  close(): void;
}

export declare class Interpolator {
  constructor(opts?: { delay?: number; size?: number; angles?: string[] });
  push(id: string, serverTimeMs: number, values: { [key: string]: number }): void;
  get(id: string, serverTimeMs: number): { [key: string]: number } | null;
  remove(id: string): void;
}

export interface Press5PlayApi {
  readonly VERSION: string;
  /** Connect and say hello. Rejects with a PlayError (code, message, fix, docs). */
  connect(opts?: ConnectOptions): Promise<Client>;
  Interpolator: typeof Interpolator;
  Client: typeof Client;
  Room: typeof Room;
  Arena: unknown;
  applyDelta(base: Json, delta: Json): Json;
  /**
   * What to tell a player press5 Guard took out, from room.onEnd's (reason, info) or a join error;
   * null when it wasn't the guard.
   */
  guardNotice(reasonOrError: string | PlayError | null | undefined, info?: { retryMs?: number }): GuardNotice | null;
}

declare const Press5Play: Press5PlayApi;
export default Press5Play;
export declare const connect: Press5PlayApi['connect'];
export declare const VERSION: string;

declare global {
  /** The global from <script src="https://play.press5.xyz/sdk/v1/press5-play.js">. */
  // eslint-disable-next-line no-var
  var Press5Play: Press5PlayApi;
}
