import { LitElement, html, css } from "lit";
import { gameStateManager } from "../core/GameStateManager.js";
import { GameLoop } from "../core/GameLoop.js";

import "./deployment-hud.js";
import "./dialogue-overlay.js";
import "./combat-hud.js";

export class GameViewport extends LitElement {
  static styles = css`
    :host {
      display: block;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    #canvas-container {
      width: 100%;
      height: 100%;
    }
  `;

  static get properties() {
    return {
      squad: { type: Array },
      deployedIds: { type: Array },
      combatState: { type: Object },
      missionDef: { type: Object },
    };
  }

  constructor() {
    super();
    this.squad = [];
    this.deployedIds = [];
    this.combatState = null;
    this.missionDef = null;
  }

  #handleUnitSelected(event) {
    const unit = event.detail.unit;
    const index = this.squad.indexOf(unit);
    gameStateManager.gameLoop.selectDeploymentUnit(index);
  }

  #handleStartBattle() {
    if (gameStateManager.gameLoop) {
      gameStateManager.gameLoop.finalizeDeployment().catch(console.error);
    }
  }

  #handleEndTurn() {
    if (gameStateManager.gameLoop) {
      gameStateManager.gameLoop.endTurn();
    }
  }

  #handleSkillClick(event) {
    const { skillId } = event.detail;
    if (gameStateManager.gameLoop) {
      gameStateManager.gameLoop.onSkillClicked(skillId);
    }
  }

  #handleMovementClick() {
    if (gameStateManager.gameLoop) {
      gameStateManager.gameLoop.onMovementClicked();
    }
  }

  async firstUpdated() {
    const container = this.shadowRoot.getElementById("canvas-container");
    const loop = new GameLoop();
    loop.init(container);
    gameStateManager.setGameLoop(loop);

    // Don't set squad from rosterLoaded - that's the full roster, not the current mission squad
    // Squad will be set from activeRunData when transitioning to deployment state

    // Get mission definition for deployment hints (lazy-loaded)
    this.missionDef = null;
    if (gameStateManager.missionManager) {
      gameStateManager.missionManager
        .getActiveMission()
        .then((mission) => {
          this.missionDef = mission || null;
          this.requestUpdate();
        })
        .catch(console.error);
    }

    // Set up combat state updates
    this.#setupCombatStateUpdates();
  }

  #setupCombatStateUpdates() {
    // Listen for combat state changes
    window.addEventListener("combat-state-changed", (e) => {
      this.combatState = e.detail.combatState;
    });

    // Listen for game state changes to update combat state
    window.addEventListener("gamestate-changed", () => {
      this.#updateCombatState();
    });

    // Listen for run data updates to get the current mission squad
    window.addEventListener("run-data-updated", (e) => {
      if (e.detail.runData?.squad) {
        this.squad = e.detail.runData.squad;
      }
    });

    // Initial updates
    this.#updateCombatState();
    this.#updateSquad();
  }

  #updateSquad() {
    // Update squad from activeRunData if available (current mission squad, not full roster)
    if (gameStateManager.activeRunData?.squad) {
      this.squad = gameStateManager.activeRunData.squad;
    }
  }

  #updateCombatState() {
    // Get combat state from GameStateManager
    this.combatState = gameStateManager.getCombatState();
  }

  render() {
    return html`<div id="canvas-container"></div>
      <deployment-hud
        .squad=${this.squad}
        .deployedIds=${this.deployedIds}
        .missionDef=${this.missionDef}
        @unit-selected=${this.#handleUnitSelected}
        @start-battle=${this.#handleStartBattle}
      ></deployment-hud>
      <combat-hud
        .combatState=${this.combatState}
        @end-turn=${this.#handleEndTurn}
        @skill-click=${this.#handleSkillClick}
        @movement-click=${this.#handleMovementClick}
      ></combat-hud>
      <dialogue-overlay></dialogue-overlay>`;
  }
}

customElements.define("game-viewport", GameViewport);
