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

/**
 * MissionReview.js
 * Component for reviewing completed missions, showing rewards and narrative.
 * @class
 */
export class MissionReview extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      cardStyles,
      overlayStyles,
      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: 900px;
          max-height: 85vh;
          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-3xl);
        }

        .close-button {
          background: transparent;
          border: none;
          color: var(--color-text-primary);
          font-size: var(--font-size-2xl);
          cursor: pointer;
          padding: var(--spacing-xs);
          line-height: 1;
          transition: color var(--transition-normal);
        }

        .close-button:hover {
          color: var(--color-accent-red);
        }

        .mission-info {
          margin-bottom: var(--spacing-xl);
        }

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

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

        .section {
          margin-bottom: var(--spacing-xl);
        }

        .section-title {
          font-size: var(--font-size-xl);
          font-weight: var(--font-weight-bold);
          color: var(--color-accent-cyan);
          margin-bottom: var(--spacing-md);
          padding-bottom: var(--spacing-sm);
          border-bottom: var(--border-width-thin) solid var(--color-border-default);
        }

        .rewards-grid {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
          gap: var(--spacing-md);
        }

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

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

        .reward-text {
          display: flex;
          flex-direction: column;
        }

        .reward-label {
          font-size: var(--font-size-xs);
          color: var(--color-text-muted);
          text-transform: uppercase;
        }

        .reward-value {
          font-size: var(--font-size-lg);
          font-weight: var(--font-weight-bold);
          color: var(--color-accent-gold);
        }

        .narrative-content {
          background: var(--color-bg-card);
          border: var(--border-width-thin) solid var(--color-border-default);
          padding: var(--spacing-lg);
          border-radius: var(--border-radius-md);
          max-height: 400px;
          overflow-y: auto;
        }

        .narrative-node {
          margin-bottom: var(--spacing-lg);
          padding-bottom: var(--spacing-lg);
          border-bottom: var(--border-width-thin) solid var(--color-border-default);
        }

        .narrative-node:last-child {
          border-bottom: none;
          margin-bottom: 0;
          padding-bottom: 0;
        }

        .narrative-speaker {
          font-size: var(--font-size-sm);
          font-weight: var(--font-weight-bold);
          color: var(--color-accent-cyan);
          margin-bottom: var(--spacing-xs);
        }

        .narrative-text {
          font-size: var(--font-size-md);
          color: var(--color-text-primary);
          line-height: 1.6;
          font-style: italic;
        }

        .narrative-portrait {
          width: 48px;
          height: 48px;
          border-radius: var(--border-radius-md);
          border: var(--border-width-thin) solid var(--color-border-default);
          margin-bottom: var(--spacing-sm);
          object-fit: cover;
        }

        .loading {
          text-align: center;
          padding: var(--spacing-2xl);
          color: var(--color-text-muted);
        }

        .empty-narrative {
          text-align: center;
          padding: var(--spacing-lg);
          color: var(--color-text-muted);
          font-style: italic;
        }

        .narrative-section {
          margin-bottom: var(--spacing-xl);
        }

        .narrative-section:last-child {
          margin-bottom: 0;
        }
      `
    ];
  }

  static get properties() {
    return {
      mission: { type: Object },
      introNarrative: { type: Object },
      outroNarrative: { type: Object },
      loading: { type: Boolean },
    };
  }

  constructor() {
    super();
    this.mission = null;
    this.introNarrative = null;
    this.outroNarrative = null;
    this.loading = false;
  }

  async connectedCallback() {
    super.connectedCallback();
    if (this.mission) {
      await this._loadNarratives();
    }
  }

  async updated(changedProperties) {
    if (changedProperties.has('mission') && this.mission) {
      await this._loadNarratives();
    }
  }

  _mapNarrativeIdToFileName(narrativeId) {
    // Convert NARRATIVE_STORY_03_INTRO -> narrative_story_03_intro
    // Remove NARRATIVE_ prefix and convert to lowercase
    const mapping = {
      NARRATIVE_TUTORIAL_INTRO: "tutorial_intro",
      NARRATIVE_TUTORIAL_SUCCESS: "tutorial_success",
      NARRATIVE_ACT1_FINAL_WIN: "act1_final_win",
      NARRATIVE_ACT1_FINAL_LOSE: "act1_final_lose",
    };

    if (mapping[narrativeId]) {
      return mapping[narrativeId];
    }

    // For unmapped IDs, convert NARRATIVE_XYZ -> narrative_xyz
    return narrativeId.toLowerCase().replace("narrative_", "");
  }

  async _loadNarratives() {
    this.loading = true;
    this.introNarrative = null;
    this.outroNarrative = null;

    const narrative = this.mission?.narrative;
    if (!narrative) {
      this.loading = false;
      return;
    }

    const loadPromises = [];

    if (narrative.intro_sequence) {
      loadPromises.push(
        this._loadNarrativeFile(narrative.intro_sequence).then(data => {
          this.introNarrative = data;
        }).catch(err => {
          console.error('Failed to load intro narrative:', err);
        })
      );
    }

    if (narrative.outro_success) {
      loadPromises.push(
        this._loadNarrativeFile(narrative.outro_success).then(data => {
          this.outroNarrative = data;
        }).catch(err => {
          console.error('Failed to load outro narrative:', err);
        })
      );
    }

    await Promise.all(loadPromises);
    this.loading = false;
    this.requestUpdate();
  }

  async _loadNarrativeFile(narrativeId) {
    const fileName = this._mapNarrativeIdToFileName(narrativeId);
    const response = await fetch(`assets/data/narrative/${fileName}.json`);
    if (!response.ok) {
      throw new Error(`Failed to load narrative: ${fileName}`);
    }
    return await response.json();
  }

  _formatRewards(rewards) {
    const rewardItems = [];
    
    if (rewards?.currency) {
      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: '💎', 
          label: 'Aether Shards', 
          value: shards 
        });
      }
      if (cores > 0) {
        rewardItems.push({ 
          icon: '⚙️', 
          label: 'Ancient Cores', 
          value: cores 
        });
      }
    }

    if (rewards?.xp) {
      rewardItems.push({ 
        icon: '⭐', 
        label: 'Experience', 
        value: rewards.xp 
      });
    }

    if (rewards?.unlocks && Array.isArray(rewards.unlocks)) {
      rewards.unlocks.forEach(unlock => {
        rewardItems.push({ 
          icon: '🔓', 
          label: 'Unlock', 
          value: unlock 
        });
      });
    }

    return rewardItems;
  }

  _renderNarrativeNodes(nodes) {
    if (!nodes || nodes.length === 0) {
      return html`<div class="empty-narrative">No narrative content available.</div>`;
    }

    return html`
      ${nodes.map(node => html`
        <div class="narrative-node">
          ${node.portrait ? html`
            <img 
              src="${node.portrait}" 
              alt="${node.speaker || 'Speaker'}"
              class="narrative-portrait"
              @error=${(e) => { e.target.style.display = 'none'; }}
            />
          ` : ''}
          ${node.speaker ? html`
            <div class="narrative-speaker">${node.speaker}</div>
          ` : ''}
          <div class="narrative-text">${node.text || ''}</div>
        </div>
      `)}
    `;
  }

  render() {
    if (!this.mission) {
      return html`
        <div class="header">
          <h2>Mission Review</h2>
          <button class="close-button" @click=${() => this.dispatchEvent(new CustomEvent('close', { bubbles: true, composed: true }))}>
            ×
          </button>
        </div>
        <div class="loading">
          <p>No mission data available.</p>
        </div>
      `;
    }

    const rewards = this._formatRewards(this.mission.rewards?.guaranteed || this.mission.rewards || {});
    const config = this.mission.config || {};

    return html`
      <div class="header">
        <h2>Mission Review</h2>
        <button class="close-button" @click=${(e) => {
          e.stopPropagation();
          this.dispatchEvent(new CustomEvent('review-close', { bubbles: false, composed: true }));
        }}>
          ×
        </button>
      </div>

      <div class="mission-info">
        <div class="mission-title">${config.title || this.mission.id}</div>
        <div class="mission-description">${config.description || 'No description available.'}</div>
      </div>

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

      ${this.loading ? html`
        <div class="section">
          <div class="loading">Loading narrative content...</div>
        </div>
      ` : html`
        ${this.introNarrative || this.outroNarrative ? html`
          <div class="section">
            <div class="section-title">Narrative</div>
            <div class="narrative-content">
              ${this.introNarrative ? html`
                <div class="narrative-section">
                  <h4 style="color: var(--color-accent-cyan); margin-bottom: var(--spacing-md); font-size: var(--font-size-lg);">
                    Mission Briefing
                  </h4>
                  ${this._renderNarrativeNodes(this.introNarrative.nodes)}
                </div>
              ` : ''}
              ${this.outroNarrative ? html`
                <div class="narrative-section">
                  <h4 style="color: var(--color-accent-cyan); margin-bottom: var(--spacing-md); font-size: var(--font-size-lg);">
                    Mission Conclusion
                  </h4>
                  ${this._renderNarrativeNodes(this.outroNarrative.nodes)}
                </div>
              ` : ''}
            </div>
          </div>
        ` : ''}
      `}
    `;
  }
}

customElements.define('mission-review', MissionReview);

