/**
 * Cyber-Assistant - License Manager
 * Auto-détecte config/license.json ou data/license.json sur HTTP(S),
 * valide la signature, et expose l'état du mode serveur.
 * Fournit une modale d'activation pour coller une clé CSI2-...
 * En mode file:// ou sans licence valide → mode local inchangé.
 */
(function() {
  'use strict';

  var _serverMode = false;
  var _license = null;
  var _detected = false;

  /**
   * Tente de charger et valider une licence depuis une URL donnée
   * @param {string} url - URL du fichier licence
   * @returns {Promise<boolean>} true si licence valide
   */
  function tryLoadLicense(url) {
    return (window.fetchWithTimeout || fetch)(url, { cache: 'no-cache' })
      .then(function(response) {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        return response.json();
      })
      .then(function(licenseFile) {
        if (!licenseFile || !licenseFile.license || !licenseFile.signature) {
          throw new Error('Structure de licence invalide');
        }

        var licenseData = licenseFile.license;
        var signature = licenseFile.signature;
        var meta = licenseFile.meta;

        if (typeof window.isLicenseExpired === 'function' && window.isLicenseExpired(licenseData)) {
          void 0;
          _license = licenseData;
          return false;
        }

        if (typeof window.validateLicenseSignature !== 'function') {
          throw new Error('Fonctions crypto non disponibles');
        }

        return window.validateLicenseSignature(licenseData, signature, meta)
          .then(function(isValid) {
            if (isValid) {
              _license = licenseData;
              void 0;
            }
            return isValid;
          });
      });
  }

  /**
   * Fallback: vérifie le mode serveur via l'API license-status.
   * Si le serveur répond avec trial actif ou licence valide → server mode.
   * @returns {Promise<boolean>}
   */
  function _checkLicenseStatusAPI() {
    return (window.fetchWithTimeout || fetch)('./data/sync.php?action=license-status', { cache: 'no-store' })
      .then(function(response) {
        if (!response.ok) throw new Error('HTTP ' + response.status);
        return response.json();
      })
      .then(function(data) {
        var isServer = !!(data.licensed || (data.trial && !data.trialExpired && data.trialDaysLeft > 0));
        _detected = true;
        _serverMode = isServer;
        if (isServer) {
          void 0;
        } else {
          void 0;
        }
        return isServer;
      })
      .catch(function() {
        _detected = true;
        _serverMode = false;
        _license = null;
        void 0;
        return false;
      });
  }

  /**
   * Crée un élément DOM avec attributs et enfants texte
   */
  function el(tag, attrs, textContent) {
    var node = document.createElement(tag);
    if (attrs) Object.keys(attrs).forEach(function(k) {
      if (k === 'className') node.className = attrs[k];
      else if (k === 'style' && typeof attrs[k] === 'string') node.style.cssText = attrs[k];
      else node.setAttribute(k, attrs[k]);
    });
    if (textContent) node.textContent = textContent;
    return node;
  }

  var LicenseManager = {

    detect: function(forceRefresh) {
      if (_detected && !forceRefresh) return Promise.resolve(_serverMode);

      if (window.location.protocol === 'file:') {
        _detected = true;
        _serverMode = false;
        void 0;
        return Promise.resolve(false);
      }

      return tryLoadLicense('./config/license.json')
        .then(function(valid) {
          if (valid) { _detected = true; _serverMode = true; return true; }
          return tryLoadLicense('./data/license.json').then(function(v2) {
            if (v2) { _detected = true; _serverMode = true; return true; }
            return _checkLicenseStatusAPI();
          });
        })
        .catch(function() {
          return tryLoadLicense('./data/license.json').then(function(v2) {
            if (v2) { _detected = true; _serverMode = true; return true; }
            return _checkLicenseStatusAPI();
          }).catch(function() {
            return _checkLicenseStatusAPI();
          });
        });
    },

    isServerMode: function() { return _serverMode; },
    getLicense: function() { return _license; },
    isDetected: function() { return _detected; },

    /**
     * Affiche la modale d'activation de licence
     * @param {Object} [options] - { required, onSuccess, onCancel }
     */
    showActivationModal: function(options) {
      options = options || {};
      var t = window.CSI_i18n ? window.CSI_i18n.t.bind(window.CSI_i18n) : function(k, fb) { return fb || k; };

      var existing = document.getElementById('csiLicenseActivationModal');
      if (existing) existing.remove();

      // Build modal with safe DOM methods
      var overlay = el('div', {
        id: 'csiLicenseActivationModal',
        className: 'csi-modal-overlay',
        style: 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;z-index:99999;'
      });

      var modal = el('div', {
        style: 'background:var(--color-surface,#fff);border-radius:12px;padding:32px;max-width:480px;width:90%;box-shadow:0 8px 32px rgba(0,0,0,0.3);'
      });

      var title = el('h2', { style: 'margin:0 0 8px 0;color:var(--color-text,#333);font-size:1.3rem;' }, t('license.title', 'Activation'));
      var desc = el('p', { style: 'margin:0 0 20px 0;color:var(--color-text-secondary,#666);font-size:0.9rem;' }, t('license.pasteHint', 'Collez la clé CSI2-... reçue par email'));

      var keyInput = el('textarea', {
        id: 'csiLicActivateKey',
        className: 'csi-license-textarea',
        placeholder: 'CSI2-...',
        style: 'width:100%;min-height:100px;padding:12px;border:1px solid var(--color-border,#ddd);border-radius:6px;margin-bottom:16px;font-family:monospace;font-size:0.85rem;resize:vertical;box-sizing:border-box;'
      });

      var msgDiv = el('div', {
        id: 'csiLicActivateMsg',
        style: 'margin-bottom:16px;font-size:0.9rem;display:none;padding:10px;border-radius:6px;'
      });

      var btnRow = el('div', { style: 'display:flex;gap:12px;justify-content:flex-end;' });

      if (!options.required) {
        var cancelBtn = el('button', {
          style: 'padding:10px 20px;border:1px solid var(--color-border,#ddd);background:var(--color-surface,#fff);border-radius:6px;cursor:pointer;font-size:0.95rem;'
        }, t('license.continueTrial', 'Continuer l\'essai'));
        cancelBtn.addEventListener('click', function() {
          overlay.remove();
          if (options.onCancel) options.onCancel();
        });
        btnRow.appendChild(cancelBtn);
      }

      var activateBtn = el('button', {
        style: 'padding:10px 20px;border:none;background:var(--color-primary,#3b82f6);color:white;border-radius:6px;cursor:pointer;font-size:0.95rem;font-weight:500;'
      }, t('license.activate', 'Activer la licence'));

      function showMsg(text, type) {
        msgDiv.style.display = 'block';
        msgDiv.textContent = text;
        msgDiv.style.background = type === 'error' ? 'var(--color-danger-bg,#fef2f2)' : 'var(--color-success-bg,#f0fdf4)';
        msgDiv.style.color = type === 'error' ? 'var(--color-danger,#dc3545)' : 'var(--color-success,#22c55e)';
      }

      activateBtn.addEventListener('click', function() {
        var key = (keyInput.value || '').trim();
        if (!key || key.indexOf('CSI2-') !== 0) {
          showMsg(t('license.error', 'Clé de licence invalide'), 'error');
          return;
        }
        activateBtn.disabled = true;
        activateBtn.textContent = '...';
        msgDiv.style.display = 'none';

        var TM = window.CSI_TrialManager;
        if (TM) {
          TM.activate(key).then(function(result) {
            showMsg(t('license.success', 'Licence activée avec succès') + (result.organization ? ' — ' + result.organization : ''), 'success');
            _serverMode = true;
            _license = result;
            setTimeout(function() {
              overlay.remove();
              if (options.onSuccess) options.onSuccess(result);
              else location.reload();
            }, 1500);
          }).catch(function(err) {
            activateBtn.disabled = false;
            activateBtn.textContent = t('license.activate', 'Activer la licence');
            showMsg(err.message || t('license.error', 'Clé de licence invalide'), 'error');
          });
        } else {
          activateBtn.disabled = false;
          activateBtn.textContent = t('license.activate', 'Activer la licence');
          showMsg('TrialManager non disponible', 'error');
        }
      });

      btnRow.appendChild(activateBtn);
      modal.appendChild(title);
      modal.appendChild(desc);
      modal.appendChild(keyInput);
      modal.appendChild(msgDiv);
      modal.appendChild(btnRow);
      overlay.appendChild(modal);
      document.body.appendChild(overlay);

      setTimeout(function() { keyInput.focus(); }, 100);
    }
  };

  if (window.CSI && window.CSI.register) {
    window.CSI.register('license-manager', {
      exports: { CSI_LicenseManager: LicenseManager }
    });
  }

  window.CSI_LicenseManager = LicenseManager;
  void 0;
})();
