import { LitElement, html, css } from 'lit';
import { gameStateManager } from '../../core/GameStateManager.js';
import { theme, buttonStyles, cardStyles, gridStyles, badgeStyles } from '../styles/theme.js';

/**
 * MissionBoard.js
 * Component for displaying and selecting available missions.
 * @class
 */
export class MissionBoard extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      cardStyles,
      gridStyles,
      badgeStyles,
      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: 1000px;
          max-height: 80vh;
          overflow-y: auto;
          color: var(--color-text-primary);
          font-family: var(--font-family);
        }

        .header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: var(--spacing-xl);
          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);
        }

        .missions-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
          gap: var(--spacing-lg);
          margin-bottom: var(--spacing-lg);
        }

        .mission-card {
          background: var(--color-bg-card);
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-lg);
          cursor: pointer;
          transition: all var(--transition-normal);
          position: relative;
        }

        .mission-card:hover {
          border-color: var(--color-accent-gold);
          box-shadow: var(--shadow-glow-gold);
          transform: translateY(-2px);
        }

        .mission-card.completed {
          border-color: var(--color-accent-green);
          opacity: 0.7;
        }

        .mission-card.locked {
          opacity: 0.5;
          cursor: not-allowed;
          border-color: var(--color-border-dark);
        }

        .mission-card.locked:hover {
          transform: none;
          border-color: var(--color-border-dark);
          box-shadow: none;
        }

        .mission-header {
          display: flex;
          justify-content: space-between;
          align-items: start;
          margin-bottom: var(--spacing-md);
        }

        .mission-title {
          font-size: var(--font-size-2xl);
          font-weight: var(--font-weight-bold);
          color: var(--color-accent-cyan);
          margin: 0;
        }

        .mission-type {
          font-size: var(--font-size-xs);
          padding: 4px var(--spacing-sm);
          background: rgba(255, 255, 255, 0.1);
          border-radius: var(--border-radius-md);
          text-transform: uppercase;
        }

        .mission-type.STORY {
          background: rgba(255, 0, 0, 0.3);
          color: var(--color-accent-red);
        }

        .mission-type.SIDE_QUEST {
          background: rgba(255, 215, 0, 0.3);
          color: var(--color-accent-gold);
        }

        .mission-type.TUTORIAL {
          background: rgba(0, 255, 255, 0.3);
          color: var(--color-accent-cyan);
        }

        .mission-type.PROCEDURAL {
          background: rgba(0, 255, 0, 0.3);
          color: var(--color-accent-green);
        }

        .mission-description {
          font-size: var(--font-size-sm);
          color: var(--color-text-secondary);
          margin-bottom: var(--spacing-md);
          line-height: 1.5;
        }

        .mission-rewards {
          display: flex;
          gap: var(--spacing-sm);
          flex-wrap: wrap;
          margin-bottom: var(--spacing-sm);
        }

        .reward-item {
          display: flex;
          align-items: center;
          gap: var(--spacing-xs);
          font-size: var(--font-size-xs);
          color: var(--color-accent-gold);
        }

        .mission-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: var(--spacing-md);
          padding-top: var(--spacing-md);
          border-top: var(--border-width-thin) solid var(--color-border-default);
        }

        .difficulty {
          font-size: var(--font-size-xs);
          color: var(--color-text-secondary);
        }

        .select-button {
          background: #008800;
          border: var(--border-width-medium) solid var(--color-accent-green);
          color: white;
          padding: var(--spacing-sm) var(--spacing-lg);
          font-family: var(--font-family);
          font-size: var(--font-size-sm);
          font-weight: var(--font-weight-bold);
          cursor: pointer;
          transition: all var(--transition-normal);
          border-radius: var(--border-radius-md);
        }

        .select-button:hover:not(:disabled) {
          background: #00aa00;
          box-shadow: var(--shadow-glow-green);
        }

        .select-button:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

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

  static get properties() {
    return {
      missions: { type: Array },
      completedMissions: { type: Set },
    };
  }

  constructor() {
    super();
    this.missions = [];
    this.completedMissions = new Set();
  }

  connectedCallback() {
    super.connectedCallback();
    this._loadMissions();
    
    // Listen for campaign data changes to refresh completed missions
    this._boundHandleCampaignChange = this._handleCampaignChange.bind(this);
    window.addEventListener('campaign-data-changed', this._boundHandleCampaignChange);
    window.addEventListener('gamestate-changed', this._boundHandleCampaignChange);
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    if (this._boundHandleCampaignChange) {
      window.removeEventListener('campaign-data-changed', this._boundHandleCampaignChange);
      window.removeEventListener('gamestate-changed', this._boundHandleCampaignChange);
    }
  }

  _handleCampaignChange() {
    // Reload missions when campaign data changes (mission completed)
    this._loadMissions();
  }

  async _loadMissions() {
    // Ensure missions are loaded before accessing registry
    await gameStateManager.missionManager._ensureMissionsLoaded();
    // Get all registered missions from MissionManager
    const missionRegistry = gameStateManager.missionManager.missionRegistry;
    this.missions = Array.from(missionRegistry.values());
    this.completedMissions = gameStateManager.missionManager.completedMissions || new Set();
    this.requestUpdate();
  }

  _isMissionAvailable(mission) {
    // Check if mission prerequisites are met
    const prerequisites = mission.config?.prerequisites || [];
    
    // If no prerequisites, mission is available
    if (prerequisites.length === 0) {
      return true;
    }
    
    // Check if all prerequisites are completed
    return prerequisites.every(prereqId => this.completedMissions.has(prereqId));
  }

  /**
   * Determines if a mission should be shown in the mission board.
   * Story missions are hidden until available, other types show as locked.
   * @param {Object} mission - Mission definition
   * @returns {boolean}
   */
  _shouldShowMission(mission) {
    const isAvailable = this._isMissionAvailable(mission);
    
    // If available, always show
    if (isAvailable) {
      return true;
    }
    
    // Check visibility setting (defaults based on mission type)
    const visibility = mission.config?.visibility_when_locked;
    
    // Default behavior: STORY missions are hidden, others show as locked
    if (visibility === undefined) {
      return mission.type !== "STORY";
    }
    
    // Explicit setting overrides default
    return visibility === "locked";
  }

  _isMissionCompleted(missionId) {
    return this.completedMissions.has(missionId);
  }

  _selectMission(mission) {
    if (!this._isMissionAvailable(mission)) {
      return;
    }

    // Dispatch mission-selected event
    this.dispatchEvent(
      new CustomEvent('mission-selected', {
        detail: { missionId: mission.id },
        bubbles: true,
        composed: true,
      })
    );
  }

  _formatRewards(rewards) {
    const rewardItems = [];
    
    if (rewards?.currency) {
      // Handle both snake_case (from JSON) and camelCase (from code)
      const shards = rewards.currency.aether_shards || rewards.currency.aetherShards || 0;
      const cores = rewards.currency.ancient_cores || rewards.currency.ancientCores || 0;
      
      if (shards > 0) {
        rewardItems.push({ icon: '💎', text: `${shards} Shards` });
      }
      if (cores > 0) {
        rewardItems.push({ icon: '⚙️', text: `${cores} Cores` });
      }
    }

    if (rewards?.xp) {
      rewardItems.push({ icon: '⭐', text: `${rewards.xp} XP` });
    }

    return rewardItems;
  }

  _getDifficultyLabel(config) {
    if (config?.difficulty_tier) {
      return `Tier ${config.difficulty_tier}`;
    }
    if (config?.difficulty) {
      return config.difficulty.toUpperCase();
    }
    if (config?.recommended_level) {
      return `Level ${config.recommended_level}`;
    }
    return 'Unknown';
  }

  render() {
    if (this.missions.length === 0) {
      return html`
        <div class="header">
          <h2>MISSION BOARD</h2>
          <button class="btn btn-close" @click=${() => this.dispatchEvent(new CustomEvent('close', { bubbles: true, composed: true }))}>
            ×
          </button>
        </div>
        <div class="empty-state">
          <p>No missions available at this time.</p>
        </div>
      `;
    }

    return html`
      <div class="header">
        <h2>MISSION BOARD</h2>
        <button class="close-button" @click=${() => this.dispatchEvent(new CustomEvent('close', { bubbles: true, composed: true }))}>
          ×
        </button>
      </div>

      <div class="missions-grid">
        ${this.missions
          .filter(mission => this._shouldShowMission(mission))
          .map((mission) => {
          const isCompleted = this._isMissionCompleted(mission.id);
          const isAvailable = this._isMissionAvailable(mission);
          const rewards = this._formatRewards(mission.rewards);

          return html`
            <div
              class="mission-card ${isCompleted ? 'completed' : ''} ${!isAvailable ? 'locked' : ''}"
              @click=${() => isAvailable && this._selectMission(mission)}
            >
              <div class="mission-header">
                <h3 class="mission-title">${mission.config?.title || mission.id}</h3>
                <span class="mission-type ${mission.type || 'PROCEDURAL'}">
                  ${mission.type || 'PROCEDURAL'}
                </span>
              </div>

              <p class="mission-description">
                ${mission.config?.description || 'No description available.'}
              </p>

              ${rewards.length > 0 ? html`
                <div class="mission-rewards">
                  ${rewards.map((reward) => html`
                    <div class="reward-item">
                      <span>${reward.icon}</span>
                      <span>${reward.text}</span>
                    </div>
                  `)}
                </div>
              ` : ''}

              <div class="mission-footer">
                <span class="difficulty">
                  Difficulty: ${this._getDifficultyLabel(mission.config)}
                </span>
                ${isCompleted ? html`<span style="color: var(--color-accent-green);">✓ Completed</span>` : ''}
                ${!isAvailable && !isCompleted ? html`
                  <span style="color: var(--color-text-muted); font-size: var(--font-size-xs);">
                    🔒 Requires: ${mission.config?.prerequisites?.map(id => {
                      const prereqMission = this.missions.find(m => m.id === id);
                      return prereqMission?.config?.title || id;
                    }).join(', ') || 'Previous missions'}
                  </span>
                ` : ''}
                ${isAvailable && !isCompleted ? html`
                  <button
                    class="btn btn-primary"
                    @click=${(e) => {
                      e.stopPropagation();
                      this._selectMission(mission);
                    }}
                  >
                    SELECT
                  </button>
                ` : ''}
              </div>
            </div>
          `;
        })}
      </div>
    `;
  }
}

customElements.define('mission-board', MissionBoard);

