import Phaser from 'phaser';
import { GameMap } from '../core/game-map';
import { Tile } from '../core/tile';
import { BuildingSystem } from '../core/building-system';
import { ResourceManager } from '../core/resource-manager';
import { Worker } from '../core/worker';
import { ProductionSystem } from '../core/production-system';
import { BuildingType } from '../core/building/building';
import { ResouceBuilding } from '../core/building/resource-building';
import { BuildingRenderer } from '../core/building-renderer';

export class GameScene extends Phaser.Scene {
    private map!: GameMap;
    private gfx!: Phaser.GameObjects.Graphics;
    private buildingRenderer!: BuildingRenderer;

    private hoveredTile: { x: number; y: number } | null = null;
    private highlightGfx!: Phaser.GameObjects.Graphics;

    private tileSize = 32;
    private camSpeed = 600;
    private zoom = 1;

    private buildingSystem!: BuildingSystem;
    private productionSystem!: ProductionSystem;
    private selectedBuilding: BuildingType | null = null;

    private resourceManager!: ResourceManager;
    private workers: Worker[] = [];

    constructor() {
        super('GameScene');
    }

    preload() {
      this.load.image('lumberhut', 'assets/lumberhut.png');
    }

    create() {
        this.map = new GameMap(19, 10, 123);
        this.gfx = this.add.graphics();

        // Highlight-Layer (separate Graphics)
        this.highlightGfx = this.add.graphics();
        this.highlightGfx.setDepth(10); // über der Karte zeichnen
        this.buildingRenderer = new BuildingRenderer(this);

        // 📸 Kamera einstellen
        const cam = this.cameras.main;
        cam.setBounds(0, 0, this.map.width * this.tileSize, this.map.height * this.tileSize);
        cam.centerOn(this.map.width * this.tileSize / 2, this.map.height * this.tileSize / 2);
        cam.setZoom(this.zoom);

            // 🕹️ Steuerung
        this.setupCameraControls();
        this.resourceManager = new ResourceManager();
        this.buildingSystem = new BuildingSystem(this.map, this.resourceManager);
        this.productionSystem = new ProductionSystem(this.buildingSystem.getAll())

        // Erstes Rendern
        this.renderMap();

        
        // Testweise standardmäßig Haus als Werkzeug
        this.selectedBuilding = 'lumberjack';

       

        
    }

    private setupCameraControls() {
    const cam = this.cameras.main;
    const keys = this.input.keyboard!.addKeys('W,A,S,D') as Record<string, Phaser.Input.Keyboard.Key>;

    // Bewegung
    this.events.on('update', (_: number, dtMs: number) => {
      const dt = dtMs / 1000;
      if (keys['W'].isDown) cam.scrollY -= this.camSpeed * dt;
      if (keys['S'].isDown) cam.scrollY += this.camSpeed * dt;
      if (keys['A'].isDown) cam.scrollX -= this.camSpeed * dt;
      if (keys['D'].isDown) cam.scrollX += this.camSpeed * dt;
    });

    // Rechtsklick-Drag
    this.input.on('pointermove', (p: Phaser.Input.Pointer) => {
      if (p.rightButtonDown()) {
        cam.scrollX -= p.velocity.x / cam.zoom;
        cam.scrollY -= p.velocity.y / cam.zoom;
      } else {
        const worldPoint = this.cameras.main.getWorldPoint(p.x, p.y);
        const tx = Math.floor(worldPoint.x / this.tileSize);
        const ty = Math.floor(worldPoint.y / this.tileSize);

        const tile = this.map.getTile(tx, ty);
        this.hoveredTile = tile ? { x: tx, y: ty } : null;
      }
    });

    // Mausrad-Zoom mit Fokus auf Mauszeiger
    this.input.on(
    'wheel',
    (
        pointer: Phaser.Input.Pointer,
        over: any[],
        dx: number,
        dy: number,
        dz: number
    ) => {
        const cam = this.cameras.main;
        const oldZoom = cam.zoom;
        const newZoom = Phaser.Math.Clamp(oldZoom - dy * 0.001, 0.3, 3);

        const worldPoint = cam.getWorldPoint(pointer.x, pointer.y);
        cam.setZoom(newZoom);
        const newWorldPoint = cam.getWorldPoint(pointer.x, pointer.y);

        cam.scrollX += worldPoint.x - newWorldPoint.x;
        cam.scrollY += worldPoint.y - newWorldPoint.y;
        this.zoom = newZoom;
    }
    );

    this.input.on('pointerdown', (pointer: Phaser.Input.Pointer) => {
        if (pointer.rightButtonDown()) return; // rechts: Kamera
        if (!this.hoveredTile) return;
        const tile = this.map.getTile(this.hoveredTile.x, this.hoveredTile.y);
        this.clickOnTile(tile);
    });
  }

