// What the server reports, plus the eased copies we actually draw: it says where a
// thing is at tick rate, we only smooth the way it gets there. Nothing here decides
// anything, and the camera that follows our ship rides along with it.
import { connect, type State } from './net';
import { pull } from './pull';
import type { Body, Loose, Ore, Ship, Shot } from './sim';
import { cam, snap } from './stage';

export let state: State | null = null;
export const ships = new Map<number, Ship>();
export const loose = new Map<number, Loose>();
export const ore = new Map<number, Ore>();
export const bodies = new Map<number, Body>();
export const shots = new Map<number, Shot>();

const ease = (a: number, b: number, k: number) => a + (b - a) * k;
const turn = (a: number, b: number, k: number) => a + Math.atan2(Math.sin(b - a), Math.cos(b - a)) * k;

// Everything drawn comes from the server. We only send intents: pick up what is
// under the cursor, report the drag, drop it and let the server decide.
const net = connect((s) => {
  const was = state?.you;
  state = s;
  const me = s.players.find((p) => p.id === s.you);
  // A ship we have never followed (the first, or the one we come back as) puts the
  // camera on it at once, so a death never slides the view across the system.
  if (me && s.you !== was) snap(me.x, me.y);
});
export const send = net.send;

// The ship we are flying, if we know it yet.
export const own = (): Ship | undefined => (state ? ships.get(state.you) : undefined);

// The server reports at tick rate; we ease our copies toward it so movement reads
// smooth without ever deciding anything ourselves.
export function apply(dt: number): void {
  const k = 1 - Math.exp(-dt * 12);
  if (state) {
    const live = new Set<number>();
    for (const p of state.players) {
      live.add(p.id);
      let s = ships.get(p.id);
      if (!s) {
        ships.set(p.id, (s = { ...p }));
      } else {
        s.x = ease(s.x, p.x, k);
        s.y = ease(s.y, p.y, k);
        s.h = turn(s.h, p.h, k);
        s.tx = p.tx;
        s.ty = p.ty;
        s.order = p.order;
        s.fuel = p.fuel; // a gauge has to jump, not ease, or it lies about the tank
        s.fuelmax = p.fuelmax;
        s.foe = p.foe;
        s.side = p.side;
        s.pieces = p.pieces; // a hull is never eased: a piece is where the server says
      }
    }
    for (const id of ships.keys()) if (!live.has(id)) ships.delete(id);

    const looseLive = new Set<number>();
    for (const l of state.loose) {
      looseLive.add(l.id);
      const d = loose.get(l.id);
      if (!d) loose.set(l.id, { ...l });
      else if (l.id === state.held && pull.to) {
        d.x = pull.to.x; // in hand: exactly where the pointer put it, no easing
        d.y = pull.to.y;
        d.h = l.h;
      } else {
        d.x = ease(d.x, l.x, k);
        d.y = ease(d.y, l.y, k);
        d.h = turn(d.h, l.h, k);
      }
    }
    for (const id of loose.keys()) if (!looseLive.has(id)) loose.delete(id);

    const oreLive = new Set<number>();
    for (const o of state.ore) {
      oreLive.add(o.id);
      const d = ore.get(o.id);
      if (!d) ore.set(o.id, { ...o });
      else {
        d.x = ease(d.x, o.x, k);
        d.y = ease(d.y, o.y, k);
        d.h = turn(d.h, o.h, k);
        d.towed = o.towed;
      }
    }
    for (const id of ore.keys()) if (!oreLive.has(id)) ore.delete(id);

    // A planet revolves at tick rate too, so its drawn copy is eased just like a
    // hull: a body that jumped a whole tick would step its limb across cells.
    const bodyLive = new Set<number>();
    for (const b of state.bodies) {
      bodyLive.add(b.id);
      const d = bodies.get(b.id);
      bodies.set(b.id, d ? { ...b, x: ease(d.x, b.x, k), y: ease(d.y, b.y, k) } : { ...b });
    }
    for (const id of bodies.keys()) if (!bodyLive.has(id)) bodies.delete(id);

    const shotLive = new Set<number>();
    for (const s of state.shots ?? []) {
      shotLive.add(s.id);
      shots.set(s.id, s); // a round is never eased, it is where the server put it
    }
    for (const id of shots.keys()) if (!shotLive.has(id)) shots.delete(id);
  }
}

// Keep our ship on screen, unless the player has panned away from it. The map is
// a still picture of the whole galaxy: nothing to follow there.
export function follow(dt: number): void {
  const me = own();
  if (cam.scene !== 'local' || !cam.follow || !me) return;
  const c = 1 - Math.exp(-dt * 8);
  cam.x = ease(cam.x, me.x, c);
  cam.y = ease(cam.y, me.y, c);
}
