// The renderer: one render target at one texel per character cell, then the
// fullscreen pass that turns it into glyphs. It draws what it is handed and keeps
// only the meshes that belong to an id, so a piece keeps its mesh for its whole life.
import * as THREE from 'three';
import { hostile, toWorld, type Body, type Kind, type Loose, type Ore, type Ship, type Shot, type System } from '../sim';
import { barrenMesh, shipyardMesh, starMesh } from './bodies';
import { Galaxy } from './galaxy';
import { CELL, CELL_WORLD, snapCell } from './grid';
import { FRAG, GLYPHS, PALETTE, VERT, lum, paletteTexture, textAtlas } from './ink';
import { crosshair, reticle, TONE } from './marks';
import { oreChunk, paint, piece, shade, type Part, type Role, type Wear } from './pieces';
import { free, plate } from './shapes';

export { CELL, CELL_WORLD, GALAXY_MAX, GALAXY_MIN, ZOOM_MAX, ZOOM_MIN } from './grid';
export { TONE } from './marks';
export { PIECE_R } from './shapes';

const SHOT_LEN = 13; // world units of laser line behind a round
const SHOT_W = 1.6; // world units thick: one bright cell wide
const FUEL_CELLS = 12; // the fuel gauge is this many cells wide at any zoom
const FUEL_WORD = 'FUEL'; // a word, not glyphs: letters are spelled out per cell
const MAP_WORD = '[M]AP'; // the hint that there is a second scene, under the bar

export type Camera = { x: number; y: number; zoom: number };
export class View {
  private renderer: THREE.WebGLRenderer;
  private scene = new THREE.Scene();
  private camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
  private rt: THREE.WebGLRenderTarget;
  private pass: THREE.ShaderMaterial;
  private quad = new THREE.Scene();
  private pieceMeshes = new Map<number, THREE.Group>();
  private oreMeshes = new Map<number, THREE.Group>();
  private shotMeshes = new Map<number, Part>();
  private bodyMeshes = new Map<number, THREE.Group>();
  private marker = crosshair();
  private cursor = reticle();
  private hud = new THREE.Scene();
  private hudCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
  private galaxy = new Galaxy();
  private fuelBar = new THREE.Group();
  private fuelCells: Part[] = [];
  private cols = 0;
  private rows = 0;

