import * as THREE from 'three';

const LIFE = 0.8;

export class DamageNumber {
  sprite: THREE.Sprite;
  private mat: THREE.SpriteMaterial;
  private life = LIFE;

  constructor(
    scene: THREE.Scene,
    text: string,
    pos: THREE.Vector3,
    color = '#ffffff'
  ) {
    const canvas = document.createElement('canvas');
    canvas.width = 128;
    canvas.height = 64;
    const ctx = canvas.getContext('2d')!;
    ctx.font = 'bold 40px monospace';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.lineWidth = 6;
    ctx.strokeStyle = '#000';
    ctx.strokeText(text, 64, 32);
    ctx.fillStyle = color;
    ctx.fillText(text, 64, 32);

    this.mat = new THREE.SpriteMaterial({
      map: new THREE.CanvasTexture(canvas),
      transparent: true,
      depthWrite: false,
    });
    this.sprite = new THREE.Sprite(this.mat);
    this.sprite.position.copy(pos);
    this.sprite.position.y += 2.6;
    this.sprite.scale.set(2, 1, 1);
    scene.add(this.sprite);
  }

  update(dt: number): boolean {
    this.life -= dt;
    this.sprite.position.y += dt * 1.6;
    this.mat.opacity = this.life < 0.3 ? this.life / 0.3 : 1;
    return this.life > 0;
  }

  dispose(scene: THREE.Scene) {
    scene.remove(this.sprite);
    this.mat.map?.dispose();
    this.mat.dispose();
  }
}
