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

export class CombatHUD extends LitElement {
  static get styles() {
    return [
      theme,
      progressBarStyles,
      portraitStyles,
      buttonStyles,
      badgeStyles,
      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);
          z-index: var(--z-tooltip);
        }

        /* Top Bar */
        .top-bar {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          height: 120px;
          background: linear-gradient(
            to bottom,
            rgba(0, 0, 0, 0.9) 0%,
            rgba(0, 0, 0, 0.7) 80%,
            transparent 100%
          );
          pointer-events: auto;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: var(--spacing-lg) var(--spacing-xl);
        }

        .turn-queue {
          display: flex;
          align-items: center;
          gap: var(--spacing-md);
          flex: 1;
        }

        .queue-portrait {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          border: var(--border-width-medium) solid var(--color-border-light);
          overflow: hidden;
          background: var(--color-bg-primary);
          position: relative;
          pointer-events: auto;
        }

        .queue-portrait.active {
          width: 80px;
          height: 80px;
          border: var(--border-width-thick) solid var(--color-accent-gold);
          box-shadow: var(--shadow-glow-gold);
        }

        .queue-portrait img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .queue-portrait.enemy {
          border-color: var(--color-accent-red);
        }

        .queue-portrait.player {
          border-color: var(--color-accent-green);
        }

        .enemy-intent {
          position: absolute;
          bottom: -5px;
          right: -5px;
          width: 20px;
          height: 20px;
          background: rgba(0, 0, 0, 0.9);
          border: var(--border-width-thin) solid var(--color-accent-red);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: var(--font-size-xs);
        }

