/**
 * Actualiza avatares de perfil en el DOM y sincroniza entre pestañas (admin ↔ escritorio).
 */
(function (global) {
  "use strict";

  var STORAGE_PREFIX = "antara:profile:";

  function resolveSrc(rel, base) {
    if (!rel) return "";
    base = base || "";
    if (/^https?:\/\//i.test(rel)) return rel;
    if (rel.charAt(0) === "/") return base + rel;
    return base + "/" + rel.replace(/^\//, "");
  }

  function mediaKindFromRel(rel) {
    if (!rel) return null;
    var path = (rel.split("?")[0] || "").toLowerCase();
    if (/\.gif$/i.test(path)) return "gif";
    if (/\.(mp4|webm|ogg)$/i.test(path)) return "video";
    if (/\.(png|jpe?g|webp)$/i.test(path)) return "image";
    return "image";
  }

  function mediaKindFromFile(file) {
    if (!file) return "image";
    var t = (file.type || "").toLowerCase();
    if (t.indexOf("video/") === 0) return "video";
    if (t === "image/gif") return "gif";
    var n = (file.name || "").toLowerCase();
    if (/\.(mp4|webm|ogg)$/.test(n)) return "video";
    if (n.endsWith(".gif")) return "gif";
    return "image";
  }

  function cacheBust(url) {
    if (!url) return "";
    if (url.indexOf("blob:") === 0) return url;
    return url + (url.indexOf("?") >= 0 ? "&" : "?") + "v=" + Date.now();
  }

  function readStored(userId) {
    try {
      var raw = localStorage.getItem(STORAGE_PREFIX + userId);
      if (!raw) return null;
      return JSON.parse(raw);
    } catch (_) {
      return null;
    }
  }

  function publish(userId, rel, options) {
    if (!userId) return;
    options = options || {};
    try {
      localStorage.setItem(
        STORAGE_PREFIX + userId,
        JSON.stringify({
          userId: userId,
          rel: rel || "",
          initial: options.initial || "?",
          projectBase: options.projectBase || "",
          mediaFrame: options.mediaFrame || null,
          ts: Date.now(),
        })
      );
    } catch (_) {}
    if (typeof global.BroadcastChannel === "function") {
      try {
        var ch = new global.BroadcastChannel("antara-profile-image");
        ch.postMessage({
          userId: userId,
          rel: rel || "",
          initial: options.initial || "?",
          projectBase: options.projectBase || "",
          mediaFrame: options.mediaFrame || null,
        });
        ch.close();
      } catch (_) {}
    }
  }

  function clearMediaFrameStyles(el) {
    if (!el) return;
    el.style.position = "";
    el.style.left = "";
    el.style.top = "";
    el.style.width = "";
    el.style.height = "";
    el.style.maxWidth = "";
  }

  function applyMediaFrame(el, wrap, frame) {
    if (!el || !wrap || !frame) {
      clearMediaFrameStyles(el);
      return;
    }
    var WAC = global.AntaraAvatarSquareCrop;
    if (!WAC || typeof WAC.applyLayoutMedia !== "function") {
      clearMediaFrameStyles(el);
      return;
    }
    var V = wrap.clientWidth || wrap.offsetWidth || 0;
    if (V <= 0) {
      clearMediaFrameStyles(el);
      return;
    }
    var editorV = frame.editorViewport > 0 ? frame.editorViewport : 300;
    var scale = V / editorV;
    var panX = (frame.panX || 0) * scale;
    var panY = (frame.panY || 0) * scale;
    var fakeVp = { clientWidth: V };
    WAC.applyLayoutMedia(el, fakeVp, frame.zoomPct || 100, panX, panY);
  }

  function primeMediaElForWrap(el) {
    if (!el) return;
    el.style.position = "absolute";
    el.style.inset = "0";
    el.style.width = "100%";
    el.style.height = "100%";
    el.style.maxWidth = "none";
    el.style.objectFit = "cover";
  }

  function ensureVideoEl(wrap, img) {
    var video = wrap.querySelector("[data-antara-profile-video]");
    if (!video) {
      video = document.createElement("video");
      video.setAttribute("data-antara-profile-video", "");
      video.muted = true;
      video.playsInline = true;
      video.loop = true;
      video.autoplay = true;
      video.className = img ? img.className : "";
      if (img && img.parentNode) {
        img.parentNode.insertBefore(video, img);
      } else {
        wrap.appendChild(video);
      }
    }
    return video;
  }

  function hideAllMedia(wrap, img, ph, video) {
    if (img) {
      img.hidden = true;
      img.setAttribute("aria-hidden", "true");
      img.removeAttribute("src");
      img.onerror = null;
      clearMediaFrameStyles(img);
    }
    if (video) {
      video.hidden = true;
      video.setAttribute("aria-hidden", "true");
      try { video.pause(); } catch (_) {}
      video.removeAttribute("src");
      clearMediaFrameStyles(video);
    }
    if (ph) {
      ph.hidden = false;
      ph.removeAttribute("aria-hidden");
    }
  }

  /**
   * Aplica avatar (imagen, GIF o vídeo) a un único contenedor.
   * @param {HTMLElement} wrap
   * @param {{ src?: string, kind?: string|null, mediaFrame?: object|null, initial?: string, noCacheBust?: boolean }} [opts]
   */
  function applyToWrap(wrap, opts) {
    opts = opts || {};
    if (!wrap) return;
    var img = wrap.querySelector("[data-antara-profile-img]");
    var ph = wrap.querySelector("[data-antara-profile-ph]");
    if (!ph) return;

    var initial = (opts.initial && String(opts.initial).charAt(0)) || "?";
    initial = initial.toUpperCase();
    ph.textContent = initial;

    var src = opts.src || "";
    if (src && !opts.noCacheBust && src.indexOf("blob:") !== 0) {
      src = cacheBust(src);
    }
    var kind = opts.kind || (src ? mediaKindFromRel(src) : null);
    var frame = opts.mediaFrame || null;
    var video = wrap.querySelector("[data-antara-profile-video]");

    if (src && kind === "video") {
      video = ensureVideoEl(wrap, img);
      if (img) {
        img.hidden = true;
        img.setAttribute("aria-hidden", "true");
        img.removeAttribute("src");
        img.onerror = null;
        clearMediaFrameStyles(img);
      }
      primeMediaElForWrap(video);
      video.onerror = function () {
        hideAllMedia(wrap, img, ph, video);
      };
      video.src = src;
      video.hidden = false;
      video.removeAttribute("aria-hidden");
      ph.hidden = true;
      ph.setAttribute("aria-hidden", "true");
      if (frame) {
        applyMediaFrame(video, wrap, frame);
      } else {
        clearMediaFrameStyles(video);
        primeMediaElForWrap(video);
      }
      try { video.load(); } catch (_) {}
      void video.play().catch(function () {});
      return;
    }

    if (video) {
      video.hidden = true;
      video.setAttribute("aria-hidden", "true");
      try { video.pause(); } catch (_) {}
      video.removeAttribute("src");
      clearMediaFrameStyles(video);
    }

    if (!img) {
      if (!src) {
        hideAllMedia(wrap, img, ph, video);
      }
      return;
    }

    if (src) {
      img.onerror = function () {
        img.hidden = true;
        ph.hidden = false;
        img.removeAttribute("src");
        clearMediaFrameStyles(img);
      };
      if (img.src === src) {
        img.removeAttribute("src");
      }
      img.src = src;
      img.hidden = false;
      ph.hidden = true;
      ph.setAttribute("aria-hidden", "true");
      img.removeAttribute("aria-hidden");
      if (kind === "gif" && frame) {
        primeMediaElForWrap(img);
        applyMediaFrame(img, wrap, frame);
      } else {
        clearMediaFrameStyles(img);
      }
      return;
    }

    hideAllMedia(wrap, img, ph, video);
    ph.textContent = initial;
  }

  /**
   * @param {string} userId
   * @param {string|null|undefined} rel
   * @param {{ projectBase?: string, initial?: string, skipPublish?: boolean, mediaFrame?: object|null }} [options]
   */
  function apply(userId, rel, options) {
    if (!userId) return;
    options = options || {};
    var base = options.projectBase || "";
    if (!base && global.ADMIN_CTX && global.ADMIN_CTX.projectBase) {
      base = global.ADMIN_CTX.projectBase;
    }
    if (!base && typeof global.BASE_URL === "string") {
      base = global.BASE_URL;
    }
    var initial = (options.initial && String(options.initial).charAt(0)) || "?";
    initial = initial.toUpperCase();
    var resolved = rel ? resolveSrc(rel, base) : "";
    var kind = mediaKindFromRel(rel || "");
    var frame = options.mediaFrame || null;

    document.querySelectorAll("[data-antara-profile-wrap]").forEach(function (wrap) {
      if (wrap.getAttribute("data-antara-profile-wrap") !== userId) return;
      applyToWrap(wrap, {
        src: resolved,
        kind: kind,
        mediaFrame: frame,
        initial: initial,
      });
    });

    if (!options.skipPublish) {
      publish(userId, rel, { projectBase: base, initial: initial, mediaFrame: frame });
    }

    if (typeof global.dispatchEvent === "function") {
      try {
        global.dispatchEvent(
          new CustomEvent("antara:profileImageUpdated", {
            detail: {
              userId: userId,
              profileImageRel: rel || "",
              profileMediaFrame: frame || null,
              projectBase: base,
            },
          })
        );
      } catch (_) {}
    }
  }

  function handlePayload(payload) {
    if (!payload || !payload.userId) return;
    apply(payload.userId, payload.rel, {
      projectBase: payload.projectBase || "",
      initial: payload.initial,
      mediaFrame: payload.mediaFrame || null,
      skipPublish: true,
    });
  }

  /**
   * Escucha cambios (otra pestaña admin) y reaplica al volver al escritorio.
   * @param {{ sessionUserId?: string, projectBase?: string, initial?: string }} [opts]
   */
  function init(opts) {
    opts = opts || {};
    var sessionUserId = opts.sessionUserId || "";

    global.addEventListener("storage", function (e) {
      if (!e.key || e.key.indexOf(STORAGE_PREFIX) !== 0) return;
      try {
        handlePayload(JSON.parse(e.newValue || "{}"));
      } catch (_) {}
    });

    if (typeof global.BroadcastChannel === "function") {
      try {
        var channel = new global.BroadcastChannel("antara-profile-image");
        channel.addEventListener("message", function (ev) {
          handlePayload(ev.data);
        });
      } catch (_) {}
    }

    global.addEventListener("focus", function () {
      if (!sessionUserId) return;
      var stored = readStored(sessionUserId);
      if (stored) handlePayload(stored);
    });

    if (sessionUserId) {
      var cur = readStored(sessionUserId);
      if (cur && cur.rel) {
        handlePayload(
          Object.assign({ projectBase: opts.projectBase || "" }, cur, { initial: opts.initial || cur.initial })
        );
      }
    }
  }

  function initClientLogoWraps() {
    if (typeof document === "undefined") return;
    document.querySelectorAll("[data-antara-client-logo-wrap]").forEach(function (wrap) {
      var img = wrap.querySelector("[data-antara-profile-img]");
      var src = img && (img.getAttribute("src") || img.src);
      if (!src) return;
      var frame = null;
      var frameAttr = wrap.getAttribute("data-client-logo-frame");
      if (frameAttr) {
        try { frame = JSON.parse(frameAttr); } catch (_) { frame = null; }
      }
      applyToWrap(wrap, {
        src: src,
        kind: mediaKindFromRel(src),
        mediaFrame: frame,
        initial: "L",
        noCacheBust: true,
      });
    });
  }

  global.AntaraProfileImageSync = {
    apply: apply,
    applyToWrap: applyToWrap,
    resolveSrc: resolveSrc,
    mediaKindFromRel: mediaKindFromRel,
    mediaKindFromFile: mediaKindFromFile,
    init: init,
    initClientLogoWraps: initClientLogoWraps,
    publish: publish,
  };

  if (typeof document !== "undefined") {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", initClientLogoWraps);
    } else {
      initClientLogoWraps();
    }
  }
})(typeof window !== "undefined" ? window : this);
