import { LitElement, html, css } from "lit";
import { gameStateManager } from "../../core/GameStateManager.js";
import { Explorer } from "../../units/Explorer.js";
import {
  theme,
  buttonStyles,
  cardStyles,
  progressBarStyles,
} from "../styles/theme.js";

/**
 * BarracksScreen.js
 * The Squad Quarters - Barracks UI component for managing the roster.
 * @class
 */
export class BarracksScreen extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      cardStyles,
      progressBarStyles,
      css`
        :host {
          display: block;
          background: var(--color-bg-secondary);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-xl);
          max-width: 1400px;
          max-height: 85vh;
          overflow: hidden;
          color: var(--color-text-primary);
          font-family: var(--font-family);
          display: grid;
          grid-template-columns: 60% 40%;
          grid-template-rows: auto 1fr;
          grid-template-areas:
            "header header"
            "roster detail";
          gap: var(--spacing-lg);
        }

        .header {
          grid-area: header;
          display: flex;
          justify-content: space-between;
          align-items: center;
          border-bottom: var(--border-width-medium) solid
            var(--color-border-default);
          padding-bottom: var(--spacing-md);
        }

        .header h2 {
          margin: 0;
          color: var(--color-accent-cyan);
          font-size: var(--font-size-4xl);
        }

        .roster-info {
          display: flex;
          gap: var(--spacing-lg);
          align-items: center;
        }

        .roster-count {
          font-size: var(--font-size-lg);
          color: var(--color-text-secondary);
        }

        .filter-bar {
          display: flex;
          gap: var(--spacing-sm);
        }

        .filter-button {
          background: var(--color-bg-card);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-sm) var(--spacing-md);
          cursor: pointer;
          transition: all var(--transition-normal);
          font-family: inherit;
          color: var(--color-text-primary);
          font-size: var(--font-size-sm);
          font-weight: var(--font-weight-bold);
          text-transform: uppercase;
        }

        .filter-button:hover:not(.active) {
          border-color: var(--color-accent-cyan);
          background: rgba(0, 255, 255, 0.1);
        }

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

        .sort-bar {
          display: flex;
          gap: var(--spacing-sm);
          margin-top: var(--spacing-sm);
        }

        .sort-button {
          background: transparent;
          border: var(--border-width-thin) solid var(--color-border-default);
          padding: var(--spacing-xs) var(--spacing-sm);
          cursor: pointer;
          transition: all var(--transition-normal);
          font-family: inherit;
          color: var(--color-text-secondary);
          font-size: var(--font-size-xs);
        }

        .sort-button:hover {
          border-color: var(--color-accent-cyan);
          color: var(--color-text-primary);
        }

        /* Roster List */
        .roster-list {
          grid-area: roster;
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
          overflow-y: auto;
          padding-right: var(--spacing-sm);
        }

        .unit-card {
          background: var(--color-bg-card);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-md);
          cursor: pointer;
          transition: all var(--transition-normal);
          display: grid;
          grid-template-columns: 80px 1fr auto;
          gap: var(--spacing-md);
          align-items: center;
        }

        .unit-card:hover {
          border-color: var(--color-accent-cyan);
          background: rgba(0, 255, 255, 0.1);
        }

        .unit-card.selected {
          border-color: var(--color-accent-gold);
          background: rgba(255, 215, 0, 0.2);
          box-shadow: var(--shadow-glow-gold);
        }

        .unit-card.injured {
          border-left: var(--border-width-thick) solid var(--color-accent-red);
        }

        .unit-card.ready {
          border-left: var(--border-width-thick) solid var(--color-accent-green);
        }

        .unit-portrait {
          width: 80px;
          height: 80px;
          background: rgba(0, 0, 0, 0.8);
          border: var(--border-width-medium) solid var(--color-border-default);
          border-radius: var(--border-radius-md);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: var(--font-size-3xl);
          overflow: hidden;
        }

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

        .unit-info {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-xs);
        }

        .unit-name {
          font-size: var(--font-size-lg);
          font-weight: var(--font-weight-bold);
          color: var(--color-text-primary);
        }

        .unit-meta {
          display: flex;
          gap: var(--spacing-md);
          font-size: var(--font-size-sm);
          color: var(--color-text-secondary);
        }

        .unit-class {
          display: flex;
          align-items: center;
          gap: var(--spacing-xs);
        }

        .unit-level {
          color: var(--color-accent-gold);
        }

        .unit-hp-bar {
          width: 100%;
          margin-top: var(--spacing-xs);
        }

        .unit-status {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          gap: var(--spacing-xs);
        }

        .status-badge {
          padding: var(--spacing-xs) var(--spacing-sm);
          border-radius: var(--border-radius-sm);
          font-size: var(--font-size-xs);
          font-weight: var(--font-weight-bold);
          text-transform: uppercase;
        }

        .status-badge.ready {
          background: var(--color-accent-green);
          color: #000;
        }

        .status-badge.injured {
          background: var(--color-accent-red);
          color: white;
        }

        .status-badge.dead {
          background: var(--color-border-dark);
          color: var(--color-text-secondary);
        }

        /* Detail Sidebar */
        .detail-sidebar {
          grid-area: detail;
          background: var(--color-bg-panel);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-lg);
          display: flex;
          flex-direction: column;
          gap: var(--spacing-lg);
          overflow-y: auto;
        }

        .detail-header {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
          border-bottom: var(--border-width-medium) solid
            var(--color-border-default);
          padding-bottom: var(--spacing-md);
        }

        .detail-preview {
          width: 100%;
          height: 200px;
          background: rgba(0, 0, 0, 0.8);
          border: var(--border-width-medium) solid var(--color-border-default);
          border-radius: var(--border-radius-md);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: var(--font-size-5xl);
          overflow: hidden;
        }

        .detail-preview img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .detail-stats {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-sm);
        }

        .stat-row {
          display: flex;
          justify-content: space-between;
          font-size: var(--font-size-sm);
        }

        .stat-label {
          color: var(--color-text-secondary);
        }

        .stat-value {
          color: var(--color-text-primary);
          font-weight: var(--font-weight-bold);
        }

        .detail-actions {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
          margin-top: var(--spacing-md);
        }

        .action-button {
          width: 100%;
          padding: var(--spacing-md);
          font-size: var(--font-size-base);
        }

        .heal-cost {
          font-size: var(--font-size-sm);
          color: var(--color-accent-gold);
          margin-top: var(--spacing-xs);
        }

        .empty-state {
          grid-column: 1 / -1;
          text-align: center;
          padding: var(--spacing-2xl);
          color: var(--color-text-secondary);
        }
      `,
    ];
  }

  static get properties() {
    return {
      units: { type: Array },
      selectedUnitId: { type: String },
      filter: { type: String },
      sort: { type: String },
      healingCostPerHp: { type: Number },
      wallet: { type: Object },
    };
  }

  constructor() {
    super();
    this.units = [];
    this.selectedUnitId = null;
    this.filter = "ALL";
    this.sort = "LEVEL_DESC";
    this.healingCostPerHp = 0.5; // 1 HP = 0.5 Shards
    this.wallet = { aetherShards: 0, ancientCores: 0 };
  }

  connectedCallback() {
    super.connectedCallback();
    this._loadRoster();
    this._loadWallet();
  }

  _loadRoster() {
    try {
      const roster = gameStateManager.rosterManager.roster || [];
      // Convert ExplorerData to RosterUnitData format
      this.units = roster.map((unitData) =>
        this._convertToRosterUnitData(unitData)
      );
      this.requestUpdate();
    } catch (error) {
      console.error("Error loading roster:", error);
      this.units = [];
      this.requestUpdate();
    }
  }

  async _loadWallet() {
    try {
      if (gameStateManager.hubStash?.currency) {
        this.wallet = {
          aetherShards: gameStateManager.hubStash.currency.aetherShards || 0,
          ancientCores: gameStateManager.hubStash.currency.ancientCores || 0,
        };
      } else {
        const runData = await gameStateManager.persistence.loadRun();
        if (runData?.inventory?.runStash?.currency) {
          this.wallet = {
            aetherShards: runData.inventory.runStash.currency.aetherShards || 0,
            ancientCores: runData.inventory.runStash.currency.ancientCores || 0,
          };
        }
      }
    } catch (error) {
      console.warn("Could not load wallet data:", error);
    }
    this.requestUpdate();
  }

  /**
   * Converts ExplorerData to RosterUnitData format
   * @param {import("../../units/types.js").ExplorerData} unitData
   * @returns {Object}
   */
  _convertToRosterUnitData(unitData) {
    // Calculate maxHp from class mastery
    let maxHp = 100; // Default
    let currentHp = 100;
    let level = 1;

    const activeClassId = unitData.activeClassId || unitData.classId;
    if (unitData.classMastery && unitData.classMastery[activeClassId]) {
      const mastery = unitData.classMastery[activeClassId];
      level = mastery.level || 1;

      // Try to get class definition to calculate accurate HP
      let classDef = null;
      if (gameStateManager.gameLoop?.classRegistry) {
        classDef = gameStateManager.gameLoop.classRegistry.get(activeClassId);
      }

      if (classDef && classDef.base_stats) {
        // Calculate maxHp: base + (level - 1) * growth
        maxHp = classDef.base_stats.health || 100;
        if (classDef.growth_rates && classDef.growth_rates.health) {
          maxHp += classDef.growth_rates.health * (level - 1);
        }
      } else {
        // Fallback: estimate from level
        maxHp = 100 + (level - 1) * 8;
      }
    }

    // Check if unit has stored currentHealth (from mission return) - check this FIRST
    if (
      unitData.currentHealth !== undefined &&
      unitData.currentHealth !== null
    ) {
      currentHp = unitData.currentHealth;
    } else {
      // Infer currentHp from status only if not stored
      if (unitData.status === "READY") {
        currentHp = maxHp;
      } else if (unitData.status === "INJURED") {
        // Assume injured units are at 50% HP
        currentHp = Math.floor(maxHp * 0.5);
      } else if (unitData.status === "DEAD") {
        currentHp = 0;
      } else {
        // Default to maxHp for other statuses
        currentHp = maxHp;
      }
    }

    // Try to get portrait path
    let portrait = unitData.portrait || unitData.image;
    if (!portrait) {
      // Default portrait path based on class
      portrait = `assets/images/portraits/${activeClassId.toLowerCase()}.png`;
    }

    return {
      id: unitData.id,
      name: unitData.name,
      classId: activeClassId,
      level: level,
      currentHp: currentHp,
      maxHp: maxHp,
      status: unitData.status || "READY",
      portrait: portrait,
      equipment: unitData.equipment || null, // Store equipment reference
      loadout: unitData.loadout || null, // Store loadout reference
      rawData: unitData, // Keep reference to original data
    };
  }

  _getFilteredUnits() {
    let filtered = [...this.units];

    // Apply filter
    if (this.filter === "READY") {
      filtered = filtered.filter((u) => u.status === "READY");
    } else if (this.filter === "INJURED") {
      filtered = filtered.filter((u) => u.currentHp < u.maxHp);
    }

    // Apply sort
    if (this.sort === "LEVEL_DESC") {
      filtered.sort((a, b) => b.level - a.level);
    } else if (this.sort === "NAME_ASC") {
      filtered.sort((a, b) => a.name.localeCompare(b.name));
    } else if (this.sort === "HP_ASC") {
      filtered.sort((a, b) => a.currentHp - b.currentHp);
    }

    return filtered;
  }

  _getSelectedUnit() {
    if (!this.selectedUnitId) return null;
    return this.units.find((u) => u.id === this.selectedUnitId);
  }

  _calculateHealCost(unit) {
    if (!unit || unit.currentHp >= unit.maxHp) return 0;
    const missingHp = unit.maxHp - unit.currentHp;
    return Math.ceil(missingHp * this.healingCostPerHp);
  }

  _onUnitClick(unitId) {
    this.selectedUnitId = unitId;
    this.requestUpdate();
  }

  _onFilterClick(filter) {
    this.filter = filter;
    this.requestUpdate();
  }

  _onSortClick(sort) {
    this.sort = sort;
    this.requestUpdate();
  }

  async _handleHeal() {
    const unit = this._getSelectedUnit();
    if (!unit || unit.currentHp >= unit.maxHp) return;

    const cost = this._calculateHealCost(unit);
    if (this.wallet.aetherShards < cost) {
      alert(
        `Insufficient funds. Need ${cost} Shards, have ${this.wallet.aetherShards}.`
      );
      return;
    }

    // Deduct currency
    if (gameStateManager.hubStash) {
      if (!gameStateManager.hubStash.currency) {
        gameStateManager.hubStash.currency = {
          aetherShards: 0,
          ancientCores: 0,
        };
      }
      gameStateManager.hubStash.currency.aetherShards -= cost;
      this.wallet.aetherShards =
        gameStateManager.hubStash.currency.aetherShards;
    }

    // Update unit HP
    const rosterUnit = gameStateManager.rosterManager.roster.find(
      (u) => u.id === unit.id
    );
    if (rosterUnit) {
      rosterUnit.currentHealth = unit.maxHp;
      rosterUnit.status = "READY";
    }

    // Update local unit data
    unit.currentHp = unit.maxHp;
    unit.status = "READY";

    // Save roster and wallet
    await gameStateManager.persistence.saveRoster(
      gameStateManager.rosterManager.save()
    );
    await gameStateManager.persistence.saveHubStash(gameStateManager.hubStash);

    // Dispatch event to update Hub header (use nextTick to ensure state is updated)
    Promise.resolve().then(() => {
      window.dispatchEvent(
        new CustomEvent("wallet-updated", {
          detail: { wallet: { ...this.wallet } },
          bubbles: true,
          composed: true,
        })
      );
    });

    this.requestUpdate();
  }

  async _handleInspect() {
    const unit = this._getSelectedUnit();
    if (!unit) return;

    // Create a proper Explorer instance from roster data
    const rosterData = unit.rawData;
    const activeClassId = rosterData.activeClassId || rosterData.classId;

    // Get class definition
    let classDef = null;
    if (gameStateManager.gameLoop?.classRegistry) {
      classDef = gameStateManager.gameLoop.classRegistry.get(activeClassId);
    }

    // If not found in registry, load directly from JSON files
    if (!classDef) {
      // Map class IDs to their JSON filenames
      const classFileMap = {
        CLASS_VANGUARD: "vanguard",
        CLASS_WEAVER: "aether_weaver",
        CLASS_AETHER_WEAVER: "aether_weaver",
        CLASS_SCAVENGER: "scavenger",
        CLASS_TINKER: "tinker",
        CLASS_CUSTODIAN: "custodian",
        CLASS_SAPPER: "sapper",
        CLASS_FIELD_ENGINEER: "field_engineer",
        CLASS_BATTLE_MAGE: "battle_mage",
        CLASS_ARCANE_SCOURGE: "arcane_scourge",
        CLASS_AETHER_SENTINEL: "aether_sentinel",
      };

      const className =
        classFileMap[activeClassId] ||
        activeClassId.toLowerCase().replace("class_", "");

      try {
        // Use fetch to load the class definition JSON file
        const response = await fetch(`assets/data/classes/${className}.json`);
        if (response.ok) {
          classDef = await response.json();
        } else {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
      } catch (error) {
        console.error(
          `Could not load class definition for ${activeClassId} (tried ${className}.json}):`,
          error
        );
      }
    }

    if (!classDef) {
      console.error(`Class definition not found for ${activeClassId}`);
      return;
    }

    // Create Explorer instance
    const explorer = new Explorer(
      rosterData.id,
      rosterData.name,
      activeClassId,
      classDef
    );

    // Restore classMastery and activeClassId
    if (rosterData.classMastery) {
      explorer.classMastery = JSON.parse(
        JSON.stringify(rosterData.classMastery)
      );
    }
    if (rosterData.activeClassId) {
      explorer.activeClassId = rosterData.activeClassId;
    }

    // Recalculate stats based on restored mastery
    if (explorer.classMastery[activeClassId]) {
      explorer.recalculateBaseStats(classDef);
    }

    // Restore current health
    if (
      rosterData.currentHealth !== undefined &&
      rosterData.currentHealth !== null
    ) {
      explorer.currentHealth = rosterData.currentHealth;
    } else {
      // Set to max if ready, or appropriate value based on status
      if (rosterData.status === "READY") {
        explorer.currentHealth = explorer.maxHealth;
      } else if (rosterData.status === "INJURED") {
        explorer.currentHealth = Math.floor(explorer.maxHealth * 0.5);
      }
    }

    // Restore equipment/loadout if stored
    if (rosterData.equipment) {
      explorer.equipment = { ...explorer.equipment, ...rosterData.equipment };
    }
    if (rosterData.loadout) {
      explorer.loadout = { ...explorer.loadout, ...rosterData.loadout };
    }

    // Set portrait from roster data or unit data
    if (unit.portrait) {
      explorer.portrait = unit.portrait;
    } else if (rosterData.portrait || rosterData.image) {
      explorer.portrait = rosterData.portrait || rosterData.image;
    } else {
      // Default portrait path
      explorer.portrait = `assets/images/portraits/${activeClassId.toLowerCase()}.png`;
    }

    // Generate skill tree if gameLoop isn't running
    let skillTree = null;
    if (
      !gameStateManager.gameLoop?.classRegistry &&
      classDef &&
      classDef.skillTreeData
    ) {
      try {
        const { SkillTreeFactory } = await import(
          "../../factories/SkillTreeFactory.js"
        );

        // Load skill tree template
        const templateResponse = await fetch(
          "assets/data/skill_trees/template_standard_30.json"
        );
        if (templateResponse.ok) {
          const template = await templateResponse.json();
          const templateRegistry = { [template.id]: template };

          // Get skill registry
          const { skillRegistry } = await import(
            "../../managers/SkillRegistry.js"
          );
          await skillRegistry.loadAll(); // Ensure skills are loaded

          // Convert Map to object for SkillTreeFactory
          const skillMap = Object.fromEntries(skillRegistry.skills);

          // Create factory and generate tree
          const factory = new SkillTreeFactory(templateRegistry, skillMap);
          skillTree = factory.createTree(classDef);
        }
      } catch (error) {
        console.warn("Failed to generate skill tree from barracks:", error);
      }
    }

    // Dispatch event to open character sheet with proper Explorer instance
    window.dispatchEvent(
      new CustomEvent("open-character-sheet", {
        detail: {
          unitId: unit.id,
          unit: explorer, // Pass the proper Explorer instance
          skillTree: skillTree, // Pass generated skill tree if available
        },
        bubbles: true,
        composed: true,
      })
    );
  }

  async _handleDismiss() {
    const unit = this._getSelectedUnit();
    if (!unit) return;

    const confirmed = confirm(
      `Are you sure you want to permanently dismiss ${unit.name}? This cannot be undone.`
    );
    if (!confirmed) return;

    // Remove from roster
    const index = gameStateManager.rosterManager.roster.findIndex(
      (u) => u.id === unit.id
    );
    if (index > -1) {
      gameStateManager.rosterManager.roster.splice(index, 1);
    }

    // Remove from local units
    this.units = this.units.filter((u) => u.id !== unit.id);

    // Clear selection if dismissed unit was selected
    if (this.selectedUnitId === unit.id) {
      this.selectedUnitId = null;
    }

    // Save roster
    await gameStateManager.persistence.saveRoster(
      gameStateManager.rosterManager.save()
    );

    this.requestUpdate();
  }

  _handleClose() {
    this.dispatchEvent(
      new CustomEvent("close-barracks", {
        bubbles: true,
        composed: true,
      })
    );
  }

  _renderUnitCard(unit) {
    const isSelected = unit.id === this.selectedUnitId;
    const statusClass = unit.status.toLowerCase();
    const hpPercent = (unit.currentHp / unit.maxHp) * 100;

    return html`
      <div
        class="unit-card ${statusClass} ${isSelected ? "selected" : ""}"
        @click=${() => this._onUnitClick(unit.id)}
      >
        <div class="unit-portrait">
          ${unit.portrait
            ? html`<img
                src="${unit.portrait}"
                alt="${unit.name}"
                style="width: 100%; height: 100%; object-fit: cover;"
                @error=${(e) => {
                  e.target.style.display = "none";
                  const fallback = unit.classId
                    ? unit.classId.replace("CLASS_", "")[0]
                    : "?";
                  e.target.parentElement.textContent = fallback;
                }}
              />`
            : unit.classId
            ? unit.classId.replace("CLASS_", "")[0]
            : "?"}
        </div>
        <div class="unit-info">
          <div class="unit-name">${unit.name}</div>
          <div class="unit-meta">
            <span class="unit-class"
              >${unit.classId?.replace("CLASS_", "") || "Unknown"}</span
            >
            <span class="unit-level">Lv. ${unit.level}</span>
          </div>
          <div class="unit-hp-bar">
            <div class="progress-bar-container">
              <div
                class="progress-bar-fill hp"
                style="width: ${hpPercent}%"
              ></div>
              <div class="progress-bar-label">
                ${unit.currentHp}/${unit.maxHp} HP
              </div>
            </div>
          </div>
        </div>
        <div class="unit-status">
          <span class="status-badge ${statusClass}">${unit.status}</span>
        </div>
      </div>
    `;
  }

  _renderDetailSidebar() {
    const unit = this._getSelectedUnit();
    if (!unit) {
      return html`
        <div class="detail-sidebar">
          <div class="empty-state">
            <p>Select a unit to view details</p>
          </div>
        </div>
      `;
    }

    const healCost = this._calculateHealCost(unit);
    const canHeal =
      unit.currentHp < unit.maxHp && this.wallet.aetherShards >= healCost;
    const isInjured = unit.currentHp < unit.maxHp;
    const hpPercent = (unit.currentHp / unit.maxHp) * 100;

    return html`
      <div class="detail-sidebar">
        <div class="detail-header">
          <div class="detail-preview">
            ${unit.portrait
              ? html`<img
                  src="${unit.portrait}"
                  alt="${unit.name}"
                  style="width: 100%; height: 100%; object-fit: cover;"
                  @error=${(e) => {
                    e.target.style.display = "none";
                    const fallback = unit.classId
                      ? unit.classId.replace("CLASS_", "")[0]
                      : "?";
                    e.target.parentElement.textContent = fallback;
                  }}
                />`
              : unit.classId
              ? unit.classId.replace("CLASS_", "")[0]
              : "?"}
          </div>
          <div>
            <h3 style="margin: 0; color: var(--color-accent-cyan);">
              ${unit.name}
            </h3>
            <p
              style="margin: var(--spacing-xs) 0; color: var(--color-text-secondary);"
            >
              ${unit.classId?.replace("CLASS_", "") || "Unknown"} • Level
              ${unit.level}
            </p>
          </div>
        </div>

        <div class="detail-stats">
          <div class="stat-row">
            <span class="stat-label">Health</span>
            <span class="stat-value">${unit.currentHp} / ${unit.maxHp}</span>
          </div>
          <div class="progress-bar-container">
            <div
              class="progress-bar-fill hp"
              style="width: ${hpPercent}%"
            ></div>
            <div class="progress-bar-label">${Math.round(hpPercent)}%</div>
          </div>
          <div class="stat-row">
            <span class="stat-label">Status</span>
            <span class="stat-value">${unit.status}</span>
          </div>
        </div>

        <div class="detail-actions">
          <button class="btn action-button" @click=${this._handleInspect}>
            Inspect / Equip
          </button>
          ${isInjured
            ? html`
                <button
                  class="btn btn-primary action-button"
                  ?disabled=${!canHeal}
                  @click=${this._handleHeal}
                >
                  Treat Wounds (${healCost} 💎)
                </button>
                ${!canHeal && healCost > 0
                  ? html`
                      <div class="heal-cost">
                        Insufficient funds. Need ${healCost} Shards.
                      </div>
                    `
                  : ""}
              `
            : html`
                <button class="btn action-button" disabled>Full Health</button>
              `}
          <button
            class="btn btn-danger action-button"
            @click=${this._handleDismiss}
          >
            Dismiss
          </button>
        </div>
      </div>
    `;
  }

  render() {
    const filteredUnits = this._getFilteredUnits();
    const rosterCount = this.units.length;
    const rosterLimit = gameStateManager.rosterManager.rosterLimit || 12;

    return html`
      <div class="header">
        <div>
          <h2>The Squad Quarters</h2>
          <div class="roster-info">
            <span class="roster-count"
              >Roster: ${rosterCount}/${rosterLimit}</span
            >
            <div class="filter-bar">
              <button
                class="filter-button ${this.filter === "ALL" ? "active" : ""}"
                @click=${() => this._onFilterClick("ALL")}
              >
                All
              </button>
              <button
                class="filter-button ${this.filter === "READY" ? "active" : ""}"
                @click=${() => this._onFilterClick("READY")}
              >
                Ready
              </button>
              <button
                class="filter-button ${this.filter === "INJURED"
                  ? "active"
                  : ""}"
                @click=${() => this._onFilterClick("INJURED")}
              >
                Injured
              </button>
            </div>
            <div class="sort-bar">
              <span
                style="color: var(--color-text-secondary); font-size: var(--font-size-xs);"
              >
                Sort:
              </span>
              <button
                class="sort-button"
                @click=${() => this._onSortClick("LEVEL_DESC")}
              >
                Level
              </button>
              <button
                class="sort-button"
                @click=${() => this._onSortClick("NAME_ASC")}
              >
                Name
              </button>
              <button
                class="sort-button"
                @click=${() => this._onSortClick("HP_ASC")}
              >
                HP
              </button>
            </div>
          </div>
        </div>
        <button class="btn btn-close" @click=${this._handleClose}>✕</button>
      </div>

      <div class="roster-list">
        ${filteredUnits.length === 0
          ? html`
              <div class="empty-state">
                <p>No units found matching the current filter.</p>
              </div>
            `
          : filteredUnits.map((unit) => this._renderUnitCard(unit))}
      </div>

      ${this._renderDetailSidebar()}
    `;
  }
}

customElements.define("barracks-screen", BarracksScreen);
