/**
 * Cyber-Assistant - Server setup assistant (v3 — JWT multi-user)
 *
 * Auto-detects mode via CSI_LicenseManager:
 * - License detected (valid config/license.json) → server mode auto-enabled
 * - No license or file:// → local mode (unchanged)
 *
 * In server mode: delegates authentication to CSI_AuthManager (JWT login).
 * Phase 1 (single shared password) has been removed.
 *
 * Depends on: modules/storage.js, modules/license-manager.js, modules/auth-manager.js
 */
(function() {
  'use strict';

  var Storage = window.CSI_Storage;
  if (!Storage) {
    void 0;
    return;
  }

  var SYNC_URL = './data/sync.php';

  async function checkSyncEndpoint() {
    try {
      var response = await (window.fetchWithTimeout || fetch)(SYNC_URL + '?action=status', {
        method: 'GET',
        cache: 'no-store'
      });
      if (!response.ok) return null;
      return await response.json();
    } catch (e) {
      return null;
    }
  }

  // ============================================================
  // Entry point (v3: JWT multi-user via AuthManager)
  // ============================================================

  async function init() {
    var LM = window.CSI_LicenseManager;
    var TM = window.CSI_TrialManager;

    if (!LM) {
      void 0;
      return;
    }

    var hasLicense = await LM.detect();

    if (TM) {
      await TM.detect();
      void 0;
    }

    if (!hasLicense) {
      if (TM && TM.isLicensed()) {
        void 0;
        Storage.markSetupCompleted('server');
      } else {
        if (!Storage.isSetupCompleted() && Storage.hasUserData()) {
          Storage.markSetupCompleted('local');
        }
        void 0;
        return;
      }
    } else {
      void 0;
      Storage.markSetupCompleted('server');
    }

    // Check sync endpoint availability
    var syncStatus = await checkSyncEndpoint();
    if (!syncStatus) {
      void 0;
      return;
    }

    // JWT auth: check if user is already logged in
    var AuthManager = window.CSI_AuthManager;
    if (AuthManager && AuthManager.isLoggedIn()) {
      void 0;
      return;
    }

    // No active JWT session — login will be handled by bundle.js login wall
    void 0;
  }

  setTimeout(init, 300);

  window.CSI_ServerSetup = {
    init: init,
    getMode: function() {
      return Storage.getDeploymentMode();
    }
  };

  void 0;

})();
