import { PLANETCONFIGS } from "../data/planets.data";
import { TradeRoute } from "../model/routes/trade-route.model";
import { ShipUi } from "../model/ship";
import { GameService } from "../service/game.service";
import { PlanetUi } from "../ui/planet.ui";

export class MapScene extends Phaser.Scene {
  public gameService: GameService = new GameService();
  private camera!: Phaser.Cameras.Scene2D.Camera;
  private isDragging = false;
  private dragStart = new Phaser.Math.Vector2();
  private ship!: ShipUi; // Das Raumschiff
  private ships: ShipUi[] = [];
  private planets: PlanetUi[] = [];


  private lastZoomTime = 0;

  constructor() {
    super({ key: 'MapScene '})
  }

  preload() {
    this.load.image('ship', 'sprites/ships/01-starter.png');
    this.load.image('harbour', 'sprites/buildings/harbour.png');
    this.load.image('planet', 'sprites/planets/sm/planet-1.png');
    this.load.image('terra-nova', 'sprites/planets/sm/terra-nova.png');
    this.load.image('mechanica-prime', 'sprites/planets/sm/mechanica-prime.png');
    this.load.image('novus-reach', 'sprites/planets/sm/novus-reach.png');
    this.load.image('aqualis', 'sprites/planets/sm/aqualis.png');
    this.load.image('ferron', 'sprites/planets/sm/ferron.png');
  }

  create() {
    this.camera = this.cameras.main;

    this.createPlaceHolderGraphic();
    // this.camera.setBackgroundColor('0x99ccff')

    // Weltgröße groß setzen, z. B. 5000x5000 Pixel
    this.camera.setBounds(0, 0, 10000, 10000);
    this.physics.world.setBounds(0, 0, 10000, 10000);
    this.cameras.main.setBounds(0, 0, 10000, 10000);


    /* Sterne */
    for (let i = 0; i< 1000; i++) {
      const x = Phaser.Math.Between(0, 10000);
      const y = Phaser.Math.Between(0, 10000);
      this.add.circle(x, y, Phaser.Math.Between(1, 3), 0x88ccff)
    }

    // Beispiel: ein paar Kreise (Planeten) zeichnen
    this.buildPlanets();

    // Events für Panning
    this.input.on('pointerdown', (pointer: Phaser.Input.Pointer) => {
      if (!this.gameService.canDrag) { return; }
      this.isDragging = true;
      
      this.dragStart.set(pointer.x, pointer.y);
    });

    this.input.on('pointerup', () => {
      this.isDragging = false;
    });

    this.input.on('pointermove', (pointer: Phaser.Input.Pointer) => {
      if (!this.isDragging || !this.gameService.canDrag) return;
      const dragX = pointer.x - this.dragStart.x;
      const dragY = pointer.y - this.dragStart.y;
      this.camera.scrollX -= dragX / this.camera.zoom;
      this.camera.scrollY -= dragY / this.camera.zoom;
      this.dragStart.set(pointer.x, pointer.y);
    });

    // Zoom via Mausrad
    this.input.on('wheel', (_: any, __: number, ___: number, deltaY: number) => {
      const now = Date.now();
      if (now - this.lastZoomTime < 50) return; // nur alle 100ms
      this.lastZoomTime = now;
      const factor = 1.05;
      if (deltaY > 0) {
        this.camera.setZoom(this.camera.zoom / factor);
      } else {
        this.camera.setZoom(this.camera.zoom * factor);
      }

      const minScale = Math.max(window.innerWidth / 10000, window.innerHeight / 10000)
      // Begrenze Zoom
      this.camera.setZoom(Phaser.Math.Clamp(this.camera.zoom, minScale, 1));
    });

    this.createShip();
    setTimeout(() => {
      this.createShip();
    }, 100)


    
  }

  createShip() {
    const s = new ShipUi(this, 100, 100, this.gameService);
    s.model.route = new TradeRoute(this.planets.filter(planet => ['Terra Nova', 'Aqualis'].includes(planet.model.name)).map(planet => planet.model))
    this.ships.push(s)
    this.physics.world.enable(s);
    s.activateRoute();
    this.gameService.ships.push(s.model)
  }

  override update(time: number, delta: number): void {
    if (this.ship) {

      this.ship.update(time, delta);
    }

    for (let ship of this.ships) {
        ship.update(time, delta)
    }
  }
  private buildPlanets() {
    for (let config of PLANETCONFIGS) {
      const planet = new PlanetUi(this, config.x, config.y, config.texture, config.config, this.gameService);
      planet.rightClick.subscribe(planet => {
        this.ship.moveTo(planet);
        this.isDragging = false;
      });
      planet.leftClick.subscribe(planet => {
        this.gameService.showDialog(planet.model);
        this.isDragging = false;
      });
      this.planets.push(planet);
      this.gameService.planets.push(planet.model);
    }
  }

  private createPlaceHolderGraphic() {
    const graphics = this.add.graphics();
    graphics.fillStyle(0x88ccff, 1);
    graphics.fillCircle(100, 100, 100);
    graphics.generateTexture('planet', 200, 200);
    graphics.destroy();
  }

  getPlanetUiByName(name: string) {
    return this.planets.find(p => p.model.name == name);
  }
}