/**
 * ComparisonMode - Gestionnaire du mode comparaison
 * 
 * Responsabilités:
 * - Afficher les codes proposés et corrigés côte à côte
 * - Colorer les différences (rouge) et identiques (vert)
 * - Afficher les commentaires de correction
 * - Gérer l'activation/désactivation du mode
 * 
 * Validates: Requirements 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7
 */
class ComparisonMode {
  constructor(stateManager) {
    this.stateManager = stateManager;
    this.isActive = false;
    this.previousState = null;
    
    // S'abonner aux changements d'état
    this.stateManager.on('comparisonModeChanged', (enabled) => {
      this.isActive = enabled;
      this.render();
    });
  }

  /**
   * Activer le mode comparaison
   * Validates: Requirements 9.1
   */
  activate() {
    // Sauvegarder l'état actuel pour le rollback
    this.previousState = {
      selectedCode: this.stateManager.getSelectedCode(),
      activeDocument: this.stateManager.getActiveDocument()
    };
    
    this.stateManager.setComparisonMode(true);
  }

  /**
   * Désactiver le mode comparaison
   * Validates: Requirements 9.7
   */
  deactivate() {
    this.stateManager.setComparisonMode(false);
    
    // Restaurer l'état précédent
    if (this.previousState) {
      if (this.previousState.selectedCode) {
        this.stateManager.setSelectedCode(this.previousState.selectedCode);
      }
      if (this.previousState.activeDocument) {
        this.stateManager.setActiveDocument(this.previousState.activeDocument);
      }
      this.previousState = null;
    }
  }

  /**
   * Basculer le mode comparaison
   */
  toggle() {
    if (this.isActive) {
      this.deactivate();
    } else {
      this.activate();
    }
  }

  /**
   * Rendre le mode comparaison
   */
  render() {
    const stay = this.stateManager.getCurrentStay();
    if (!stay) return;
    
    const container = document.getElementById('comparison-container');
    if (!container) {
      // Créer le container s'il n'existe pas
      this.createComparisonContainer();
      return this.render();
    }
    
    if (!this.isActive) {
      container.style.display = 'none';
      return;
    }
    
    // Vérifier s'il y a des corrections
    const corrections = stay.corrections || [];
    
    if (corrections.length === 0) {
      this.renderNoCorrections(container);
      return;
    }
    
    this.renderComparison(container, stay, corrections);
    container.style.display = 'block';
  }

  /**
   * Créer le container de comparaison
   */
  createComparisonContainer() {
    const mainLayout = document.getElementById('main-layout');
    if (!mainLayout) return;
    
    const container = document.createElement('div');
    container.id = 'comparison-container';
    container.className = 'comparison-overlay';
    container.style.display = 'none';
    
    mainLayout.parentNode.insertBefore(container, mainLayout);
  }

  /**
   * Rendre le message "aucune correction"
   * Validates: Requirements 9.6
   */
  renderNoCorrections(container) {
    container.innerHTML = `
      <div class="comparison-content">
        <div class="comparison-header">
          <h2>Mode Comparaison</h2>
          <button class="btn btn-secondary" onclick="window.comparisonMode.deactivate()">
            ✕ Fermer
          </button>
        </div>
        <div class="no-corrections">
          <div class="empty-icon">📋</div>
          <h3>Aucune correction disponible</h3>
          <p>Ce séjour n'a pas encore été corrigé.</p>
        </div>
      </div>
    `;
  }

  /**
   * Rendre la comparaison
   * Validates: Requirements 9.2, 9.3, 9.4, 9.5
   */
  renderComparison(container, stay, corrections) {
    let html = `
      <div class="comparison-content">
        <div class="comparison-header">
          <h2>Mode Comparaison - Codes Proposés vs Corrigés</h2>
          <button class="btn btn-secondary" onclick="window.comparisonMode.deactivate()">
            ✕ Fermer
          </button>
        </div>
        <div class="comparison-grid">
    `;
    
    // Comparer DP
    if (stay.codes.dp) {
      html += this.renderCodeComparison('DP', stay.codes.dp, corrections);
    }
    
    // Comparer DR
    if (stay.codes.dr) {
      html += this.renderCodeComparison('DR', stay.codes.dr, corrections);
    }
    
    // Comparer DAS
    if (stay.codes.das && stay.codes.das.length > 0) {
      stay.codes.das.forEach((code, index) => {
        html += this.renderCodeComparison(`DAS ${index + 1}`, code, corrections);
      });
    }
    
    // Comparer CCAM
    if (stay.codes.ccam && stay.codes.ccam.length > 0) {
      stay.codes.ccam.forEach((code, index) => {
        html += this.renderCodeComparison(`CCAM ${index + 1}`, code, corrections);
      });
    }
    
    html += `
        </div>
      </div>
    `;
    
    container.innerHTML = html;
  }

  /**
   * Rendre la comparaison d'un code
   */
  renderCodeComparison(title, proposedCode, corrections) {
    // Trouver la correction pour ce code
    const correction = corrections.find(c => c.original_code === proposedCode.code);
    
    const isDifferent = correction && correction.corrected_code !== proposedCode.code;
    const statusClass = isDifferent ? 'different' : 'identical';
    const statusColor = isDifferent ? '#f56565' : '#48bb78';
    const statusLabel = isDifferent ? 'Modifié' : 'Identique';
    
    return `
      <div class="comparison-item ${statusClass}">
        <div class="comparison-item-header">
          <h4>${title}</h4>
          <span class="comparison-status" style="background: ${statusColor};">
            ${statusLabel}
          </span>
        </div>
        
        <div class="comparison-columns">
          <div class="comparison-column">
            <div class="column-label">Code Proposé</div>
            <div class="code-box proposed">
              <div class="code-value">${proposedCode.code}</div>
              <div class="code-label">${proposedCode.label}</div>
              <div class="code-confidence">
                Confiance: ${Math.round(proposedCode.confidence * 100)}%
              </div>
            </div>
          </div>
          
          <div class="comparison-arrow">→</div>
          
          <div class="comparison-column">
            <div class="column-label">Code Corrigé</div>
            ${correction ? `
              <div class="code-box corrected">
                <div class="code-value">${correction.corrected_code}</div>
                <div class="code-label">${correction.corrected_label || 'N/A'}</div>
                ${correction.comment ? `
                  <div class="correction-comment">
                    💬 ${this.escapeHTML(correction.comment)}
                  </div>
                ` : ''}
              </div>
            ` : `
              <div class="code-box no-correction">
                <div class="code-value">${proposedCode.code}</div>
                <div class="code-label">Aucune correction</div>
              </div>
            `}
          </div>
        </div>
      </div>
    `;
  }

  /**
   * Échapper le HTML
   */
  escapeHTML(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

// Export pour utilisation dans d'autres modules
if (typeof module !== 'undefined' && module.exports) {
  module.exports = ComparisonMode;
}
