/**
 * Sincroniza login y logout entre pestañas del mismo origen (Flexia / Antara).
 *
 * - Logout en una pestaña → las demás con sesión redirigen al login.
 * - Login en una pestaña de /login/ → las demás pestañas de login redirigen al escritorio.
 */
(function (global) {
  "use strict";

  var CHANNEL = "antara-auth-sync";
  var STORAGE_KEY = "antara:auth-sync";
  var TAB_ID = "t" + Math.random().toString(36).slice(2) + Date.now().toString(36);
  var applying = false;

  function publish(event, payload) {
    var msg = {
      event: event,
      tabId: TAB_ID,
      ts: Date.now(),
    };
    if (payload) {
      for (var k in payload) {
        if (Object.prototype.hasOwnProperty.call(payload, k)) msg[k] = payload[k];
      }
    }
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(msg));
    } catch (_) {}
    if (typeof global.BroadcastChannel === "function") {
      try {
        var ch = new global.BroadcastChannel(CHANNEL);
        ch.postMessage(msg);
        ch.close();
      } catch (_) {}
    }
  }

  function clearClientAuthHints() {
    try {
      sessionStorage.removeItem("grid_auth_user_json");
      sessionStorage.removeItem("antara_login_username");
    } catch (_) {}
  }

  function appendQuery(url, key, value) {
    if (!url) return url;
    var sep = url.indexOf("?") >= 0 ? "&" : "?";
    return url + sep + encodeURIComponent(key) + "=" + encodeURIComponent(value);
  }

  function defaultLogoutRedirect(loginUrl) {
    clearClientAuthHints();
    var target = loginUrl || "/login/";
    target = appendQuery(target, "reason", "logout");
    applying = true;
    global.location.replace(target);
  }

  function defaultLoginRedirect(nextUrl) {
    var target = nextUrl || "/index.php";
    applying = true;
    global.location.replace(target);
  }

  function handleMessage(msg, cfg) {
    if (!msg || !msg.event || msg.tabId === TAB_ID) return;
    if (applying) return;

    if (msg.event === "logout") {
      if (!cfg.listenLogout) return;
      var onLogout = cfg.onRemoteLogout;
      if (typeof onLogout === "function") {
        applying = true;
        onLogout(msg.loginUrl || cfg.loginUrl || "");
        return;
      }
      defaultLogoutRedirect(msg.loginUrl || cfg.loginUrl || "");
      return;
    }

    if (msg.event === "login") {
      if (!cfg.listenLogin) return;
      if (cfg.reloadOnRemoteLogin) {
        applying = true;
        global.location.reload();
        return;
      }
      var onLogin = cfg.onRemoteLogin;
      if (typeof onLogin === "function") {
        applying = true;
        onLogin(msg.nextUrl || cfg.nextUrl || "");
        return;
      }
      defaultLoginRedirect(msg.nextUrl || cfg.nextUrl || "");
    }
  }

  function bindListeners(cfg) {
    global.addEventListener("storage", function (e) {
      if (e.key !== STORAGE_KEY || !e.newValue) return;
      try {
        handleMessage(JSON.parse(e.newValue), cfg);
      } catch (_) {}
    });

    if (typeof global.BroadcastChannel === "function") {
      try {
        var channel = new global.BroadcastChannel(CHANNEL);
        channel.addEventListener("message", function (ev) {
          handleMessage(ev.data, cfg);
        });
      } catch (_) {}
    }
  }

  /**
   * @param {{ listenLogin?: boolean, listenLogout?: boolean, loginUrl?: string, nextUrl?: string, onRemoteLogin?: function(string), onRemoteLogout?: function(string) }} cfg
   */
  function init(cfg) {
    cfg = cfg || {};
    bindListeners(cfg);
  }

  function notifyLogin(nextUrl) {
    publish("login", { nextUrl: nextUrl || "" });
  }

  function notifyLogout(loginUrl) {
    publish("logout", { loginUrl: loginUrl || "" });
  }

  global.AntaraAuthTabSync = {
    init: init,
    notifyLogin: notifyLogin,
    notifyLogout: notifyLogout,
    clearClientAuthHints: clearClientAuthHints,
  };

  if (global.ANTARA_AUTH_TAB_SYNC_CFG) {
    init(global.ANTARA_AUTH_TAB_SYNC_CFG);
  }
})(typeof window !== "undefined" ? window : this);
