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

/**
 * MarketplaceScreen.js
 * The Gilded Bazaar - Marketplace UI component for buying and selling items.
 */
export class MarketplaceScreen extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      cardStyles,
      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: 1200px;
          max-height: 85vh;
          overflow: hidden;
          color: var(--color-text-primary);
          font-family: var(--font-family);
          display: grid;
          grid-template-columns: 250px 1fr;
          grid-template-rows: auto 1fr;
          grid-template-areas:
            "header header"
            "sidebar content";
          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-gold);
          font-size: var(--font-size-4xl);
        }

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

        .wallet-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);
        }

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

        .merchant-tab {
          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);
          text-align: left;
          font-family: inherit;
          color: var(--color-text-primary);
          font-size: var(--font-size-base);
          font-weight: var(--font-weight-bold);
          display: flex;
          align-items: center;
          gap: var(--spacing-sm);
        }

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

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

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

        /* Main Content */
        .content {
          grid-area: content;
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
          overflow: hidden;
        }

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

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

        .filter-button:hover:not(.active) {
          border-color: var(--color-accent-cyan);
        }

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

        .items-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
          gap: var(--spacing-md);
          overflow-y: auto;
          padding: var(--spacing-sm);
        }

        .item-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);
          position: relative;
          display: flex;
          flex-direction: column;
          align-items: center;
          text-align: center;
          min-height: 180px;
        }

        .item-card:hover:not(.sold-out):not(.unaffordable) {
          border-color: var(--color-accent-cyan);
          box-shadow: var(--shadow-glow-cyan);
          transform: translateY(-2px);
        }

        /* Rarity borders */
        .item-card.rarity-common {
          border-color: #888;
        }

        .item-card.rarity-uncommon {
          border-color: #00ff00;
        }

        .item-card.rarity-rare {
          border-color: #0088ff;
        }

        .item-card.rarity-ancient {
          border-color: #ff00ff;
        }

        .item-card.sold-out {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .item-card.unaffordable {
          opacity: 0.7;
        }

        .item-card.unaffordable .item-price {
          color: var(--color-accent-red);
        }

        .item-name {
          font-size: var(--font-size-sm);
          font-weight: var(--font-weight-bold);
          margin-bottom: var(--spacing-xs);
          color: var(--color-text-primary);
        }

        .item-type {
          font-size: var(--font-size-xs);
          color: var(--color-text-secondary);
          margin-bottom: var(--spacing-sm);
        }

        .item-price {
          font-size: var(--font-size-base);
          font-weight: var(--font-weight-bold);
          color: var(--color-accent-gold);
          margin-top: auto;
        }

        .sold-overlay {
          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);
          color: var(--color-text-muted);
        }

        /* Modal */
        .modal {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.8);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: var(--z-modal);
        }

        .modal-content {
          background: var(--color-bg-tertiary);
          border: var(--border-width-thick) solid var(--color-accent-gold);
          padding: var(--spacing-xl);
          max-width: 400px;
          width: 90%;
          display: flex;
          flex-direction: column;
          gap: var(--spacing-lg);
        }

        .modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .modal-title {
          font-size: var(--font-size-2xl);
          color: var(--color-accent-gold);
          margin: 0;
        }

        .modal-close {
          background: transparent;
          border: var(--border-width-medium) solid var(--color-accent-red);
          color: var(--color-accent-red);
          width: 30px;
          height: 30px;
          cursor: pointer;
          font-size: var(--font-size-lg);
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .modal-close:hover {
          background: var(--color-accent-red);
          color: white;
        }

        .modal-body {
          display: flex;
          flex-direction: column;
          gap: var(--spacing-md);
        }

        .modal-item-info {
          background: var(--color-bg-card);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-md);
        }

        .modal-actions {
          display: flex;
          gap: var(--spacing-md);
          justify-content: flex-end;
        }

        .empty-state {
          text-align: center;
          padding: var(--spacing-2xl);
          color: var(--color-text-muted);
        }
      `,
    ];
  }

  static get properties() {
    return {
      marketManager: { type: Object },
      wallet: { type: Object },
      activeMerchant: { type: String },
      activeFilter: { type: String },
      selectedItem: { type: Object, attribute: false },
      showModal: { type: Boolean, attribute: false },
    };
  }

  constructor() {
    super();
    this.marketManager = null;
    this.wallet = { aetherShards: 0, ancientCores: 0 };
    this.activeMerchant = "SMITH";
    this.activeFilter = "ALL";
    this.selectedItem = null;
    this.showModal = false;
  }

  connectedCallback() {
    super.connectedCallback();
    this._updateWallet();
    this.requestUpdate();
  }

  updated(changedProperties) {
    super.updated(changedProperties);
    if (changedProperties.has("marketManager")) {
      this._updateWallet();
    }
  }

  _updateWallet() {
    if (this.marketManager?.inventoryManager?.hubStash) {
      this.wallet = {
        aetherShards:
          this.marketManager.inventoryManager.hubStash.currency.aetherShards ||
          0,
        ancientCores:
          this.marketManager.inventoryManager.hubStash.currency.ancientCores ||
          0,
      };
    }
  }

  _getStock() {
    if (!this.marketManager) return [];
    const stock = this.marketManager.getStockForMerchant(this.activeMerchant);

    // Apply filter
    if (this.activeFilter === "ALL") {
      return stock;
    }
    return stock.filter((item) => item.type === this.activeFilter);
  }

  _onMerchantClick(merchant) {
    this.activeMerchant = merchant;
    this.activeFilter = "ALL";
    this.requestUpdate();
  }

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

  _onItemClick(item) {
    if (item.purchased) return;
    this.selectedItem = item;
    this.showModal = true;
    this.requestUpdate();
  }

  _closeModal() {
    this.showModal = false;
    this.selectedItem = null;
    this.requestUpdate();
  }

  async _confirmBuy() {
    if (!this.selectedItem || !this.marketManager) return;

    const success = await this.marketManager.buyItem(this.selectedItem.id);
    if (success) {
      this._updateWallet();
      this._closeModal();
      this.requestUpdate();
    } else {
      alert("Purchase failed. Check your currency.");
    }
  }

  _canAfford(item) {
    return this.wallet.aetherShards >= item.price;
  }

  _getRarityClass(rarity) {
    return `rarity-${rarity.toLowerCase()}`;
  }

  _getItemName(item) {
    // Get from itemRegistry if available
    if (this.marketManager?.itemRegistry) {
      const itemDef = this.marketManager.itemRegistry.get(item.defId);
      return itemDef?.name || item.defId;
    }
    return item.defId;
  }

  _dispatchClose() {
    this.dispatchEvent(
      new CustomEvent("market-closed", {
        bubbles: true,
        composed: true,
      })
    );
  }

  render() {
    const stock = this._getStock();
    const merchants = [
      { id: "SMITH", icon: "⚔️", label: "Smith" },
      { id: "TAILOR", icon: "🧥", label: "Tailor" },
      { id: "ALCHEMIST", icon: "⚗️", label: "Alchemist" },
      { id: "BUYBACK", icon: "♻️", label: "Buyback" },
    ];

    const filters = [
      { id: "ALL", label: "All" },
      { id: "WEAPON", label: "Weapons" },
      { id: "ARMOR", label: "Armor" },
      { id: "UTILITY", label: "Utility" },
      { id: "CONSUMABLE", label: "Consumables" },
    ];

    return html`
      <div class="header">
        <h2>The Gilded Bazaar</h2>
        <div class="wallet-display">
          <div class="wallet-item">
            <span>💎</span>
            <span>${this.wallet.aetherShards} Shards</span>
          </div>
          <button class="btn btn-close" @click=${this._dispatchClose}>✕</button>
        </div>
      </div>

      <div class="sidebar">
        ${merchants.map(
          (merchant) => html`
            <button
              class="merchant-tab ${this.activeMerchant === merchant.id
                ? "active"
                : ""}"
              @click=${() => this._onMerchantClick(merchant.id)}
            >
              <span class="merchant-icon">${merchant.icon}</span>
              <span>${merchant.label}</span>
            </button>
          `
        )}
      </div>

      <div class="content">
        <div class="filter-bar">
          ${filters.map(
            (filter) => html`
              <button
                class="filter-button ${this.activeFilter === filter.id
                  ? "active"
                  : ""}"
                @click=${() => this._onFilterClick(filter.id)}
              >
                ${filter.label}
              </button>
            `
          )}
        </div>

        <div class="items-grid">
          ${stock.length === 0
            ? html`<div class="empty-state">No items available</div>`
            : stock.map(
                (item) => html`
                  <div
                    class="item-card ${this._getRarityClass(
                      item.rarity
                    )} ${item.purchased ? "sold-out" : ""} ${!this._canAfford(
                      item
                    ) && !item.purchased
                      ? "unaffordable"
                      : ""}"
                    @click=${() => this._onItemClick(item)}
                  >
                    ${item.purchased
                      ? html`<div class="sold-overlay">SOLD</div>`
                      : ""}
                    <div class="item-name">${this._getItemName(item)}</div>
                    <div class="item-type">${item.type}</div>
                    <div class="item-price">${item.price} 💎</div>
                  </div>
                `
              )}
        </div>
      </div>

      ${this.showModal && this.selectedItem
        ? html`
            <div
              class="modal"
              @click=${(e) =>
                e.target.classList.contains("modal") && this._closeModal()}
            >
              <div class="modal-content">
                <div class="modal-header">
                  <h3 class="modal-title">Confirm Purchase</h3>
                  <button class="modal-close" @click=${this._closeModal}>
                    ✕
                  </button>
                </div>
                <div class="modal-body">
                  <div class="modal-item-info">
                    <div class="item-name">
                      ${this._getItemName(this.selectedItem)}
                    </div>
                    <div class="item-type">${this.selectedItem.type}</div>
                    <div class="item-price">
                      Price: ${this.selectedItem.price} 💎
                    </div>
                  </div>
                  ${!this._canAfford(this.selectedItem)
                    ? html`<div style="color: var(--color-accent-red);">
                        Insufficient funds!
                      </div>`
                    : ""}
                </div>
                <div class="modal-actions">
                  <button
                    class="btn btn-primary"
                    ?disabled=${!this._canAfford(this.selectedItem)}
                    @click=${this._confirmBuy}
                  >
                    Buy for ${this.selectedItem.price} 💎
                  </button>
                  <button class="btn" @click=${this._closeModal}>Cancel</button>
                </div>
              </div>
            </div>
          `
        : ""}
    `;
  }
}

customElements.define("marketplace-screen", MarketplaceScreen);