  constructor(private canvas: HTMLCanvasElement) {
    THREE.ColorManagement.enabled = false;
    this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false });
    this.renderer.outputColorSpace = THREE.LinearSRGBColorSpace;
    this.scene.add(this.marker);
    // The fuel gauge is geometry in a HUD layer, not a page overlay: it is built
    // from the same cells as everything else, so it reads as part of the game,
    // and it is measured in cells rather than in the world, so flying cannot make
    // it hop from one cell to the next.
    this.hudCam.position.z = 10;
    this.hud.add(this.fuelBar);
    this.cursor.visible = false;
    this.hud.add(this.cursor);
    for (let i = 0; i < FUEL_CELLS; i++) {
      const m = plate(1, 1, 1);
      this.fuelCells.push(m);
      this.fuelBar.add(m);
    }
    this.rt = new THREE.WebGLRenderTarget(1, 1, {
      depthBuffer: false,
      stencilBuffer: false,
      minFilter: THREE.LinearFilter,
      magFilter: THREE.LinearFilter,
    });
    this.pass = new THREE.ShaderMaterial({
      vertexShader: VERT,
      fragmentShader: FRAG,
      uniforms: {
        uScene: { value: this.rt.texture },
        uAtlas: { value: textAtlas(GLYPHS) },
        uPalette: { value: paletteTexture() },
        uBg: { value: new THREE.Color(PALETTE[0]) },
        uCells: { value: new THREE.Vector2() },
        uCellPx: { value: CELL },
        uWord: { value: textAtlas(FUEL_WORD) },
        uWordCell: { value: new THREE.Vector4() },
        uWordCol: { value: new THREE.Color(PALETTE[5]) },
        uWord2: { value: textAtlas(MAP_WORD) },
        uWord2Cell: { value: new THREE.Vector4() },
        uWord2Col: { value: new THREE.Color(PALETTE[4]) },
      },
    });
    const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.pass);
    quad.frustumCulled = false;
    this.quad.add(quad);
    this.resize();
  }

  // Built once: a body keeps an identity for the whole run, only its place moves.
  // The mesh is rebuilt if that identity ever changes: a galaxy is generated per
  // server boot, and a client that stays connected through a restart must not keep
  // drawing the old planet under the new one.
  private bodies(bs: Body[], t: number): void {
    const seen = new Set<number>();
    for (const b of bs) {
      seen.add(b.id);
      let m = this.bodyMeshes.get(b.id);
      if (m && (m.userData.kind !== b.kind || m.userData.r !== b.r)) {
        free(m);
        this.scene.remove(m);
        this.bodyMeshes.delete(b.id);
        m = undefined;
      }
      if (!m) {
        m = b.kind === 'star' ? starMesh(b.r) : b.kind === 'shipyard' ? shipyardMesh(b.r) : barrenMesh(b.r);
        m.position.z = -1;
        m.userData.spin = b.kind === 'star' ? 0.08 : 0.15; // slow enough to read as alive
        m.userData.kind = b.kind;
        m.userData.r = b.r;
        this.scene.add(m);
        this.bodyMeshes.set(b.id, m);
      }
      m.position.set(b.x, b.y, -1);
      m.rotation.z = t * m.userData.spin;
    }
    for (const [id, m] of this.bodyMeshes) {
      if (seen.has(id)) continue;
      free(m);
      this.scene.remove(m);
      this.bodyMeshes.delete(id);
    }
  }

  resize(): void {
    // Whole cells only: the canvas, the frustum and the glyph grid must describe
    // the same rectangle, or world positions land half a cell off their glyph.
    const dpr = Math.min(devicePixelRatio, 2);
    this.cols = Math.max(1, Math.floor(innerWidth / CELL));
    this.rows = Math.max(1, Math.floor(innerHeight / CELL));
    const w = this.cols * CELL;
    const h = this.rows * CELL;
    this.renderer.setPixelRatio(dpr);
    this.renderer.setSize(w, h, false);
    this.canvas.style.width = `${w}px`;
    this.canvas.style.height = `${h}px`;
    this.rt.setSize(this.cols, this.rows);
    this.pass.uniforms.uCells.value.set(this.cols, this.rows);
    // One HUD unit is one cell, so a plate of size 1 covers exactly one glyph.
    this.hudCam.left = -this.cols / 2;
    this.hudCam.right = this.cols / 2;
    this.hudCam.top = this.rows / 2;
    this.hudCam.bottom = -this.rows / 2;
    this.hudCam.updateProjectionMatrix();
    this.pass.uniforms.uCellPx.value = CELL * dpr;
  }

  // One mesh per piece, whether it is bolted to a hull or drifting loose: ids are
  // unique across the world, so a torn-off piece stays the same mesh.
  private place(
    id: number,
    kind: Kind,
    role: Role,
    x: number,
    y: number,
    h: number,
    w: Wear,
    hostile: boolean,
    seen: Set<number>,
  ): void {
    seen.add(id);
    let g = this.pieceMeshes.get(id);
    if (!g) {
      g = piece(kind);
      this.pieceMeshes.set(id, g);
      this.scene.add(g);
    }
    paint(g, role, w, hostile);
    g.position.set(x, y, 0);
    g.rotation.z = h;
  }

  // The pointer, in cells from the top left corner: one cell is one glyph, so the
  // mark sits on the cell the click will resolve to and nowhere between them. The
  // tone says what that cell holds.
  setPointer(cx: number | null, cy = 0, tone: THREE.Color = TONE.space): void {
    this.cursor.visible = cx !== null;
    if (cx === null) return;
    this.cursor.position.set(cx - this.cols / 2 + 0.5, this.rows / 2 - cy - 0.5, 1);
    for (const p of this.cursor.children) (p as Part).material.color.copy(tone);
  }

  // The fuel gauge is a row of cells two rows off the bottom of the screen, in a
  // layer that only knows about cells. Gold while there is plenty, and a red pulse
  // that quickens as the tank empties. To its right, the map hint, which is a
  // reminder of a control and not a control of its own.
  private fuel(own: Ship | undefined, t: number, hint = true): void {
    this.fuelBar.visible = !!own && own.fuelmax > 0;
    this.pass.uniforms.uWordCell.value.set(0, 0, 0, 0); // no tank, no word
    this.pass.uniforms.uWord2Cell.value.set(0, 0, 0, 0);
    if (!own || own.fuelmax <= 0) return;
    const start = Math.floor((this.cols - FUEL_CELLS) / 2);
    const ratio = Math.max(0, Math.min(1, own.fuel / own.fuelmax));
    const lit = Math.ceil(ratio * FUEL_CELLS);
    const low = ratio <= 0.25;
    // The pulse never dims a lit cell into the same glyph band as the empty
    // track, or the gauge would look shorter than it is while it warns.
    const blink = 0.45 + 0.55 * (0.5 + 0.5 * Math.sin(t * (6 + 120 * (0.25 - ratio))));
    // A cell t is centred on t+0.5 measured from the edge, so this lands on glyphs.
    const x = start - this.cols / 2 + 0.5;
    const y = 2 - this.rows / 2 + 0.5;
    // The label sits on the same row, one cell clear of the bar, and the hint sits
    // one cell clear of the bar's other end.
    const w = Math.max(0, start - 1 - FUEL_WORD.length);
    this.pass.uniforms.uWordCell.value.set(w, 2, FUEL_WORD.length, 1);
    if (hint) {
      const h = Math.min(start + FUEL_CELLS + 1, this.cols - MAP_WORD.length);
      this.pass.uniforms.uWord2Cell.value.set(h, 2, MAP_WORD.length, 1);
    }
    for (let i = 0; i < FUEL_CELLS; i++) {
      const m = this.fuelCells[i];
      m.position.set(x + i, y, 0);
      m.scale.set(0.85, 0.85, 1);
      m.material.color.copy(i < lit ? lum(low ? blink : 1, low ? 14 : 6) : lum(0.22, 2));
    }
  }

  draw(
    cam: Camera,
    bodies: Body[],
    ships: Ship[],
    ownId: number,
    shots: Shot[],
    loose: Loose[],
    ore: Ore[],
    marker: { x: number; y: number } | null,
  ): void {
    // Zoom is world units per character cell: the raster keeps one texel per
    // cell, so zooming only changes how much world a cell covers.
    const wpc = this.frame(cam);
    // Bodies sit behind the ships: the server says where, we only draw them.
    this.bodies(bodies, performance.now() / 1000);

    const seen = new Set<number>();
    const me = ships.find((s) => s.id === ownId);
    for (const s of ships) {
      const role: Role = s.id === ownId ? 'own' : s.side === 'rogue' ? 'rogue' : s.ai ? 'ai' : 'other';
      // A ship is an enemy by the server's own rule: a rogue always, anyone else
      // the moment one of the two has declared it.
      const enemy = hostile(me, s);
      for (const p of s.pieces) {
        const w = toWorld(s, p);
        this.place(p.id, p.kind, role, w.x, w.y, s.h, p, enemy, seen);
      }
    }
    for (const l of loose) this.place(l.id, l.kind, 'loose', l.x, l.y, l.h, l, false, seen);
    for (const [id, g] of this.pieceMeshes) {
      if (seen.has(id)) continue;
      free(g);
      this.scene.remove(g);
      this.pieceMeshes.delete(id);
    }
    // Ore is its own thing: not a piece, so it never snaps onto a hull. Towed ore
    // lights up like a hull so a full line reads at a glance.
    const oreSeen = new Set<number>();
    for (const o of ore) {
      oreSeen.add(o.id);
      let g = this.oreMeshes.get(o.id);
      if (!g) {
        g = oreChunk();
        this.oreMeshes.set(o.id, g);
        this.scene.add(g);
      }
      shade(g, o.towed ? 'towed' : 'ore');
      g.position.set(o.x, o.y, 0);
      g.rotation.z = o.h;
    }
    for (const [id, g] of this.oreMeshes) {
      if (oreSeen.has(id)) continue;
      free(g);
      this.scene.remove(g);
      this.oreMeshes.delete(id);
    }
    // A round is a laser line lying along its heading, so a dodged shot is read as
    // a line passing by the hull rather than a dot that vanished. It is never eased:
    // a round has to be where the server says or it cannot be trusted to dodge.
    const shotSeen = new Set<number>();
    for (const s of shots) {
      shotSeen.add(s.id);
      let m = this.shotMeshes.get(s.id);
      if (!m) {
        m = plate(SHOT_LEN, SHOT_W, 1);
        m.material.color.copy(lum(1, 7));
        m.renderOrder = 1;
        this.shotMeshes.set(s.id, m);
        this.scene.add(m);
      }
      // One cell wide at every zoom, like every other thing that is a mark rather
      // than a body: at the far zoom a world-sized line would be a dim smudge.
      m.scale.set(1, wpc / SHOT_W, 1);
      m.position.set(s.x - Math.cos(s.h) * SHOT_LEN * 0.5, s.y - Math.sin(s.h) * SHOT_LEN * 0.5, 0);
      m.rotation.z = s.h;
    }
    for (const [id, m] of this.shotMeshes) {
      if (shotSeen.has(id)) continue;
      free(m);
      this.scene.remove(m);
      this.shotMeshes.delete(id);
    }
    this.marker.visible = marker !== null;
    if (marker) {
      // The marker is one cell per plate, so it is scaled into cells and snapped to
      // the cell it is on, exactly like the pointer ring.
      this.marker.scale.setScalar(wpc);
      this.marker.position.set(
        snapCell(marker.x, cam.x, wpc, this.cols),
        snapCell(marker.y, cam.y, wpc, this.rows, -1),
        0.5,
      );
    }
    this.fuel(ships.find((s) => s.id === ownId), performance.now() / 1000);

    this.present(this.scene);
  }

  // Scene 2: the map. Nothing of local space is drawn: at a hundred world units to
  // the cell a hull, an ore or a round is not a glyph, it is noise.
  drawGalaxy(cam: Camera, systems: System[], ships: Ship[], ownId: number): void {
    const wpc = this.frame(cam);
    this.galaxy.show(cam, systems, ships, ownId, wpc, this.cols, this.rows);
    // No map hint on the map itself: you are already there.
    this.fuel(ships.find((s) => s.id === ownId), performance.now() / 1000, false);
    this.present(this.galaxy.scene);
  }

  // The frustum is one rectangle of whole cells in either scene: only how much
  // world a cell covers changes.
  private frame(cam: Camera): number {
    const wpc = CELL_WORLD / cam.zoom;
    const hw = (this.cols / 2) * wpc;
    const hh = (this.rows / 2) * wpc;
    this.camera.left = -hw;
    this.camera.right = hw;
    this.camera.top = hh;
    this.camera.bottom = -hh;
    this.camera.updateProjectionMatrix();
    this.camera.position.set(cam.x, cam.y, 10);
    return wpc;
  }

  // Down to one texel per cell, the HUD over it, then the pass that turns every
  // texel into a glyph. Both scenes end here.
  private present(scene: THREE.Scene): void {
    this.renderer.setRenderTarget(this.rt);
    this.renderer.clear();
    this.renderer.render(scene, this.camera);
    this.renderer.autoClear = false; // the HUD draws over the world, cell for cell
    this.renderer.render(this.hud, this.hudCam);
    this.renderer.autoClear = true;
    this.renderer.setRenderTarget(null);
    this.renderer.render(this.quad, new THREE.Camera());
  }
}
