/**
 * 공유 네비게이션 헤더 + SSO 쿠키 유틸리티
 *
 * 각 시스템 페이지에서 import하여 SSO 인증 유틸 제공
 * <script src="/shared/nav-header.js"></script>
 */
(function() {
  // 쿠키 헬퍼
  function cookieGet(name) {
    var match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
    return match ? decodeURIComponent(match[1]) : null;
  }
  function cookieSet(name, value, days) {
    var cookie = name + '=' + encodeURIComponent(value) + '; path=/';
    if (days) cookie += '; max-age=' + (days * 86400);
    if (window.location.hostname.includes('technicalkorea.net')) {
      cookie += '; domain=.technicalkorea.net; secure; samesite=lax';
    }
    document.cookie = cookie;
  }
  function cookieRemove(name) {
    var cookie = name + '=; path=/; max-age=0';
    if (window.location.hostname.includes('technicalkorea.net')) {
      cookie += '; domain=.technicalkorea.net; secure; samesite=lax';
    }
    document.cookie = cookie;
  }

  /**
   * SSO 인증 유틸리티 (쿠키 + localStorage 이중 지원)
   */
  window.SSOAuth = {
    getToken: function() {
      return cookieGet('sso_token');
    },

    getUser: function() {
      var raw = cookieGet('sso_user');
      try { return JSON.parse(raw); } catch(e) { return null; }
    },

    isLoggedIn: function() {
      var token = this.getToken();
      return !!token && token !== 'undefined' && token !== 'null';
    },

    logout: function() {
      cookieRemove('sso_token');
      cookieRemove('sso_user');
      cookieRemove('sso_refresh_token');
      ['sso_token','sso_user','sso_refresh_token','token','user','access_token','currentUser','current_user','userInfo','userPageAccess'].forEach(function(k) {
        localStorage.removeItem(k);
      });
      window.location.href = this.getLoginUrl(window.location.href) + '&logout=1';
    },

    /**
     * 중앙 로그인 URL 반환
     */
    getLoginUrl: function(redirect) {
      var hostname = window.location.hostname;
      var loginUrl;

      if (hostname.includes('technicalkorea.net')) {
        loginUrl = window.location.protocol + '//tkds.technicalkorea.net/dashboard';
      } else {
        // 개발 환경: tkds 포트 (30780)
        loginUrl = window.location.protocol + '//' + hostname + ':30780/dashboard';
      }

      if (redirect) {
        loginUrl += '?redirect=' + encodeURIComponent(redirect);
      }
      return loginUrl;
    },

    /**
     * 토큰을 Authorization 헤더에 포함한 fetch wrapper
     */
    fetch: function(url, options) {
      options = options || {};
      options.headers = options.headers || {};
      var token = this.getToken();
      if (token) {
        options.headers['Authorization'] = 'Bearer ' + token;
      }
      return fetch(url, options);
    },

    /**
     * 로그인 안 되어있으면 중앙 로그인 페이지로 리다이렉트
     */
    requireLogin: function() {
      if (!this.isLoggedIn()) {
        window.location.href = this.getLoginUrl(window.location.href);
      }
    }
  };
})();
