/**
 * Cyber-Assistant - Trial Manager
 * Gere l'etat trial/licence en communiquant avec le serveur.
 * En mode file:// → aucune restriction (licensed: true, trial: false).
 * Si le serveur est injoignable → fallback sans restriction.
 */
(function() {
  'use strict';

  var _state = null;
  var _detected = false;

  var TrialManager = {

    /**
     * Detecte l'etat trial/licence depuis le serveur.
     * Appelé une seule fois au demarrage.
     * @returns {Promise<Object>} etat trial/licence
     */
    detect: function(forceRefresh) {
      // Deja detecte → retourner le resultat mis en cache (sauf si forceRefresh ou serverUnreachable)
      if (_detected && !forceRefresh && !(_state && _state.serverUnreachable)) return Promise.resolve(_state);

      // Détection basée sur edition.js
      var ed = window._csiEdition;

      // Corporate Local : déléguer au LocalTrialManager
      if (ed && ed.id === 'corporate-local') {
        var LTM = window.CSI_LocalTrialManager;
        if (LTM) {
            return LTM.detect().then(function(state) {
                _state = state;
                _detected = true;
                void 0;
                return _state;
            });
        }
      }

      // Community (pas de trial/licence) : aucune restriction
      if (ed && !ed.trial && !ed.license) {
        _state = { licensed: true, trial: false };
        _detected = true;
        void 0;
        return Promise.resolve(_state);
      }

      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) {
          _state = data;
          _detected = true;
          void 0;
          return _state;
        })
        .catch(function(err) {
          _state = {
            licensed: false,
            trial: false,
            serverUnreachable: true,
            trialDaysLeft: 0,
            trialExpired: false
          };
          _detected = true;
          void 0;
          return _state;
        });
    },

    /**
     * Active une licence via cle.
     * @param {string} licenseKey - cle de licence a activer
     * @returns {Promise<Object>} reponse serveur
     */
    activate: function(licenseKey) {
      // Mode Corporate Local : activation locale (pas d'API serveur)
      var ed = window._csiEdition;
      if (ed && ed.id === 'corporate-local') {
        var LTM = window.CSI_LocalTrialManager;
        if (LTM) {
            return LTM.activate(licenseKey).then(function(result) {
                _state = LTM.getState();
                _detected = true;
                return result;
            });
        }
      }

      var headers = {
        'Content-Type': 'application/json'
      };

      var token = null;
      try {
        // Use auth-manager API if available, fallback to sessionStorage key
        if (window.CSI_AuthManager && window.CSI_AuthManager.getToken) {
          token = window.CSI_AuthManager.getToken();
        } else {
          token = sessionStorage.getItem('csi_auth_token');
        }
      } catch (e) {
        // sessionStorage indisponible
      }

      if (token) {
        headers['Authorization'] = 'Bearer ' + token;
      }

      return (window.fetchWithTimeout || fetch)('./data/sync.php?action=license-activate', {
        method: 'POST',
        headers: headers,
        body: JSON.stringify({ licenseKey: licenseKey })
      })
        .then(function(response) {
          var contentType = response.headers.get('content-type') || '';
          if (contentType.indexOf('application/json') === -1) {
            throw new Error('Réponse serveur invalide (non-JSON, HTTP ' + response.status + ')');
          }
          return response.json().then(function(data) {
            if (!response.ok) {
              throw new Error(data.message || data.error || 'Erreur activation (HTTP ' + response.status + ')');
            }
            // Merge activation response into existing state rather than replacing it,
            // since license-activate returns only {ok, organization, expiresAt}
            // but _state needs licensed, trial, trialDaysLeft, etc.
            _state = Object.assign({}, _state || {}, data, {
              licensed: true,
              trial: false,
              trialExpired: false,
              licenseExpired: false
            });
            _detected = true;
            void 0;
            // Re-detect full state from server for consistency
            TrialManager.detect(true);
            return data;
          });
        });
    },

    /**
     * @returns {Object|null} etat trial/licence complet
     */
    getState: function() {
      return _state;
    },

    /**
     * @returns {boolean} true si la detection a deja ete effectuee
     */
    isDetected: function() {
      return _detected;
    },

    /**
     * @returns {boolean} true si le trial est actif et qu'il reste des jours
     */
    isTrialActive: function() {
      return _state !== null && _state.trial === true && _state.trialDaysLeft > 0;
    },

    /**
     * @returns {boolean} true si le trial est expire
     */
    isTrialExpired: function() {
      return _state !== null && _state.trial === true &&
        (_state.trialExpired === true || _state.trialDaysLeft <= 0);
    },

    /**
     * @returns {boolean} true si une licence valide est active
     */
    isLicensed: function() {
      return _state !== null && _state.licensed === true;
    },

    /**
     * @returns {boolean} true si la licence est expiree
     */
    isLicenseExpired: function() {
      return _state !== null && _state.licenseExpired === true;
    },

    /**
     * @returns {number} jours restants du trial (0 si aucun)
     */
    getDaysLeft: function() {
      return (_state && _state.trialDaysLeft) || 0;
    },

    /**
     * @returns {string|null} nom de l'organisation ou null
     */
    getOrganization: function() {
      return (_state && _state.organization) || null;
    },

    /**
     * @returns {boolean} true si l'utilisateur doit entrer une cle de licence
     */
    needsLicense: function() {
      return TrialManager.isTrialExpired() || TrialManager.isLicenseExpired();
    }
  };

  // Enregistrer dans le registre CSI si disponible
  if (window.CSI && window.CSI.register) {
    window.CSI.register('trial-manager', {
      exports: { CSI_TrialManager: TrialManager }
    });
  }

  // Exposer globalement
  window.CSI_TrialManager = TrialManager;

  void 0;
})();
