// ============================================
// SYSTÈME DE GESTION DE LICENCE FICHIER .LIC
// ============================================

const LICENSE_FILE_KEY = 'git_pusher_license_file';
const LICENSE_STATUS_ENDPOINT = '/custom/git_pusher/license_status';

let currentLicenseStatus = null;

function initializeLicenseSystem() {
  console.log("Initializing file-based license system...");
  
  // Vérifier le statut de la licence
  checkLicenseStatus();
}

function checkLicenseStatus() {
  console.log("Checking license status...");
  
  // Appeler le backend pour vérifier la licence
  fetch(LICENSE_STATUS_ENDPOINT)
    .then(response => response.json())
    .then(data => {
      console.log("License status:", data);
      currentLicenseStatus = data;
      
      if (data.licensed) {
        // Licence valide
        displayLicenseBadge(data.license_info, data.warnings);
      } else {
        // Pas de licence ou invalide
        showLicenseUploadModal(data.errors);
      }
    })
    .catch(error => {
      console.error("Error checking license:", error);
      // En cas d'erreur, afficher le modal
      showLicenseUploadModal(["Impossible de vérifier la licence"]);
    });
}

function displayLicenseBadge(licenseInfo, warnings) {
  console.log("Displaying license badge...");
  
  const container = document.getElementById('license-badge-container');
  if (!container) {
    console.error("license-badge-container not found");
    return;
  }
  
  // Créer le badge
  const badge = document.createElement('div');
  badge.id = 'license-badge';
  badge.style.cssText = `
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 12px 20px;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 600;
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    cursor: pointer;
    transition: all 0.3s ease;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    text-align: center;
    min-width: 200px;
  `;
  
  // Déterminer le texte et la couleur selon le type
  let badgeText = '✓ Licence Activée';
  let badgeColor = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
  
  if (licenseInfo.type === 'trial') {
    badgeText = `⏱️ Essai: ${licenseInfo.days_remaining} jours`;
    badgeColor = 'linear-gradient(135deg, #ff9800 0%, #f57c00 100%)';
  } else if (licenseInfo.type === 'standard') {
    badgeText = `✓ Standard (${licenseInfo.days_remaining}j)`;
  } else if (licenseInfo.type === 'enterprise') {
    badgeText = `✓ Enterprise (${licenseInfo.days_remaining}j)`;
    badgeColor = 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)';
  }
  
  // Avertissement si expire bientôt
  if (licenseInfo.days_remaining < 30) {
    badgeColor = 'linear-gradient(135deg, #ff9800 0%, #f57c00 100%)';
    badgeText = `⚠️ Expire dans ${licenseInfo.days_remaining}j`;
  }
  
  badge.style.background = badgeColor;
  badge.textContent = badgeText;
  
  // Clic pour afficher les détails
  badge.onclick = function() {
    showLicenseDetailsModal(licenseInfo, warnings);
  };
  
  container.appendChild(badge);
  
  // Hover effect
  badge.addEventListener('mouseenter', function() {
    this.style.transform = 'translateY(-3px)';
    this.style.boxShadow = '0 6px 25px rgba(102, 126, 234, 0.5)';
  });
  
  badge.addEventListener('mouseleave', function() {
    this.style.transform = 'translateY(0)';
    this.style.boxShadow = '0 4px 15px rgba(102, 126, 234, 0.3)';
  });
}