  clickOnTile(tile: Tile | null) {
    if (!tile) { return; }
    console.log(`Tile [${tile.x}, ${tile.y}] → ${tile.type}`);
    if (this.selectedBuilding != null) {
      const succ = this.buildingSystem.tryPlaceBuilding(tile.x, tile.y, this.selectedBuilding);
      if (succ) {
        this.buildingRenderer.addBuilding(succ)
      }
      this.selectedBuilding = 'storage';
    }

  }

  private renderMap() {
    const g = this.gfx;
    g.clear();

    const cam = this.cameras.main;
    const ts = this.tileSize;

    // Nur sichtbare Tiles zeichnen
    const left = Math.floor(cam.scrollX / ts) - 2;
    const top = Math.floor(cam.scrollY / ts) - 2;
    const right = Math.ceil((cam.scrollX + cam.width / cam.zoom) / ts) + 2;
    const bottom = Math.ceil((cam.scrollY + cam.height / cam.zoom) / ts) + 2;

    this.map.forEach((tile: Tile) => {
      if (tile.x < left || tile.x > right || tile.y < top || tile.y > bottom) return;

      g.fillStyle(this.tileColor(tile.type), 1);
      g.fillRect(tile.x * ts, tile.y * ts, ts - 1, ts - 1);
    });

    // Gebäude zeichnen
    for (const b of this.buildingSystem.getAll()) {
      // g.fillStyle(0xffcc66, 1);
      // g.fillRect(b.x * this.tileSize, b.y * this.tileSize, this.tileSize - 1, this.tileSize - 1);

      if (b instanceof ResouceBuilding && b.assignedWorker) {
          g.fillStyle(0xffffff, 1);
          g.fillCircle(
            b.assignedWorker.x * this.tileSize + this.tileSize / 2,
            b.assignedWorker.y * this.tileSize + this.tileSize / 2,
            this.tileSize / 4);
      }
    }

  }

  private tileColor(type: string): number {
    switch (type) {
      case 'grass': return 0x3a6b35;
      case 'forest': return 0x285028;
      case 'stone': return 0x8a8a8a;
      case 'water': return 0x244b6b;
      default: return 0xff00ff;
    }
  }

  override update() {
    this.renderMap();

    // Highlight zeichnen
    if (this.hoveredTile) {
    const { x, y } = this.hoveredTile;
    if (this.highlightGfx) {
        this.highlightGfx.clear();
    }
    this.highlightGfx.lineStyle(2, 0xffffff, 0.8);
    this.highlightGfx.strokeRect(
        x * this.tileSize,
        y * this.tileSize,
        this.tileSize - 1,
        this.tileSize - 1
    );
    } else {
        if (this.highlightGfx) {

            this.highlightGfx.clear();
        }
    }

    const dt = this.game.loop.delta / 1000;

    // Produktion tickt
  this.productionSystem.update(dt);

  this.buildingSystem.update(dt);
  this.buildingRenderer.update();

  }

  


//   private tileColor(kind: TileKind): number {
//     switch (kind) {
//       case 'grass': return 0x3a6b35;
//       case 'forest': return 0x285028;
//       case 'stone': return 0x8a8a8a;
//       case 'water': return 0x244b6b;
//     }
//   }
}