        .global-info {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          gap: var(--spacing-sm);
          background: var(--color-bg-primary);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-sm) var(--spacing-lg);
          pointer-events: auto;
        }

        .round-counter {
          font-size: var(--font-size-lg);
          font-weight: var(--font-weight-bold);
        }

        .threat-level {
          font-size: var(--font-size-sm);
          padding: 2px var(--spacing-sm);
          border-radius: var(--border-radius-sm);
        }

        .threat-level.low {
          background: rgba(0, 255, 0, 0.3);
          color: var(--color-accent-green);
        }

        .threat-level.medium {
          background: rgba(255, 255, 0, 0.3);
          color: #ffff66;
        }

        .threat-level.high {
          background: rgba(255, 0, 0, 0.3);
          color: var(--color-accent-red);
        }

        /* Bottom Bar */
        .bottom-bar {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 180px;
          background: linear-gradient(
            to top,
            rgba(0, 0, 0, 0.9) 0%,
            rgba(0, 0, 0, 0.7) 80%,
            transparent 100%
          );
          pointer-events: auto;
          display: flex;
          align-items: flex-end;
          justify-content: space-between;
          padding: var(--spacing-lg) var(--spacing-xl);
        }

        /* Unit Status (Bottom-Left) */
        .unit-status {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-sm);
          background: var(--color-bg-primary);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-md);
          min-width: 200px;
          pointer-events: auto;
        }

        .unit-portrait {
          width: 120px;
          height: 120px;
          border: var(--border-width-medium) solid var(--color-border-light);
          overflow: hidden;
          background: rgba(0, 0, 0, 0.9);
          margin: 0 auto;
        }

        .unit-portrait img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .unit-name {
          text-align: center;
          font-size: var(--font-size-base);
          font-weight: var(--font-weight-bold);
          margin-top: var(--spacing-xs);
        }

        .status-icons {
          display: flex;
          gap: var(--spacing-xs);
          justify-content: center;
          flex-wrap: wrap;
          margin-top: var(--spacing-xs);
        }

        .status-icon {
          width: 24px;
          height: 24px;
          border: var(--border-width-thin) solid var(--color-border-default);
          border-radius: var(--border-radius-sm);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: var(--font-size-sm);
          background: rgba(0, 0, 0, 0.7);
          cursor: help;
          position: relative;
        }

        .status-icon:hover::after {
          content: attr(data-description);
          position: absolute;
          bottom: 100%;
          left: 50%;
          transform: translateX(-50%);
          background: rgba(0, 0, 0, 0.95);
          border: var(--border-width-thin) solid var(--color-border-default);
          padding: var(--spacing-xs) var(--spacing-sm);
          white-space: nowrap;
          font-size: var(--font-size-sm);
          margin-bottom: var(--spacing-xs);
          pointer-events: none;
        }

        /* Action Bar (Bottom-Center) */
        .action-bar {
          display: flex;
          gap: var(--spacing-sm);
          align-items: center;
          pointer-events: auto;
        }

        .skill-button {
          width: 70px;
          height: 70px;
          background: var(--color-bg-primary);
          border: var(--border-width-medium) solid var(--color-border-light);
          cursor: pointer;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: var(--spacing-xs);
          position: relative;
          transition: all var(--transition-normal);
          pointer-events: auto;
          color: var(--color-text-primary);
        }

        .skill-button:hover:not(:disabled) {
          border-color: var(--color-accent-gold);
          box-shadow: var(--shadow-glow-gold);
          transform: translateY(-2px);
        }

        .skill-button:disabled {
          opacity: 0.5;
          cursor: not-allowed;
          border-color: var(--color-border-dark);
        }

        .skill-button.active {
          background: rgba(255, 215, 0, 0.2);
          border-color: var(--color-accent-gold);
          box-shadow: var(--shadow-glow-gold);
        }

        .movement-button {
          width: 70px;
          height: 70px;
          background: var(--color-bg-primary);
          border: var(--border-width-medium) solid var(--color-border-light);
          cursor: pointer;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          gap: var(--spacing-xs);
          position: relative;
          transition: all var(--transition-normal);
          pointer-events: auto;
          color: var(--color-text-primary);
        }

        .movement-button:hover {
          border-color: var(--color-accent-green);
          box-shadow: var(--shadow-glow-green);
          transform: translateY(-2px);
        }

        .movement-button.active {
          background: rgba(102, 255, 102, 0.2);
          border-color: var(--color-accent-green);
          box-shadow: var(--shadow-glow-green);
        }

        .movement-button .icon {
          font-size: var(--font-size-2xl);
          margin-top: var(--spacing-sm);
        }

        .movement-button .name {
          font-size: var(--font-size-xs);
          text-align: center;
          padding: 0 4px;
        }

        .skill-button .hotkey {
          position: absolute;
          top: 2px;
          left: 2px;
          font-size: var(--font-size-xs);
          background: var(--color-bg-primary);
          padding: 2px 4px;
          border: var(--border-width-thin) solid var(--color-border-default);
          color: var(--color-text-primary);
        }

        .skill-button .icon {
          font-size: var(--font-size-2xl);
          margin-top: var(--spacing-sm);
        }

        .skill-button .name {
          font-size: var(--font-size-xs);
          text-align: center;
          padding: 0 4px;
        }

        .skill-button .cost {
          position: absolute;
          bottom: 2px;
          right: 2px;
          font-size: var(--font-size-xs);
          color: var(--color-accent-orange);
        }

        .skill-button .cooldown {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: var(--font-size-xl);
          font-weight: var(--font-weight-bold);
        }

        /* End Turn Button (Bottom-Right) */
        .end-turn-button {
          background: var(--color-bg-primary);
          border: var(--border-width-medium) solid var(--color-accent-red);
          padding: var(--spacing-md) var(--spacing-xl);
          font-size: var(--font-size-lg);
          font-weight: var(--font-weight-bold);
          color: var(--color-text-primary);
          cursor: pointer;
          transition: all var(--transition-normal);
          pointer-events: auto;
          font-family: var(--font-family);
        }

        .end-turn-button:hover {
          background: rgba(255, 102, 102, 0.2);
          box-shadow: var(--shadow-glow-red);
          transform: translateY(-2px);
        }

        .end-turn-button:active {
          transform: translateY(0);
        }

        /* Responsive Design - Mobile (< 768px) */
        @media (max-width: 767px) {
          .bottom-bar {
            flex-direction: column;
            align-items: stretch;
            gap: var(--spacing-md);
            height: auto;
            min-height: 180px;
          }

          .unit-status {
            width: 100%;
            min-width: auto;
          }

          .action-bar {
            justify-content: center;
            flex-wrap: wrap;
          }

          .end-turn-button {
            width: 100%;
            margin-top: var(--spacing-sm);
          }

          .top-bar {
            flex-direction: column;
            height: auto;
            min-height: 120px;
            gap: var(--spacing-sm);
          }

          .turn-queue {
            justify-content: center;
            flex-wrap: wrap;
          }

          .global-info {
            align-items: center;
            width: 100%;
          }
        }
      `,
    ];
  }

  static get properties() {
    return {
      combatState: { type: Object },
    };
  }

  constructor() {
    super();
    this.combatState = null;
  }

  _handleSkillClick(skillId) {
    this.dispatchEvent(
      new CustomEvent("skill-click", {
        detail: { skillId },
        bubbles: true,
        composed: true,
      })
    );
  }

  _handleEndTurn(event) {
    this.dispatchEvent(
      new CustomEvent("end-turn", {
        bubbles: true,
        composed: true,
      })
    );
    // Blur the button to prevent it from retaining focus
    // This prevents spacebar from triggering it when moving units
    if (event && event.target) {
      event.target.blur();
    }
  }

  _handleMovementClick() {
    this.dispatchEvent(
      new CustomEvent("movement-click", {
        bubbles: true,
        composed: true,
      })
    );
  }

  _handleSkillHover(skillId) {
    this.dispatchEvent(
      new CustomEvent("hover-skill", {
        detail: { skillId },
        bubbles: true,
        composed: true,
      })
    );
  }

  _handlePortraitClick(unit) {
    // Dispatch open-character-sheet event with unit ID
    // GameLoop will resolve to full unit object
    if (unit && unit.unitId) {
      window.dispatchEvent(
        new CustomEvent("open-character-sheet", {
          detail: {
            unitId: unit.unitId,
            readOnly: false,
          },
        })
      );
    } else if (unit) {
      // If unit object is provided directly, use it
      window.dispatchEvent(
        new CustomEvent("open-character-sheet", {
          detail: {
            unit: unit,
            readOnly: false,
          },
        })
      );
    }
  }

  _getThreatLevel() {
    if (!this.combatState) return "low";
    const queue =
      this.combatState.enrichedQueue || this.combatState.turnQueue || [];
    // If turnQueue is string[], we can't filter by team, so use enrichedQueue
    const enemyCount =
      Array.isArray(queue) && queue.length > 0 && typeof queue[0] === "object"
        ? queue.filter((entry) => entry.team === "ENEMY").length
        : 0; // Fallback if we only have string IDs
    if (enemyCount >= 3) return "high";
    if (enemyCount >= 2) return "medium";
    return "low";
  }

  _renderBar(label, current, max, type) {
    const percentage = max > 0 ? (current / max) * 100 : 0;
    return html`
      <div class="bar-container">
        <div class="bar-label">
          <span>${label}</span>
          <span>${current}/${max}</span>
        </div>
        <div class="progress-bar-container">
          <div
            class="progress-bar-fill ${type}"
            style="width: ${percentage}%"
          ></div>
        </div>
      </div>
    `;
  }

  render() {
    if (!this.combatState) {
      return html``;
    }

    const { activeUnit, enrichedQueue, turnQueue, roundNumber, round } =
      this.combatState;
    // Use enrichedQueue if available (for UI), otherwise fall back to turnQueue
    const displayQueue = enrichedQueue || turnQueue || [];
    const threatLevel = this._getThreatLevel();

    return html`
      <!-- Top Bar -->
      <div class="top-bar">
        <!-- Turn Queue (Center-Left) -->
        <div class="turn-queue">
          ${displayQueue?.map(
            (entry, index) => html`
              <div
                class="queue-portrait ${entry.team.toLowerCase()} ${index === 0
                  ? "active"
                  : ""}"
              >
                <img src="${entry.portrait}" alt="${entry.unitId}" />
                ${index === 0 && entry.team === "ENEMY"
                  ? html`<div class="enemy-intent">⚔</div>`
                  : ""}
              </div>
            `
          ) || html``}
        </div>

        <!-- Global Info (Top-Right) -->
        <div class="global-info">
          <div class="round-counter">Round ${round || roundNumber || 1}</div>
          <div class="threat-level ${threatLevel}">
            ${threatLevel.toUpperCase()}
          </div>
        </div>
      </div>

      <!-- Bottom Bar -->
      <div class="bottom-bar">
        <!-- Unit Status (Bottom-Left) -->
        ${activeUnit
          ? html`
              <div class="unit-status">
                <div
                  class="unit-portrait"
                  @click="${() => this._handlePortraitClick(activeUnit)}"
                  style="cursor: pointer;"
                  title="Click to view character sheet (C)"
                >
                  <img src="${activeUnit.portrait}" alt="${activeUnit.name}" />
                </div>
                <div class="unit-name">${activeUnit.name}</div>

                ${activeUnit.statuses?.length > 0
                  ? html`
                      <div class="status-icons">
                        ${activeUnit.statuses.map(
                          (status) => html`
                            <div
                              class="status-icon"
                              data-description="${status.description} (${status.turnsRemaining} turns)"
                              title="${status.description}"
                            >
                              ${status.icon}
                            </div>
                          `
                        )}
                      </div>
                    `
                  : ""}
                ${this._renderBar(
                  "HP",
                  activeUnit.hp.current,
                  activeUnit.hp.max,
                  "hp"
                )}
                ${this._renderBar(
                  "AP",
                  activeUnit.ap.current,
                  activeUnit.ap.max,
                  "ap"
                )}
                ${this._renderBar("Charge", activeUnit.charge, 100, "charge")}
              </div>
            `
          : html``}

        <!-- Action Bar (Bottom-Center) -->
        <div class="action-bar">
          <!-- Movement Button -->
          <button
            class="movement-button ${!this.combatState?.targetingMode
              ? "active"
              : ""}"
            @click="${this._handleMovementClick}"
            title="Movement Mode (M)"
          >
            <span class="icon">🚶</span>
            <span class="name">Move</span>
          </button>
          ${activeUnit?.skills?.map(
            (skill, index) => html`
              <button
                class="skill-button ${this.combatState?.targetingMode &&
                this.combatState?.activeSkillId === skill.id
                  ? "active"
                  : ""}"
                ?disabled="${!skill.isAvailable}"
                @click="${() => this._handleSkillClick(skill.id)}"
                @mouseenter="${() => this._handleSkillHover(skill.id)}"
                title="${skill.name} - ${skill.costAP} AP${skill.cooldown > 0
                  ? ` (CD: ${skill.cooldown})`
                  : ""}"
              >
                <span class="hotkey">${index + 1}</span>
                <span class="icon">${skill.icon}</span>
                <span class="name">${skill.name}</span>
                <span class="cost">${skill.costAP}AP</span>
                ${skill.cooldown > 0
                  ? html`<div class="cooldown">${skill.cooldown}</div>`
                  : ""}
              </button>
            `
          ) || html``}
        </div>

        <!-- End Turn Button (Bottom-Right) -->
        <button class="end-turn-button" @click="${this._handleEndTurn}">
          END TURN
        </button>
      </div>
    `;
  }
}

customElements.define("combat-hud", CombatHUD);