function showLicenseUploadModal(errors = []) {
  console.log("Showing license upload modal");
  
  // Créer le modal
  const modal = document.createElement('div');
  modal.id = 'license-modal';
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  `;
  
  const content = document.createElement('div');
  content.style.cssText = `
    background: white;
    border-radius: 16px;
    padding: 40px;
    max-width: 550px;
    width: 90%;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
    animation: slideIn 0.3s ease;
  `;
  
  let errorsHtml = '';
  if (errors.length > 0) {
    errorsHtml = `
      <div style="background: #fff3cd; padding: 15px; border-radius: 8px; margin-bottom: 25px; border-left: 4px solid #ff9800;">
        <p style="margin: 0; color: #856404; font-weight: 500; font-size: 13px;">
          ⚠️ <strong>Problèmes détectés:</strong>
        </p>
        <ul style="margin: 10px 0 0 20px; color: #856404; font-size: 12px;">
          ${errors.map(e => `<li>${e}</li>`).join('')}
        </ul>
      </div>
    `;
  }
  
  content.innerHTML = `
    <div style="text-align: center; margin-bottom: 30px;">
      <h1 style="font-size: 32px; margin: 0 0 10px 0; color: #333;">🔐 Git Pusher</h1>
      <p style="color: #666; margin: 0; font-size: 14px;">Activation de licence requise</p>
    </div>
    
    ${errorsHtml}
    
    <div style="background: #f5f7ff; padding: 15px; border-radius: 8px; margin-bottom: 25px; border-left: 4px solid #667eea;">
      <p style="margin: 0; color: #667eea; font-weight: 500; font-size: 13px;">
        📋 <strong>Hostname détecté:</strong> <span id="detected-hostname">Chargement...</span>
      </p>
    </div>
    
    <div style="margin-bottom: 25px;">
      <label style="display: block; font-weight: 600; color: #333; margin-bottom: 12px; font-size: 14px;">
        📂 Choisissez votre fichier de licence (.lic)
      </label>
      
      <div id="drop-zone" style="
        border: 3px dashed #667eea;
        border-radius: 12px;
        padding: 40px 20px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #f8f9ff;
      ">
        <div style="font-size: 48px; margin-bottom: 15px;">📄</div>
        <p style="margin: 0 0 10px 0; font-weight: 600; color: #333;">
          Glissez votre fichier .lic ici
        </p>
        <p style="margin: 0; color: #999; font-size: 13px;">
          ou cliquez pour parcourir
        </p>
        <input type="file" id="license-file-input" accept=".lic" style="display: none;">
      </div>
      
      <div id="file-info" style="display: none; margin-top: 15px; padding: 12px; background: #e8f5e9; border-radius: 8px; border-left: 4px solid #4caf50;">
        <p style="margin: 0; color: #2e7d32; font-size: 13px;">
          ✓ <strong id="file-name"></strong> (<span id="file-size"></span>)
        </p>
      </div>
      
      <small style="color: #999; display: block; margin-top: 12px; font-size: 12px;">
        💡 Vous n'avez pas de licence? Contactez-nous pour obtenir votre fichier .lic personnalisé
      </small>
    </div>
    
    <div id="license-message" style="display: none; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 14px;"></div>
    
    <div style="display: flex; gap: 10px;">
      <button id="upload-btn" onclick="uploadLicenseFile()" disabled style="
        flex: 1;
        padding: 14px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        cursor: not-allowed;
        font-size: 14px;
        transition: all 0.3s ease;
        opacity: 0.5;
      ">📤 Installer la licence</button>
      
      <button onclick="requestTrial()" style="
        padding: 14px 20px;
        background: #f5f7ff;
        color: #667eea;
        border: 2px solid #667eea;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
      ">⏱️ Essai gratuit</button>
    </div>
  `;
  
  modal.appendChild(content);
  document.body.appendChild(modal);
  
  // Ajouter l'animation CSS
  const style = document.createElement('style');
  style.textContent = `
    @keyframes slideIn {
      from {
        opacity: 0;
        transform: translateY(-20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
  `;
  document.head.appendChild(style);
  
  // Récupérer et afficher le hostname
  getHostname().then(hostname => {
    document.getElementById('detected-hostname').textContent = hostname;
  });
  
  // Configurer le drag & drop et file input
  setupFileUpload();
}

function setupFileUpload() {
  const dropZone = document.getElementById('drop-zone');
  const fileInput = document.getElementById('license-file-input');
  const fileInfo = document.getElementById('file-info');
  const uploadBtn = document.getElementById('upload-btn');
  
  let selectedFile = null;
  
  // Clic sur la zone pour ouvrir le sélecteur
  dropZone.onclick = () => fileInput.click();
  
  // Hover effect
  dropZone.addEventListener('mouseenter', function() {
    this.style.background = '#eef1ff';
    this.style.borderColor = '#5568d3';
  });
  
  dropZone.addEventListener('mouseleave', function() {
    this.style.background = '#f8f9ff';
    this.style.borderColor = '#667eea';
  });
  
  // Drag & drop
  dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.style.background = '#e3e7ff';
    dropZone.style.borderColor = '#5568d3';
  });
  
  dropZone.addEventListener('dragleave', () => {
    dropZone.style.background = '#f8f9ff';
    dropZone.style.borderColor = '#667eea';
  });
  
  dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.style.background = '#f8f9ff';
    dropZone.style.borderColor = '#667eea';
    
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileSelection(files[0]);
    }
  });
  
  // Sélection de fichier
  fileInput.addEventListener('change', (e) => {
    if (e.target.files.length > 0) {
      handleFileSelection(e.target.files[0]);
    }
  });
  
  function handleFileSelection(file) {
    selectedFile = file;
    
    // Vérifier l'extension
    if (!file.name.endsWith('.lic')) {
      showLicenseMessage('⚠️ Veuillez sélectionner un fichier .lic', 'warning');
      return;
    }
    
    // Afficher les infos du fichier
    document.getElementById('file-name').textContent = file.name;
    document.getElementById('file-size').textContent = formatFileSize(file.size);
    fileInfo.style.display = 'block';
    
    // Activer le bouton
    uploadBtn.disabled = false;
    uploadBtn.style.cursor = 'pointer';
    uploadBtn.style.opacity = '1';
    
    // Stocker le fichier pour l'upload
    window.selectedLicenseFile = file;
    
    showLicenseMessage('✓ Fichier prêt à être installé', 'success');
  }
}

function formatFileSize(bytes) {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}

function uploadLicenseFile() {
  const file = window.selectedLicenseFile;
  
  if (!file) {
    showLicenseMessage('❌ Aucun fichier sélectionné', 'error');
    return;
  }
  
  showLicenseMessage('⏳ Installation de la licence...', 'info');
  
  // Lire le fichier
  const reader = new FileReader();
  
  reader.onload = function(e) {
    const fileContent = e.target.result;
    
    // Envoyer au backend pour validation et installation
    fetch('/custom/git_pusher/install_license', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        license_file: fileContent,
        filename: file.name
      })
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        showLicenseMessage('✅ Licence installée avec succès !', 'success');
        
        setTimeout(() => {
          closeLicenseModal();
          // Recharger pour afficher le badge
          checkLicenseStatus();
        }, 1500);
      } else {
        showLicenseMessage('❌ ' + (data.message || 'Erreur d\'installation'), 'error');
        
        if (data.errors && data.errors.length > 0) {
          const errorList = data.errors.map(e => `• ${e}`).join('\n');
          console.error('License errors:', errorList);
        }
      }
    })
    .catch(error => {
      console.error('Upload error:', error);
      showLicenseMessage('❌ Erreur de connexion au serveur', 'error');
    });
  };
  
  reader.onerror = function() {
    showLicenseMessage('❌ Erreur de lecture du fichier', 'error');
  };
  
  reader.readAsText(file);
}

function requestTrial() {
  showLicenseMessage('⏳ Demande d\'essai en cours...', 'info');
  
  // Appeler le backend pour créer une licence d'essai
  fetch('/custom/git_pusher/request_trial', {
    method: 'POST'
  })
  .then(response => response.json())
  .then(data => {
    if (data.success) {
      showLicenseMessage('✅ Licence d\'essai activée (7 jours) !', 'success');
      
      setTimeout(() => {
        closeLicenseModal();
        checkLicenseStatus();
      }, 1500);
    } else {
      showLicenseMessage('❌ ' + (data.message || 'Erreur'), 'error');
    }
  })
  .catch(error => {
    console.error('Trial request error:', error);
    showLicenseMessage('❌ Erreur de connexion', 'error');
  });
}

function showLicenseDetailsModal(licenseInfo, warnings) {
  // Créer un modal pour afficher les détails de la licence
  const modal = document.createElement('div');
  modal.id = 'license-details-modal';
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10001;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  `;
  
  const content = document.createElement('div');
  content.style.cssText = `
    background: white;
    border-radius: 16px;
    padding: 40px;
    max-width: 500px;
    width: 90%;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
  `;
  
  let warningsHtml = '';
  if (warnings && warnings.length > 0) {
    warningsHtml = `
      <div style="background: #fff3cd; padding: 12px; border-radius: 8px; margin-top: 20px; border-left: 4px solid #ff9800;">
        ${warnings.map(w => `<p style="margin: 5px 0; color: #856404; font-size: 13px;">${w}</p>`).join('')}
      </div>
    `;
  }
  
  const featuresHtml = Object.entries(licenseInfo.features || {})
    .map(([feature, enabled]) => {
      const icon = enabled ? '✅' : '❌';
      return `<div style="padding: 8px 0;"><span style="font-size: 14px;">${icon} ${feature}</span></div>`;
    }).join('');
  
  content.innerHTML = `
    <div style="text-align: center; margin-bottom: 25px;">
      <h2 style="font-size: 24px; margin: 0 0 5px 0; color: #333;">🔐 Informations de licence</h2>
    </div>
    
    <div style="background: #f5f7ff; padding: 20px; border-radius: 12px; margin-bottom: 20px;">
      <div style="margin-bottom: 15px;">
        <strong style="color: #667eea;">🆔 ID de licence:</strong>
        <div style="font-family: monospace; font-size: 12px; margin-top: 5px; color: #555;">${licenseInfo.license_id}</div>
      </div>
      
      <div style="margin-bottom: 15px;">
        <strong style="color: #667eea;">👤 Client:</strong>
        <div style="margin-top: 5px; color: #555;">${licenseInfo.customer}</div>
      </div>
      
      <div style="margin-bottom: 15px;">
        <strong style="color: #667eea;">🏷️ Type:</strong>
        <div style="margin-top: 5px; color: #555;">${licenseInfo.type.toUpperCase()}</div>
      </div>
      
      <div style="margin-bottom: 15px;">
        <strong style="color: #667eea;">📅 Expire le:</strong>
        <div style="margin-top: 5px; color: #555;">${new Date(licenseInfo.expires).toLocaleDateString('fr-FR')}</div>
      </div>
      
      <div>
        <strong style="color: #667eea;">⏰ Jours restants:</strong>
        <div style="margin-top: 5px; color: #555; font-size: 18px; font-weight: 600;">${licenseInfo.days_remaining} jours</div>
      </div>
    </div>
    
    <div style="margin-bottom: 20px;">
      <strong style="color: #333; display: block; margin-bottom: 10px;">✨ Fonctionnalités:</strong>
      <div style="background: #f9f9f9; padding: 15px; border-radius: 8px;">
        ${featuresHtml}
      </div>
    </div>
    
    ${warningsHtml}
    
    <div style="display: flex; gap: 10px; margin-top: 25px;">
      <button onclick="showLicenseUploadModal([])" style="
        flex: 1;
        padding: 12px;
        background: #667eea;
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        font-size: 14px;
      ">🔄 Changer de licence</button>
      
      <button onclick="closeDetailsModal()" style="
        flex: 1;
        padding: 12px;
        background: #f5f7ff;
        color: #667eea;
        border: 2px solid #667eea;
        border-radius: 8px;
        font-weight: 600;
        cursor: pointer;
        font-size: 14px;
      ">Fermer</button>
    </div>
  `;
  
  modal.appendChild(content);
  document.body.appendChild(modal);
}

function closeDetailsModal() {
  const modal = document.getElementById('license-details-modal');
  if (modal) {
    modal.remove();
  }
}

function showLicenseMessage(message, type) {
  const messageEl = document.getElementById('license-message');
  if (!messageEl) return;
  
  messageEl.style.display = 'block';
  messageEl.textContent = message;
  
  if (type === 'success') {
    messageEl.style.background = '#d4edda';
    messageEl.style.color = '#155724';
    messageEl.style.border = '1px solid #c3e6cb';
  } else if (type === 'error') {
    messageEl.style.background = '#f8d7da';
    messageEl.style.color = '#721c24';
    messageEl.style.border = '1px solid #f5c6cb';
  } else if (type === 'warning') {
    messageEl.style.background = '#fff3cd';
    messageEl.style.color = '#856404';
    messageEl.style.border = '1px solid #ffeaa7';
  } else if (type === 'info') {
    messageEl.style.background = '#d1ecf1';
    messageEl.style.color = '#0c5460';
    messageEl.style.border = '1px solid #bee5eb';
  }
}

function closeLicenseModal() {
  const modal = document.getElementById('license-modal');
  if (modal) {
    modal.remove();
  }
}

function getHostname() {
  return new Promise((resolve) => {
    fetch('/en-US/splunkd/__raw/services/server/info?output_mode=json')
      .then(r => r.json())
      .then(d => {
        const hostname = d.entry?.[0]?.content?.host || 'unknown';
        resolve(hostname);
      })
      .catch(() => resolve('unknown'));
  });
}

function checkLicenseBeforePush() {
  if (!currentLicenseStatus || !currentLicenseStatus.licensed) {
    alert('⚠️ Aucune licence valide détectée. Veuillez installer une licence.');
    showLicenseUploadModal([]);
    return false;
  }
  
  return true;
}

// Initialiser au chargement de la page
document.addEventListener('DOMContentLoaded', function() {
  initializeLicenseSystem();
});
