/**
 * @fileoverview Utility module for CRTMonitor.js
 * 
 * @module games.cripto.ui.CRTMonitor
 */

export default class CRTMonitor {
  constructor(scene, width, height) {
    this.scene = scene;
    this.width = width;
    this.height = height;

    this.container = scene.add.container(width / 2, height / 2);
    this.contentLayer = scene.add.container(-width / 2, -height / 2);

    this.init();
  }

  init() {
    // 1. Fundo do Monitor (Verde Escuro)
    const bg = this.scene.add.rectangle(
      0,
      0,
      this.width,
      this.height,
      0x001100,
    );

    // 2. Scanlines (Linhas horizontais)
    this.createScanlinesTexture();
    const scanlines = this.scene.add.image(0, 0, "scanlines-texture");
    scanlines.setAlpha(0.3); // Opacidade das linhas

    // 3. Vignette (Sombra nos cantos)
    this.createVignetteTexture();
    const vignette = this.scene.add.image(0, 0, "vignette-texture");
    vignette.setAlpha(0.8);

    // --- ORDEM DE MONTAGEM ---
    this.container.add(bg);
    this.container.add(this.contentLayer);
    this.container.add(scanlines);
    this.container.add(vignette);
  }

  addContent(gameObject) {
    this.contentLayer.add(gameObject);
  }

  clearContent() {
    this.contentLayer.removeAll(true);
  }

  createScanlinesTexture() {
    if (this.scene.textures.exists("scanlines-texture")) return;

    const graphics = this.scene.make.graphics();
    graphics.fillStyle(0x000000);

    for (let y = 0; y < this.height; y += 3) {
      graphics.fillRect(0, y, this.width, 1);
    }

    graphics.generateTexture("scanlines-texture", this.width, this.height);
    graphics.destroy();
  }

  createVignetteTexture() {
    if (this.scene.textures.exists("vignette-texture")) return;

    const canvas = this.scene.textures.createCanvas(
      "vignette-texture",
      this.width,
      this.height,
    );
    const ctx = canvas.context;

    const gradient = ctx.createRadialGradient(
      this.width / 2,
      this.height / 2,
      this.width * 0.3, // Centro
      this.width / 2,
      this.height / 2,
      this.width * 0.7, // Bordas
    );

    gradient.addColorStop(0, "rgba(0, 0, 0, 0)");
    gradient.addColorStop(1, "rgba(0, 0, 0, 0.8)"); // Borda escura

    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, this.width, this.height);

    canvas.refresh();
  }

  getContainer() {
    return this.container;
  }

  getContentLayer() {
    return this.contentLayer;
  }
}
