import { LitElement, html, css } from "lit";
import { theme, buttonStyles, cardStyles } from "./styles/theme.js";

export class DeploymentHUD extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      cardStyles,
      css`
        :host {
          display: block;
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          pointer-events: none;
          font-family: var(--font-family);
          color: var(--color-text-primary);
        }

        /* --- HEADER --- */
        .header {
          position: absolute;
          top: var(--spacing-lg);
          left: 50%;
          transform: translateX(-50%);
          background: var(--color-bg-primary);
          border: var(--border-width-medium) solid var(--color-accent-cyan);
          padding: var(--spacing-md) var(--spacing-xl);
          text-align: center;
          pointer-events: auto;
        }

        .status-bar {
          margin-top: var(--spacing-xs);
          font-size: var(--font-size-xl);
          color: var(--color-accent-green);
        }

        /* --- UNIT BENCH (Bottom) --- */
        .bench-container {
          position: absolute;
          bottom: var(--spacing-lg);
          left: 50%;
          transform: translateX(-50%);
          display: flex;
          gap: var(--spacing-md);
          background: rgba(0, 0, 0, 0.85);
          padding: var(--spacing-md);
          border-top: var(--border-width-thick) solid
            var(--color-border-default);
          pointer-events: auto;
          border-radius: var(--border-radius-lg) var(--border-radius-lg) 0 0;
          max-width: 90%;
          overflow-x: auto;
        }

        .unit-card {
          width: 100px;
          height: 130px;
          background: #222;
          border: var(--border-width-medium) solid var(--color-border-dashed);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all var(--transition-fast);
          position: relative;
        }

        .unit-card:hover {
          background: #333;
          transform: translateY(-5px);
        }

        .unit-card[selected] {
          border-color: var(--color-accent-cyan);
          box-shadow: var(--shadow-glow-cyan);
        }

        .unit-card[deployed] {
          border-color: var(--color-accent-green);
          opacity: 0.5;
        }

        .unit-card[suggested] {
          border-color: var(--color-accent-orange);
          box-shadow: 0 0 10px rgba(255, 170, 0, 0.5);
          background: #332200;
        }

        .unit-card[suggested]:hover {
          background: #443300;
        }

        /* Selected takes priority over suggested */
        .unit-card[selected][suggested] {
          border-color: var(--color-accent-cyan);
          box-shadow: var(--shadow-glow-cyan);
          background: #223322; /* Slightly green-tinted background to show it's both */
        }

        .unit-card[selected][suggested]:hover {
          background: #334433;
        }

        .tutorial-hint {
          position: absolute;
          top: 80px;
          left: 50%;
          transform: translateX(-50%);
          background: rgba(0, 0, 0, 0.9);
          border: var(--border-width-medium) solid var(--color-accent-orange);
          padding: var(--spacing-md) 25px;
          text-align: center;
          pointer-events: auto;
          font-size: var(--font-size-base);
          color: var(--color-accent-orange);
          max-width: 500px;
          border-radius: 5px;
          box-shadow: 0 0 20px rgba(255, 170, 0, 0.3);
        }

        .unit-portrait {
          width: 100%;
          height: 60%;
          object-fit: cover;
          background: #111;
          border-bottom: var(--border-width-thin) solid
            var(--color-border-dashed);
        }

        .unit-icon {
          font-size: var(--font-size-4xl);
          margin-bottom: var(--spacing-xs);
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 60%;
          background: #111;
          border-bottom: var(--border-width-thin) solid
            var(--color-border-dashed);
        }

        .unit-info {
          height: 40%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: var(--spacing-xs);
          width: 100%;
          box-sizing: border-box;
        }

        .unit-name {
          font-size: var(--font-size-sm);
          text-align: center;
          font-weight: var(--font-weight-bold);
          margin-bottom: 2px;
        }
        .unit-class {
          font-size: var(--font-size-xs);
          color: var(--color-text-secondary);
        }

        /* --- ACTION BUTTON --- */
        .action-panel {
          position: absolute;
          right: var(--spacing-xl);
          bottom: 200px; /* Above bench */
          pointer-events: auto;
        }

        .start-btn {
          background: #008800;
          color: white;
          border: var(--border-width-medium) solid var(--color-accent-green);
          padding: var(--spacing-md) var(--spacing-2xl);
          font-size: var(--font-size-2xl);
          font-family: var(--font-family);
          font-weight: var(--font-weight-bold);
          text-transform: uppercase;
          cursor: pointer;
          box-shadow: var(--shadow-glow-green);
        }

        .start-btn:disabled {
          background: #333;
          border-color: var(--color-border-default);
          color: var(--color-text-muted);
          cursor: not-allowed;
          box-shadow: none;
        }
      `,
    ];
  }

  static get properties() {
    return {
      squad: { type: Array }, // List of all available units
      deployedIds: { type: Array }, // List of IDs currently on the board
      selectedId: { type: String }, // ID of unit currently being placed
      maxUnits: { type: Number },
      currentState: { type: String }, // Current game state
      missionDef: { type: Object }, // Mission definition for tutorial hints and suggested units
    };
  }

  constructor() {
    super();
    this.squad = [];
    this.deployedIds = [];
    this.deployedIndices = []; // Store indices from GameLoop
    this.selectedId = null;
    this.maxUnits = 4;
    this.currentState = null;
    this.missionDef = null;
    window.addEventListener("deployment-update", (e) => {
      // Store the indices - we'll convert to IDs when squad is available
      this.deployedIndices = e.detail.deployedIndices || [];
      this._updateDeployedIds();
      this.requestUpdate(); // Trigger re-render
    });
    window.addEventListener("gamestate-changed", (e) => {
      this.currentState = e.detail.newState;
    });
  }

  updated(changedProperties) {
    // Update deployedIds when squad changes
    if (changedProperties.has("squad")) {
      this._updateDeployedIds();
    }
  }

  render() {
    // Hide the deployment HUD when not in deployment state
    // Show by default (when currentState is null) since we start in deployment
    if (
      this.currentState !== null &&
      this.currentState !== "STATE_DEPLOYMENT"
    ) {
      return html``;
    }

    // Ensure deployedIds is up to date
    this._updateDeployedIds();

    const deployedCount = this.deployedIds.length;
    const canStart = deployedCount > 0; // At least 1 unit required

    // Get tutorial hint and suggested units from mission definition
    const tutorialHint = this.missionDef?.deployment?.tutorial_hint;
    const suggestedUnits = this.missionDef?.deployment?.suggested_units || [];
    const defaultHint =
      "Select a unit below, then click a green tile to place.";

    return html`
      <div class="header">
        <h2>MISSION DEPLOYMENT</h2>
        <div class="status-bar">
          Squad Size: ${deployedCount} / ${this.maxUnits}
        </div>
        <div style="font-size: 0.8rem; margin-top: 5px; color: #ccc;">
          ${tutorialHint || defaultHint}
        </div>
      </div>

      ${tutorialHint
        ? html` <div class="tutorial-hint">${tutorialHint}</div> `
        : ""}

      <div class="action-panel">
        <button
          class="btn btn-primary start-btn"
          ?disabled="${!canStart}"
          @click="${this._handleStartBattle}"
        >
          START MISSION
        </button>
      </div>

      <div class="bench-container">
        ${this.squad.map((unit) => {
          const isDeployed = this.deployedIds.includes(unit.id);
          const isSelected = this.selectedId === unit.id;
          // Check if this unit is suggested (match by classId)
          const isSuggested = suggestedUnits.includes(unit.classId);

          // Get portrait/image (support both for backward compatibility)
          let portrait = unit.portrait || unit.image;
          // Normalize path: ensure it starts with / if it doesn't already
          if (
            portrait &&
            !portrait.startsWith("/") &&
            !portrait.startsWith("http")
          ) {
            portrait = "/" + portrait;
          }

          return html`
            <div
              class="unit-card"
              ?deployed=${isDeployed}
              ?selected=${isSelected}
              ?suggested=${isSuggested}
              @click="${() => this._selectUnit(unit)}"
            >
              ${portrait
                ? html`<img
                    src="${portrait}"
                    alt="${unit.name}"
                    class="unit-portrait"
                    @error="${(e) => {
                      e.target.style.display = "none";
                      const icon = e.target.nextElementSibling;
                      if (icon) icon.style.display = "flex";
                    }}"
                  />`
                : ""}
              <div class="unit-icon" style="${portrait ? "display:none;" : ""}">
                ${unit.icon || "🛡️"}
              </div>
              <div class="unit-info">
                <div class="unit-name">${unit.name || "Unknown"}</div>
                <div class="unit-class">
                  ${unit.className ||
                  this._formatClassName(unit.classId) ||
                  "Unknown"}
                </div>
                ${isSuggested && !isDeployed
                  ? html`<div
                      style="font-size:0.65rem; color:#ffaa00; margin-top:3px;"
                    >
                      RECOMMENDED
                    </div>`
                  : ""}
                ${isDeployed
                  ? html`<div style="font-size:0.7rem; color:#00ff00;">
                      DEPLOYED
                    </div>`
                  : ""}
              </div>
            </div>
          `;
        })}
      </div>
    `;
  }

  /**
   * Converts deployed indices to unit IDs and updates deployedIds
   * @private
   */
  _updateDeployedIds() {
    this.deployedIds = this.deployedIndices
      .map((index) => {
        const unit = this.squad[index];
        return unit?.id;
      })
      .filter((id) => id != null); // Filter out undefined/null IDs
  }

  /**
   * Formats a classId (e.g., "CLASS_VANGUARD") to a readable class name (e.g., "Vanguard")
   * @param {string} classId - The class identifier
   * @returns {string} - Formatted class name
   * @private
   */
  _formatClassName(classId) {
    if (!classId) return "Unknown";
    // Remove "CLASS_" prefix and format as title case
    const name = classId.replace(/^CLASS_/, "");
    return name
      .split("_")
      .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
      .join(" ");
  }

  _selectUnit(unit) {
    // Ensure deployedIds is up to date
    this._updateDeployedIds();

    if (this.deployedIds.includes(unit.id)) {
      // If already deployed, maybe select it to move it?
      // For now, let's just emit event to focus/recall it
      this.dispatchEvent(
        new CustomEvent("recall-unit", { detail: { unitId: unit.id } })
      );
      return;
    }

    if (this.deployedIds.length < this.maxUnits) {
      // Only update if selecting a different unit
      if (this.selectedId !== unit.id) {
        this.selectedId = unit.id;
      }
      // Tell GameLoop we want to place this unit next click
      this.dispatchEvent(
        new CustomEvent("unit-selected", { detail: { unit } })
      );
    }
  }

  _handleStartBattle() {
    this.dispatchEvent(
      new CustomEvent("start-battle", {
        bubbles: true,
        composed: true,
      })
    );
  }
}

customElements.define("deployment-hud", DeploymentHUD);
