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

// Class definitions will be lazy-loaded when component connects

// UI Metadata Mapping
const CLASS_METADATA = {
  'CLASS_VANGUARD': { 
    icon: '🛡️', 
    portrait: 'assets/images/portraits/vanguard.png',
    role: 'Tank', 
    description: 'A heavy frontline tank specialized in absorbing damage.' 
  },
  'CLASS_WEAVER': { 
    icon: '✨', 
    portrait: 'assets/images/portraits/weaver.png',
    role: 'Magic DPS', 
    description: 'A master of elemental magic capable of creating synergy chains.' 
  },
  'CLASS_SCAVENGER': { 
    icon: '🎒', 
    portrait: 'assets/images/portraits/scavenger.png',
    role: 'Utility', 
    description: 'Highly mobile utility expert who excels at finding loot.' 
  },
  'CLASS_TINKER': { 
    icon: '🔧', 
    portrait: 'assets/images/portraits/tinker.png',
    role: 'Tech', 
    description: 'Uses ancient technology to deploy turrets.' 
  },
  'CLASS_CUSTODIAN': { 
    icon: '🌿', 
    portrait: 'assets/images/portraits/custodian.png',
    role: 'Healer', 
    description: 'A spiritual healer focused on removing corruption.' 
  }
};

// Class definitions loaded lazily
let RAW_TIER_1_CLASSES = null;

export class TeamBuilder extends LitElement {
  static get styles() {
    return [
      theme,
      buttonStyles,
      cardStyles,
      css`
        :host {
          display: block;
          position: absolute;
          top: 0; left: 0; width: 100%; height: 100%;
          font-family: var(--font-family);
          color: var(--color-text-primary);
          pointer-events: none;
          z-index: var(--z-overlay);
          box-sizing: border-box;
        }

        .container {
          display: grid;
          grid-template-columns: 280px 1fr 300px;
          grid-template-rows: 1fr 100px;
          grid-template-areas: "roster squad details" "footer footer footer";
          height: 100%; width: 100%;
          pointer-events: auto;
          background: rgba(0, 0, 0, 0.85);
          backdrop-filter: blur(4px);
        }

        @media (max-width: 1024px) {
          .container {
            grid-template-columns: 1fr;
            grid-template-rows: 200px 1fr 200px 80px;
            grid-template-areas: "roster" "squad" "details" "footer";
          }
        }

        /* --- LEFT PANEL: ROSTER --- */
        .roster-panel {
          grid-area: roster;
          background: var(--color-bg-panel);
          border-right: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-base);
          overflow-y: auto;
          display: flex;
          flex-direction: column;
          gap: var(--spacing-sm);
        }

        h3 { 
          margin-top: 0; 
          color: var(--color-accent-cyan); 
          border-bottom: var(--border-width-thin) solid var(--color-border-default); 
          padding-bottom: var(--spacing-sm); 
        }

        .card {
          background: #333;
          border: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-md);
          cursor: pointer;
          transition: all var(--transition-normal);
          display: flex;
          align-items: center;
          gap: var(--spacing-md);
          width: 100%;
          text-align: left;
          font-family: inherit;
          color: inherit;
          appearance: none;
        }

        .card:hover:not(:disabled) {
          border-color: var(--color-accent-cyan);
          background: #444;
          transform: translateX(5px);
        }

        .card.selected {
          border-color: var(--color-accent-green);
          background: #224422;
        }

        .card:disabled {
          opacity: 0.5;
          cursor: not-allowed;
          filter: grayscale(1);
        }

        /* --- CENTER PANEL: SQUAD SLOTS --- */
        .squad-panel {
          grid-area: squad;
          display: flex;
          justify-content: center;
          align-items: center;
          padding: var(--spacing-2xl);
          gap: var(--spacing-xl);
          flex-wrap: wrap;
        }

        .slot-wrapper {
          position: relative;
          width: 180px; /* Wider for portraits */
          height: 240px; /* Taller for portraits */
          transition: transform var(--transition-normal);
        }
        .slot-wrapper:hover { transform: scale(1.05); }

        .squad-slot {
          width: 100%; height: 100%;
          background: rgba(10, 10, 10, 0.8);
          border: var(--border-width-thick) dashed var(--color-border-light);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          font-family: inherit; color: inherit; padding: 0; appearance: none;
          overflow: hidden;
        }
        
        /* Image placeholder style */
        .unit-image {
          width: 100%;
          height: 75%;
          object-fit: cover;
          background-color: #222; 
          border-bottom: var(--border-width-medium) solid var(--color-border-default);
        }
        
        .unit-info {
          height: 25%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 100%;
          background: rgba(30,30,40,0.95);
          padding: var(--spacing-xs);
          box-sizing: border-box;
        }

        .squad-slot.filled {
          border: var(--border-width-thick) solid var(--color-accent-green);
          background: rgba(0, 20, 0, 0.8);
        }
        
        .squad-slot.selected {
          border-color: var(--color-accent-cyan);
          box-shadow: var(--shadow-glow-cyan);
        }

        .remove-btn {
          position: absolute; top: -12px; right: -12px;
          background: #cc0000; color: white;
          width: 28px; height: 28px;
          border: var(--border-width-medium) solid white; border-radius: 50%;
          cursor: pointer; font-weight: var(--font-weight-bold); z-index: 2;
        }
        
        .placeholder-img {
          display: flex; 
          align-items: center; 
          justify-content: center; 
          background: transparent; 
          color: var(--color-border-default); 
          font-size: var(--font-size-5xl);
          height: 100%;
        }

        /* --- RIGHT PANEL: DETAILS --- */
        .details-panel {
          grid-area: details;
          background: var(--color-bg-panel);
          border-left: var(--border-width-medium) solid var(--color-border-default);
          padding: var(--spacing-xl);
          overflow-y: auto;
        }

        .footer {
          grid-area: footer;
          display: flex;
          justify-content: center;
          align-items: center;
          background: var(--color-bg-tertiary);
          border-top: var(--border-width-medium) solid var(--color-border-default);
        }

        .embark-btn {
          padding: var(--spacing-md) var(--spacing-2xl);
          font-size: var(--font-size-3xl);
          background: #008800;
          color: white;
          border: var(--border-width-thick) solid var(--color-accent-green);
          cursor: pointer;
          text-transform: uppercase;
          font-weight: var(--font-weight-bold);
          font-family: var(--font-family);
          letter-spacing: 2px;
        }
        .embark-btn:disabled {
          background: #333; border-color: var(--color-border-default); color: var(--color-text-muted); cursor: not-allowed;
        }
      `
    ];
  }

