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

/**
 * HubScreen.js
 * The Forward Operating Base - Main hub screen for managing resources, units, and mission selection.
 * @class
 */
export class HubScreen extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      overlayStyles,
      css`
        :host {
          display: block;
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          font-family: var(--font-family);
          color: var(--color-text-primary);
          overflow: hidden;
        }

        /* Background Image */
        .background {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-image: url("assets/images/ui/hub_bg_dusk.png");
          background-size: cover;
          background-position: center;
          background-repeat: no-repeat;
          z-index: var(--z-base);
        }

        /* Fallback background if image doesn't exist */
        .background::before {
          content: "";
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background: linear-gradient(
            135deg,
            rgba(20, 20, 40, 0.95) 0%,
            rgba(40, 30, 50, 0.95) 50%,
            rgba(20, 20, 40, 0.95) 100%
          );
          z-index: -1;
        }

        /* Top Bar */
        .top-bar {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 80px;
          background: rgba(0, 0, 0, 0.7);
          border-bottom: var(--border-width-medium) solid
            var(--color-border-default);
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 var(--spacing-xl);
          z-index: var(--z-overlay);
          box-sizing: border-box;
        }

        .logo {
          font-size: var(--font-size-3xl);
          font-weight: var(--font-weight-bold);
          color: var(--color-accent-cyan);
          text-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
        }

        .resource-strip {
          display: flex;
          gap: var(--spacing-lg);
          align-items: center;
          font-size: var(--font-size-base);
        }

        .resource-item {
          display: flex;
          align-items: center;
          gap: var(--spacing-sm);
          padding: var(--spacing-sm) var(--spacing-md);
          background: var(--color-bg-card);
          border: var(--border-width-thin) solid var(--color-border-default);
          border-radius: var(--border-radius-md);
        }

        .resource-item .icon {
          font-size: var(--font-size-2xl);
        }

        /* Bottom Dock */
        .bottom-dock {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 100px;
          background: var(--color-bg-backdrop);
          border-top: var(--border-width-medium) solid
            var(--color-border-default);
          display: flex;
          align-items: center;
          justify-content: center;
          gap: var(--spacing-md);
          padding: 0 var(--spacing-lg);
          z-index: var(--z-overlay);
          box-sizing: border-box;
        }

        .dock-button {
          flex: 1;
          max-width: 200px;
          height: 60px;
          background: rgba(50, 50, 70, 0.8);
          border: var(--border-width-medium) solid var(--color-border-default);
          color: var(--color-text-primary);
          font-family: var(--font-family);
          font-size: var(--font-size-sm);
          font-weight: var(--font-weight-bold);
          text-transform: uppercase;
          cursor: pointer;
          transition: all var(--transition-normal);
          border-radius: var(--border-radius-md);
        }

        .dock-button:hover:not(:disabled) {
          background: rgba(70, 70, 90, 0.9);
          border-color: var(--color-accent-cyan);
          box-shadow: var(--shadow-glow-cyan);
          transform: translateY(-2px);
        }

        .dock-button:disabled {
          opacity: 0.4;
          cursor: not-allowed;
          background: rgba(30, 30, 40, 0.5);
        }

        /* Hotspots */
        .hotspot {
          position: absolute;
          cursor: pointer;
          border: var(--border-width-medium) solid transparent;
          transition: all var(--transition-slow);
          z-index: 5;
        }

        .hotspot:hover {
          border-color: currentColor;
          box-shadow: 0 0 20px currentColor;
        }

        .hotspot.barracks {
          top: 40%;
          left: 10%;
          width: 20%;
          height: 20%;
          color: var(--color-accent-cyan-dark);
        }

        .hotspot.missions {
          top: 60%;
          left: 40%;
          width: 20%;
          height: 20%;
          color: var(--color-accent-gold);
        }

        .hotspot.market {
          top: 50%;
          left: 80%;
          width: 15%;
          height: 20%;
          color: var(--color-accent-green);
        }
      `,
    ];
  }

  static get properties() {
    return {
      wallet: { type: Object },
      rosterSummary: { type: Object },
      unlocks: { type: Object },
      activeOverlay: { type: String },
      day: { type: Number },
    };
  }

  constructor() {
    super();
    this.wallet = { aetherShards: 0, ancientCores: 0 };
    this.rosterSummary = { total: 0, ready: 0, injured: 0 };
    this.unlocks = { market: true, research: false }; // Market enabled by default
    this.activeOverlay = "NONE";
    this.day = 1;
  }

  connectedCallback() {
    super.connectedCallback();
    this._loadData();

    // Bind the handlers so we can remove them later
    this._boundHandleStateChange = this._handleStateChange.bind(this);
    this._boundHandleWalletUpdate = this._handleWalletUpdate.bind(this);
    // Listen for state changes to update data
    window.addEventListener("gamestate-changed", this._boundHandleStateChange);
    // Listen for wallet updates from Barracks
    window.addEventListener("wallet-updated", this._boundHandleWalletUpdate);
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    if (this._boundHandleStateChange) {
      window.removeEventListener(
        "gamestate-changed",
        this._boundHandleStateChange
      );
    }
    if (this._boundHandleWalletUpdate) {
      window.removeEventListener(
        "wallet-updated",
        this._boundHandleWalletUpdate
      );
    }
  }

  async _loadData() {
    // Load wallet data from hub stash (persistent currency)
    try {
      // First try to load from hub stash (where mission rewards go)
      if (gameStateManager.hubStash?.currency) {
        this.wallet = {
          aetherShards: gameStateManager.hubStash.currency.aetherShards || 0,
          ancientCores: gameStateManager.hubStash.currency.ancientCores || 0,
        };
      } else {
        // Fallback to run data if hub stash not available
        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);
    }

    // Load roster summary
    const deployableUnits = gameStateManager.rosterManager.getDeployableUnits();
    const allUnits = gameStateManager.rosterManager.roster || [];
    const injuredUnits = allUnits.filter((u) => u.status === "INJURED");

    this.rosterSummary = {
      total: allUnits.length,
      ready: deployableUnits.length,
      injured: injuredUnits.length,
    };

    // Load unlocks from completed missions
    const completedMissions =
      gameStateManager.missionManager.completedMissions || new Set();
    this.unlocks = {
      market: true, // Market always enabled
      research: completedMissions.size > 2, // Example: unlock research after 3 missions
    };

    this.requestUpdate();
  }

  _handleStateChange() {
    // Reload data when state changes
    this._loadData();
  }

  _handleWalletUpdate(e) {
    // Update wallet from event detail
    if (e.detail?.wallet) {
      this.wallet = e.detail.wallet;
      this.requestUpdate();
    } else {
      // Fallback: reload wallet data
      this._loadData();
    }
  }

  _openOverlay(type) {
    this.activeOverlay = type;
    this.requestUpdate();
  }

  _closeOverlay() {
    this.activeOverlay = "NONE";
    this.requestUpdate();
  }

  _onMissionSelected(e) {
    const missionId = e.detail?.missionId;
    if (missionId) {
      // Dispatch request-team-builder event
      window.dispatchEvent(
        new CustomEvent("request-team-builder", {
          detail: { missionId },
        })
      );
      this._closeOverlay();
    }
  }

  _handleHotspotClick(type) {
    if (type === "BARRACKS") {
      // Barracks is always available
      this._openOverlay("BARRACKS");
    } else if (type === "MISSIONS") {
      this._openOverlay("MISSIONS");
    } else if (type === "MARKET") {
      // Market is always available
      this._openOverlay("MARKET");
    } else if (type === "RESEARCH" && this.unlocks.research) {
      this._openOverlay("RESEARCH");
    }
  }

  _renderOverlay() {
    if (this.activeOverlay === "NONE") {
      return html``;
    }

    let overlayComponent = null;

    switch (this.activeOverlay) {
      case "MISSIONS":
        overlayComponent = html`
          <mission-board
            @mission-selected=${this._onMissionSelected}
            @close=${this._closeOverlay}
          ></mission-board>
        `;
        break;
      case "BARRACKS":
        overlayComponent = html`
          <barracks-screen
            @close-barracks=${this._closeOverlay}
          ></barracks-screen>
        `;
        break;
      case "MARKET":
        overlayComponent = html`
          <marketplace-screen
            .marketManager=${gameStateManager.marketManager}
            @market-closed=${this._closeOverlay}
          ></marketplace-screen>
        `;
        break;
      case "RESEARCH":
        overlayComponent = html`
          <research-screen @close=${this._closeOverlay}></research-screen>
        `;
        break;
      case "SYSTEM":
        overlayComponent = html`
          <div
            style="background: rgba(20, 20, 30, 0.95); padding: 30px; border: 2px solid #555; max-width: 800px;"
          >
            <h2 style="margin-top: 0; color: #ff6666;">SYSTEM</h2>
            <button
              @click=${() => {
                window.dispatchEvent(new CustomEvent("save-and-quit"));
                this._closeOverlay();
              }}
              style="margin-top: 20px; padding: 10px 20px; background: #333; border: 2px solid #555; color: white; cursor: pointer;"
            >
              Save and Quit
            </button>
            <button
              @click=${this._closeOverlay}
              style="margin-top: 20px; margin-left: 10px; padding: 10px 20px; background: #333; border: 2px solid #555; color: white; cursor: pointer;"
            >
              Close
            </button>
          </div>
        `;
        break;
    }

    return html`
      <div class="overlay-container active">
        <div class="overlay-backdrop" @click=${this._closeOverlay}></div>
        <div class="overlay-content">${overlayComponent}</div>
      </div>
    `;
  }

  render() {
    // Trigger async import when MISSIONS overlay is opened
    if (this.activeOverlay === "MISSIONS") {
      import("../components/mission-board.js").catch(console.error);
    }
    // Trigger async import when MARKET overlay is opened
    if (this.activeOverlay === "MARKET") {
      import("./marketplace-screen.js").catch(console.error);
    }
    // Trigger async import when BARRACKS overlay is opened
    if (this.activeOverlay === "BARRACKS") {
      import("./BarracksScreen.js").catch(console.error);
    }
    // Trigger async import when RESEARCH overlay is opened
    if (this.activeOverlay === "RESEARCH") {
      import("./ResearchScreen.js").catch(console.error);
    }

    return html`
      <div class="background"></div>

      <!-- Hotspots -->
      <div
        class="hotspot barracks"
        @click=${() => this._handleHotspotClick("BARRACKS")}
        title="Barracks"
      ></div>
      <div
        class="hotspot missions"
        @click=${() => this._handleHotspotClick("MISSIONS")}
        title="Mission Board"
      ></div>
      <div
        class="hotspot market"
        @click=${() => this._handleHotspotClick("MARKET")}
        title="Market"
        ?hidden=${!this.unlocks.market}
      ></div>

      <!-- Top Bar -->
      <div class="top-bar">
        <div class="logo">AETHER SHARDS</div>
        <div class="resource-strip">
          <div class="resource-item">
            <span class="icon">💎</span>
            <span>${this.wallet.aetherShards} Shards</span>
          </div>
          <div class="resource-item">
            <span class="icon">⚙️</span>
            <span>${this.wallet.ancientCores} Cores</span>
          </div>
          <div class="resource-item">
            <span>Day ${this.day}</span>
          </div>
        </div>
      </div>

      <!-- Bottom Dock -->
      <div class="bottom-dock">
        <button
          class="dock-button"
          @click=${() => this._openOverlay("BARRACKS")}
        >
          BARRACKS
        </button>
        <button
          class="dock-button"
          @click=${() => this._openOverlay("MISSIONS")}
        >
          MISSIONS
        </button>
        <button
          class="dock-button"
          ?disabled=${!this.unlocks.market}
          @click=${() => this._openOverlay("MARKET")}
        >
          MARKET
        </button>
        <button
          class="dock-button"
          ?disabled=${!this.unlocks.research}
          @click=${() => this._openOverlay("RESEARCH")}
        >
          RESEARCH
        </button>
        <button class="dock-button" @click=${() => this._openOverlay("SYSTEM")}>
          SYSTEM
        </button>
      </div>

      <!-- Overlay Container -->
      ${this._renderOverlay()}
    `;
  }
}

customElements.define("hub-screen", HubScreen);
