/**
 * Permite a cualquier usuario logueado cambiar su foto/GIF/vídeo de perfil desde el escritorio.
 */
(function (global) {
  "use strict";

  var pendingFile = null;
  var pendingMediaFrame = null;
  var pendingBlobUrl = "";
  var binding = null;
  var CSRF = "";

  function $(id) {
    return document.getElementById(id);
  }

  function revokePending() {
    if (pendingBlobUrl) {
      try { URL.revokeObjectURL(pendingBlobUrl); } catch (_) {}
      pendingBlobUrl = "";
    }
  }

  function setFeedback(msg, ok) {
    var fb = $("profile-self-feedback");
    if (!fb) return;
    fb.textContent = msg || "";
    fb.classList.toggle("is-ok", !!ok);
  }

  async function uploadProfile(userId, file, mediaFrame) {
    var auth = global.GRID_AUTH || {};
    var apiUrl = auth.apiUrl || "/core/auth/api.php";
    var url = apiUrl + (apiUrl.indexOf("?") >= 0 ? "&" : "?") + "action=usersProfileImage";
    var fd = new FormData();
    fd.append("userId", userId);
    fd.append("file", file);
    if (mediaFrame) fd.append("mediaFrame", JSON.stringify(mediaFrame));
    var res = await fetch(url, {
      method: "POST",
      credentials: "same-origin",
      headers: { Accept: "application/json", "X-CSRF-Token": CSRF },
      body: fd,
    });
    var data;
    try { data = await res.json(); } catch (_) { data = { success: false, error: "Bad JSON" }; }
    if (data && data.data && typeof data.data.csrf === "string") CSRF = data.data.csrf;
    if (!data || data.success !== true) {
      throw new Error((data && data.error) || ("HTTP " + res.status));
    }
    return data.data;
  }

  function applyUser(user) {
    var u = global.GRID_SESSION_USER;
    if (!u || !user) return;
    u.profileImageRel = user.profileImageRel || "";
    u.profileMediaFrame = user.profileMediaFrame || null;
    var sync = global.AntaraProfileImageSync;
    if (sync && typeof sync.apply === "function") {
      sync.apply(u.id, u.profileImageRel, {
        projectBase: typeof global.BASE_URL === "string" ? global.BASE_URL : "",
        initial: u.initial || "?",
        mediaFrame: u.profileMediaFrame,
      });
    }
  }

  function onAccepted(b) {
    var f = b && b.fileInput && b.fileInput.files && b.fileInput.files[0];
    if (!f) return;
    pendingFile = f;
    pendingMediaFrame = b.mediaFrame || null;
    revokePending();
    pendingBlobUrl = URL.createObjectURL(f);
    setFeedback("Listo. Pulsa Guardar para aplicar tu foto de perfil.", true);
  }

  function resetPicker() {
    pendingFile = null;
    pendingMediaFrame = null;
    revokePending();
    var fi = $("profile-self-file");
    if (fi) fi.value = "";
    if (binding) binding.cropReady = false;
  }

  function init() {
    var u = global.GRID_SESSION_USER;
    var auth = global.GRID_AUTH || {};
    if (!u || !u.id) return;
    CSRF = auth.csrf || "";

    var pickGallery = $("profile-self-gallery");
    var pickCamera = $("profile-self-camera");
    var fileInput = $("profile-self-file");
    var saveBtn = $("profile-self-save");
    var clearBtn = $("profile-self-clear");
    var cancelBtn = $("profile-self-cancel");
    var IIP = global.InstallImagePicker;

    if (IIP && fileInput) {
      IIP.ensureDialog();
      binding = IIP.bind({
        fileInput: fileInput,
        sourceHidden: $("profile-self-source"),
        dialogTitle: "Foto de perfil",
        onAccept: onAccepted,
      });
    }

    function openPicker(capture) {
      if (!fileInput) return;
      if (capture) fileInput.setAttribute("capture", "environment");
      else fileInput.removeAttribute("capture");
      fileInput.click();
    }

    if (pickGallery) pickGallery.addEventListener("click", function () { openPicker(false); });
    if (pickCamera) pickCamera.addEventListener("click", function () { openPicker(true); });
    if (cancelBtn) {
      cancelBtn.addEventListener("click", function () {
        resetPicker();
        setFeedback("");
        var dlg = $("profile-self-dialog");
        if (dlg && dlg.open) dlg.close();
      });
    }
    if (clearBtn) {
      clearBtn.addEventListener("click", async function () {
        setFeedback("Quitando…", false);
        try {
          var res = await fetch((auth.apiUrl || "/core/auth/api.php") + "?action=usersUpdate", {
            method: "POST",
            credentials: "same-origin",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              "X-CSRF-Token": CSRF,
            },
            body: JSON.stringify({ id: u.id, clearProfileImage: true }),
          });
          var data = await res.json();
          if (data && data.data && data.data.csrf) CSRF = data.data.csrf;
          if (!data || data.success !== true) throw new Error((data && data.error) || "Error");
          applyUser(data.data.user || { profileImageRel: "", profileMediaFrame: null });
          resetPicker();
          setFeedback("Imagen quitada.", true);
        } catch (e) {
          setFeedback(e.message || "Error.", false);
        }
      });
    }
    if (saveBtn) {
      saveBtn.addEventListener("click", async function () {
        if (!pendingFile) {
          setFeedback("Elige un archivo primero.", false);
          return;
        }
        if (binding && IIP && !IIP.validateSubmit(binding)) {
          setFeedback("Confirma en el editor (Aceptar) antes de guardar.", false);
          return;
        }
        setFeedback("Guardando…", false);
        try {
          var payload = await uploadProfile(u.id, pendingFile, pendingMediaFrame);
          applyUser(payload.user || {});
          resetPicker();
          setFeedback("Foto de perfil actualizada.", true);
          setTimeout(function () {
            var dlg = $("profile-self-dialog");
            if (dlg && dlg.open) dlg.close();
          }, 500);
        } catch (e) {
          setFeedback(e.message || "Error al subir.", false);
        }
      });
    }
  }

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