  static get properties() {
    return {
      mode: { type: String }, // 'DRAFT' (Classes) or 'ROSTER' (Existing Units)
      availablePool: { type: Array }, // List of Classes OR Units
      squad: { type: Array }, // The 4 slots
      selectedSlotIndex: { type: Number },
      hoveredItem: { type: Object }
    };
  }

  constructor() {
    super();
    this.squad = [null, null, null, null];
    this.selectedSlotIndex = 0;
    this.hoveredItem = null;
    this.mode = 'DRAFT'; // Default
    this.availablePool = [];
    /** @type {boolean} Whether availablePool was explicitly set (vs default empty) */
    this._poolExplicitlySet = false;
  }

  async connectedCallback() {
    super.connectedCallback();
    await this._initializeData();
    
    // Listen for unlock changes to refresh the class list
    this._boundHandleUnlocksChanged = this._handleUnlocksChanged.bind(this);
    window.addEventListener('classes-unlocked', this._boundHandleUnlocksChanged);
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    if (this._boundHandleUnlocksChanged) {
      window.removeEventListener('classes-unlocked', this._boundHandleUnlocksChanged);
    }
  }

  /**
   * Handles unlock changes by refreshing the class list.
   */
  async _handleUnlocksChanged() {
    if (this.mode === 'DRAFT') {
      await this._initializeData();
      this.requestUpdate();
    }
  }

  /**
   * Lifecycle method called when properties change.
   * Re-initializes data if availablePool changes.
   */
  willUpdate(changedProperties) {
    if (changedProperties.has('availablePool')) {
      this._initializeData();
    }
  }

