// One socket is one player. The server owns the world; we send intents and are
// handed back the state to draw.
import type { Body, Loose, Ore, Ship, Shot, System } from './sim';

export type State = {
  you: number;
  held: number;
  bodies: Body[];
  systems: System[];
  loose: Loose[];
  ore: Ore[];
  shots: Shot[];
  players: Ship[];
};

// Dev: vite on :5173, game server on :8090. Prod: Caddy proxies /ws on the same
// origin, so the page's own scheme/host is the right socket.
const url = import.meta.env.DEV
  ? `ws://${location.hostname}:8090/ws`
  : `${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`;

export function connect(onState: (s: State) => void): { send: (msg: unknown) => void } {
  let ws: WebSocket | null = null;
  const open = () => {
    ws = new WebSocket(url);
    ws.onmessage = (e) => {
      const m = JSON.parse(e.data);
      if (m.t === 'state') onState(m);
    };
    ws.onclose = () => setTimeout(open, 500);
  };
  open();
  return {
    send: (msg) => {
      if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(msg));
    },
  };
}