  /**
   * Configures the component based on provided data.
   */
  async _initializeData() {
    // 1. If availablePool was explicitly set (from mission selection), use ROSTER mode.
    // This happens when opening from mission selection - we want to show roster even if all units are injured.
    if (this._poolExplicitlySet) {
        this.mode = 'ROSTER';
        console.log("TeamBuilder: Using Roster Mode", this.availablePool.length > 0 ? `with ${this.availablePool.length} deployable units` : "with no deployable units");
        return;
    }

    // 2. Default: Draft Mode (New Game)
    // Populate with Tier 1 classes and check unlock status
    this.mode = 'DRAFT';
    
    // Lazy-load class definitions if not already loaded
    if (!RAW_TIER_1_CLASSES) {
      const [vanguardDef, weaverDef, scavengerDef, tinkerDef, custodianDef] = await Promise.all([
        import('../assets/data/classes/vanguard.json', { with: { type: 'json' } }).then(m => m.default),
        import('../assets/data/classes/aether_weaver.json', { with: { type: 'json' } }).then(m => m.default),
        import('../assets/data/classes/scavenger.json', { with: { type: 'json' } }).then(m => m.default),
        import('../assets/data/classes/tinker.json', { with: { type: 'json' } }).then(m => m.default),
        import('../assets/data/classes/custodian.json', { with: { type: 'json' } }).then(m => m.default)
      ]);
      RAW_TIER_1_CLASSES = [vanguardDef, weaverDef, scavengerDef, tinkerDef, custodianDef];
    }
    
    // Load unlocked classes from persistence
    let unlockedClasses = [];
    try {
      if (gameStateManager?.persistence) {
        unlockedClasses = await gameStateManager.persistence.loadUnlocks();
      } else {
        // Fallback to localStorage if persistence not available
        const stored = localStorage.getItem('aether_shards_unlocks');
        if (stored) {
          unlockedClasses = JSON.parse(stored);
        }
      }
    } catch (e) {
      console.warn('Failed to load unlocks:', e);
    }
    
    // Define which classes are unlocked by default (starter classes)
    // Note: CLASS_TINKER is unlocked by the tutorial mission, so it's not in the default list
    const defaultUnlocked = ['CLASS_VANGUARD', 'CLASS_WEAVER'];
    
    this.availablePool = RAW_TIER_1_CLASSES.map(cls => {
      const meta = CLASS_METADATA[cls.id] || {};
      // Check if class is unlocked (either default or in unlocked list)
      const isUnlocked = defaultUnlocked.includes(cls.id) || unlockedClasses.includes(cls.id);
      return { ...cls, ...meta, unlocked: isUnlocked };
    });
    console.log("TeamBuilder: Initializing Draft Mode", { unlockedClasses, availablePool: this.availablePool.map(c => ({ id: c.id, unlocked: c.unlocked })) });
  }

  render() {
    const isSquadValid = this.squad.some(u => u !== null);

    return html`
      <div class="container">
        <!-- ROSTER PANEL -->
        <div class="roster-panel">
          <h3>${this.mode === 'DRAFT' ? 'Recruit Explorers' : 'Barracks Roster'}</h3>
          
          ${this.availablePool.map(item => {
             const isSelected = this.squad.some(s => s && (this.mode === 'ROSTER' ? s.id === item.id : false));
             
             return html`
              <button 
                type="button"
                class="card ${isSelected ? 'selected' : ''}"
                ?disabled="${this.mode === 'DRAFT' && !item.unlocked || isSelected}"
                @click="${() => this._assignItem(item)}"
                @mouseenter="${() => this.hoveredItem = item}"
                @mouseleave="${() => this.hoveredItem = null}"
              >
                <div class="icon" style="font-size: 1.5rem;">
                    ${item.icon || CLASS_METADATA[item.classId]?.icon || '⚔️'}
                </div>
                <div>
                  <strong>${item.name}</strong><br>
                  <small>${this.mode === 'ROSTER' ? (() => {
                    // Calculate level from classMastery
                    const activeClassId = item.activeClassId || item.classId;
                    const level = item.classMastery?.[activeClassId]?.level || 1;
                    return `Lvl ${level} ${item.classId.replace('CLASS_', '')}`;
                  })() : item.role}</small>
                </div>
              </button>
            `;
          })}
        </div>

        <!-- SQUAD SLOTS -->
        <div class="squad-panel">
          ${this.squad.map((unit, index) => html`
            <div class="slot-wrapper">
              <button 
                type="button"
                class="squad-slot ${unit ? 'filled' : ''} ${this.selectedSlotIndex === index ? 'selected' : ''}"
                @click="${() => this._selectSlot(index)}"
              >
                ${unit 
                  ? html`
                      <!-- Use portrait/image property if available, otherwise show large icon placeholder -->
                      ${(unit.portrait || unit.image)
                        ? html`<img src="${unit.portrait || unit.image}" alt="${unit.name}" class="unit-image" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'">` 
                        : ''
                      }
                      <div class="placeholder-img" style="${(unit.portrait || unit.image) ? 'display:none;' : ''} font-size: 3rem;">
                         ${unit.icon || '🛡️'}
                      </div>
                      
                      <div class="unit-info">
                        <strong>${unit.name}</strong>
                        <small style="font-size: 0.7rem; color: #aaa;">${this.mode === 'DRAFT' ? unit.role : unit.classId.replace('CLASS_', '')}</small>
                      </div>
                    ` 
                  : html`
                      <div class="placeholder-img">+</div>
                      <div class="unit-info" style="background:transparent;">
                        <span>Slot ${index + 1}</span>
                        <small>Select ${this.mode === 'DRAFT' ? 'Class' : 'Unit'}</small>
                      </div>
                    `
                }
              </button>
              ${unit ? html`<button type="button" class="remove-btn" @click="${() => this._removeUnit(index)}">X</button>` : ''}
            </div>
          `)}
        </div>

        <!-- DETAILS PANEL -->
        <div class="details-panel">
          ${this._renderDetails()}
        </div>

        <!-- FOOTER -->
        <div class="footer">
          <button type="button" class="btn btn-primary embark-btn" ?disabled="${!isSquadValid}" @click="${this._handleEmbark}">
            ${this.mode === 'DRAFT' ? 'INITIALIZE SQUAD' : 'EMBARK'}
          </button>
        </div>
      </div>
    `;
  }

  _renderDetails() {
      if (!this.hoveredItem) return html`<p>Hover over a unit to see details.</p>`;
      
      // Handle data structure diffs between ClassDef and UnitInstance
      const name = this.hoveredItem.name;
      const role = this.hoveredItem.role || this.hoveredItem.classId;
      const stats = this.hoveredItem.base_stats || this.hoveredItem.stats || {}; 
      
      return html`
        <h2>${name}</h2>
        <p><em>${role}</em></p>
        <hr>
        <p>${this.hoveredItem.description || 'Ready for deployment.'}</p>
        <h4>Stats</h4>
        <ul>
            <li>HP: ${stats.health}</li>
            <li>Atk: ${stats.attack || 0}</li>
            <li>Spd: ${stats.speed}</li>
        </ul>
      `;
  }

  _selectSlot(index) {
    this.selectedSlotIndex = index;
  }

  _assignItem(item) {
    if (this.mode === 'DRAFT' && !item.unlocked) return;

    let unitManifest;

    if (this.mode === 'DRAFT') {
        // Create new unit definition
        // name will be generated in RosterManager.recruitUnit()
        unitManifest = {
            classId: item.id,
            name: item.name, // This will become className in recruitUnit
            icon: item.icon,
            portrait: item.portrait || item.image, // Support both for backward compatibility
            role: item.role,
            isNew: true // Flag for GameLoop/Manager to generate ID
        };
    } else {
        // Select existing unit
        // Try to recover portrait from CLASS_METADATA if not stored on unit instance
        const meta = CLASS_METADATA[item.classId] || {};
        
        unitManifest = {
            id: item.id,
            classId: item.classId,
            name: item.name, // Character name
            className: item.className, // Class name
            icon: meta.icon,
            portrait: item.portrait || item.image || meta.portrait || meta.image, // Support both for backward compatibility
            role: meta.role,
            ...item
        };
    }

    const newSquad = [...this.squad];
    newSquad[this.selectedSlotIndex] = unitManifest;
    this.squad = newSquad;

    if (this.selectedSlotIndex < 3) this.selectedSlotIndex++;
  }

  _removeUnit(index) {
    const newSquad = [...this.squad];
    newSquad[index] = null;
    this.squad = newSquad;
    this.selectedSlotIndex = index;
  }

  _handleEmbark() {
    const manifest = this.squad.filter(u => u !== null);
    
    this.dispatchEvent(new CustomEvent('embark', {
      detail: { squad: manifest, mode: this.mode },
      bubbles: true,
      composed: true
    }));
  }

  // Helpers to make IDs readable (e.g. "ITEM_RUSTY_BLADE" -> "Rusty Blade")
  _formatItemName(id) {
    return id.replace('ITEM_', '').replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, l => l.toUpperCase());
  }

  _formatSkillName(id) {
    return id.replace('SKILL_', '').replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, l => l.toUpperCase());
  }
}

customElements.define('team-builder', TeamBuilder);