/**
 * Selector de imagen con original o recorte 1:1 — instalador Flexia.
 */
(function (global) {
  'use strict';

  var dlg = null;
  var titleEl = null;
  var previewImg = null;
  var cropImg = null;
  var cropWrap = null;
  var previewBlock = null;
  var cropHint = null;
  var modeCropRadio = null;
  var applyCropBtn = null;
  var redoCropBtn = null;
  var cancelBtn = null;
  var acceptBtn = null;
  var cropper = null;
  var activeBinding = null;
  var modalObjectUrl = '';
  var modalCroppedBlob = null;
  var modalCroppedDisplayUrl = '';
  var modalPendingFile = null;
  var closeCommitted = false;
  var cropReady = false;
  var modeBlock = null;
  var frameWrap = null;
  var frameViewport = null;
  var frameImg = null;
  var frameVideo = null;
  var frameZoom = null;
  var frameUnbind = null;
  var editorMode = 'image';

  function isVideo(f) {
    if (!f) return false;
    var t = (f.type || '').toLowerCase();
    if (t.indexOf('video/') === 0) return true;
    var n = (f.name || '').toLowerCase();
    return /\.(mp4|webm|ogg)$/.test(n);
  }

  function usesFrameMode(f) {
    return isGif(f) || isVideo(f);
  }

  function destroyFrameEditor() {
    if (typeof frameUnbind === 'function') {
      try { frameUnbind(); } catch (_) {}
    }
    frameUnbind = null;
    if (frameImg) {
      frameImg.hidden = true;
      frameImg.removeAttribute('src');
    }
    if (frameVideo) {
      try { frameVideo.pause(); } catch (_) {}
      frameVideo.hidden = true;
      frameVideo.removeAttribute('src');
    }
  }

  function bootFrameEditor() {
    destroyFrameEditor();
    if (!frameViewport || !modalObjectUrl) return;
    var mediaEl = isVideo(modalPendingFile) ? frameVideo : frameImg;
    if (!mediaEl) return;
    if (frameImg) frameImg.hidden = mediaEl !== frameImg;
    if (frameVideo) frameVideo.hidden = mediaEl !== frameVideo;
    mediaEl.src = modalObjectUrl;
    var WAC = global.AntaraAvatarSquareCrop;
    if (!WAC || typeof WAC.bindSquareAvatarCrop !== 'function') return;
    function attach() {
      frameUnbind = WAC.bindSquareAvatarCrop({
        viewport: frameViewport,
        img: mediaEl,
        zoomRange: frameZoom,
        frameInsetRatio: 0.1,
      });
    }
    if (mediaEl.tagName === 'VIDEO') {
      mediaEl.onloadeddata = function () {
        mediaEl.onloadeddata = null;
        attach();
      };
      try { mediaEl.load(); } catch (_) {}
      if (mediaEl.readyState >= 2) attach();
    } else {
      mediaEl.onload = function () {
        mediaEl.onload = null;
        attach();
      };
      if (mediaEl.complete && mediaEl.naturalWidth) attach();
    }
  }

  function syncFrameModeUi() {
    if (modeBlock) modeBlock.hidden = true;
    if (previewBlock) previewBlock.hidden = true;
    if (cropWrap) cropWrap.hidden = true;
    if (frameWrap) frameWrap.hidden = false;
    destroyCropper();
    bootFrameEditor();
  }

  function isGif(f) {
    if (!f) return false;
    var t = (f.type || '').toLowerCase();
    if (t === 'image/gif') return true;
    var n = (f.name || '').toLowerCase();
    return n.endsWith('.gif');
  }

  function alertMsg(msg) {
    if (typeof global.installAlert === 'function') {
      return global.installAlert(msg);
    }
    global.alert(msg);
    return Promise.resolve();
  }

  function revokeUrl(urlRef) {
    if (urlRef && urlRef.current) {
      try {
        URL.revokeObjectURL(urlRef.current);
      } catch (e) {}
      urlRef.current = '';
    }
  }

  function destroyCropper() {
    if (cropper) {
      try {
        cropper.destroy();
      } catch (e) {}
      cropper = null;
    }
    updateCropActionButtons();
  }

  function revokeCroppedDisplay() {
    if (modalCroppedDisplayUrl) {
      try {
        URL.revokeObjectURL(modalCroppedDisplayUrl);
      } catch (e) {}
      modalCroppedDisplayUrl = '';
    }
  }

  function revokeModalUrl() {
    if (modalObjectUrl) {
      try {
        URL.revokeObjectURL(modalObjectUrl);
      } catch (e) {}
      modalObjectUrl = '';
    }
  }

  function getModeRadios() {
    return dlg ? dlg.querySelectorAll('input[name="install_image_modal_mode"]') : [];
  }

  function wantCropMode() {
    var cropRadio = dlg ? dlg.querySelector('input[name="install_image_modal_mode"][value="crop"]') : null;
    return !!(cropRadio && cropRadio.checked);
  }

  function updateCropActionButtons() {
    if (!wantCropMode()) {
      if (applyCropBtn) {
        applyCropBtn.hidden = false;
        applyCropBtn.disabled = false;
      }
      if (redoCropBtn) redoCropBtn.hidden = true;
      return;
    }
    var appliedCrop = !!modalCroppedBlob;
    var hasCropperInst = !!cropper;
    if (applyCropBtn) {
      applyCropBtn.hidden = !!(appliedCrop && !hasCropperInst);
      applyCropBtn.disabled = false;
    }
    if (redoCropBtn) {
      redoCropBtn.hidden = !(appliedCrop && !hasCropperInst);
    }
  }

  function showSavedCropInStage() {
    if (!cropImg || !modalCroppedBlob) return;
    destroyCropper();
    revokeCroppedDisplay();
    modalCroppedDisplayUrl = URL.createObjectURL(modalCroppedBlob);
    cropImg.src = modalCroppedDisplayUrl;
    updateCropActionButtons();
  }

  function applyCropFromCropper() {
    return new Promise(function (resolve) {
      if (!cropper || !modalPendingFile || isGif(modalPendingFile)) {
        resolve(null);
        return;
      }
      var canvas = cropper.getCroppedCanvas({
        width: 512,
        height: 512,
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high',
        fillColor: 'transparent',
      });
      if (!canvas) {
        resolve(null);
        return;
      }
      canvas.toBlob(function (blob) {
        resolve(blob || null);
      }, 'image/png');
    });
  }

  function bootCropper() {
    if (!cropImg || typeof global.Cropper === 'undefined') return;
    destroyCropper();
    cropper = new global.Cropper(cropImg, {
      aspectRatio: 1,
      viewMode: 1,
      dragMode: 'move',
      autoCropArea: 0.9,
      background: false,
      responsive: true,
      checkCrossOrigin: false,
      restore: false,
      guides: true,
      highlight: true,
    });
    updateCropActionButtons();
  }

  function syncModalModeUi() {
    if (editorMode === 'frame') {
      syncFrameModeUi();
      return;
    }
    if (frameWrap) frameWrap.hidden = true;
    if (modeBlock) modeBlock.hidden = false;
    if (!wantCropMode()) {
      destroyCropper();
      if (cropWrap) cropWrap.hidden = true;
      if (previewBlock) previewBlock.hidden = false;
      if (previewImg && modalObjectUrl) {
        if (previewImg.src && previewImg.src.indexOf('blob:') === 0 && previewImg.src !== modalObjectUrl) {
          try {
            URL.revokeObjectURL(previewImg.src);
          } catch (eR) {}
        }
        previewImg.removeAttribute('src');
        previewImg.src = modalObjectUrl;
      }
      updateCropActionButtons();
      return;
    }
    if (previewBlock) previewBlock.hidden = true;
    if (cropWrap) cropWrap.hidden = false;
    if (modalCroppedBlob) {
      if (cropHint) {
        cropHint.textContent =
          'Recorte guardado. «Aceptar» con «Recortar» lo envía. «Volver a ajustar» reinicia el encuadre sobre el original.';
      }
      showSavedCropInStage();
      return;
    }
    if (cropHint) {
      cropHint.textContent = 'Ajusta el encuadre y pulsa «Fijar recorte» (512 px).';
    }
    if (cropImg && modalObjectUrl) {
      if (cropImg.src && cropImg.src.indexOf('blob:') === 0 && cropImg.src !== modalObjectUrl) {
        try {
          URL.revokeObjectURL(cropImg.src);
        } catch (eRev) {}
      }
      cropImg.src = modalObjectUrl;
      function onImg() {
        bootCropper();
      }
      if (cropImg.complete && cropImg.naturalWidth) {
        onImg();
      } else {
        cropImg.onload = function () {
          cropImg.onload = null;
          onImg();
        };
      }
    }
    updateCropActionButtons();
  }

  function closeDialog(committed) {
    closeCommitted = !!committed;
    if (dlg && dlg.open) dlg.close();
  }

  function hideBindingPreview(binding) {
    if (!binding) return;
    if (binding.previewWrap) binding.previewWrap.classList.remove('is-on');
    var mediaWrap = binding.previewWrap && binding.previewWrap.querySelector('[data-install-media-wrap]');
    var sync = global.AntaraProfileImageSync;
    if (sync && mediaWrap) {
      sync.applyToWrap(mediaWrap, { initial: binding.previewInitial || '?' });
    } else if (binding.previewImg) {
      binding.previewImg.removeAttribute('src');
    }
    if (binding.formPreviewUrl) {
      try {
        URL.revokeObjectURL(binding.formPreviewUrl);
      } catch (e) {}
      binding.formPreviewUrl = '';
    }
    if (binding.mediaFrameHidden) binding.mediaFrameHidden.value = '';
    binding.mediaFrame = null;
  }

  function refreshBindingPreview(binding) {
    if (!binding || !binding.previewWrap) return;
    var file = binding.fileInput && binding.fileInput.files && binding.fileInput.files[0];
    var mediaWrap = binding.previewWrap.querySelector('[data-install-media-wrap]');
    var sync = global.AntaraProfileImageSync;
    if (!file) {
      if (binding.existingUrl && sync && mediaWrap) {
        sync.applyToWrap(mediaWrap, {
          src: binding.existingUrl,
          kind: binding.existingKind || null,
          mediaFrame: binding.existingFrame || null,
          initial: binding.previewInitial || 'L',
          noCacheBust: false,
        });
        binding.previewWrap.classList.add('is-on');
      }
      return;
    }
    if (binding.formPreviewUrl) {
      try {
        URL.revokeObjectURL(binding.formPreviewUrl);
      } catch (_) {}
    }
    binding.formPreviewUrl = URL.createObjectURL(file);
    var kind = isVideo(file) ? 'video' : (isGif(file) ? 'gif' : 'image');
    if (sync && mediaWrap) {
      sync.applyToWrap(mediaWrap, {
        src: binding.formPreviewUrl,
        kind: kind,
        mediaFrame: binding.mediaFrame || null,
        initial: binding.previewInitial || 'L',
        noCacheBust: true,
      });
    } else if (binding.previewImg) {
      binding.previewImg.src = binding.formPreviewUrl;
    }
    binding.previewWrap.classList.add('is-on');
    if (binding.mediaFrameHidden) {
      binding.mediaFrameHidden.value = binding.mediaFrame ? JSON.stringify(binding.mediaFrame) : '';
    }
  }

  function ensureDialog() {
    if (dlg) return dlg;
    dlg = document.getElementById('installImageEditorDialog');
    if (!dlg) return null;
    titleEl = document.getElementById('installImageEditorTitle');
    previewImg = document.getElementById('installImageModalPreviewImg');
    cropImg = document.getElementById('installImageModalCropImg');
    cropWrap = document.getElementById('installImageModalCropWrap');
    previewBlock = document.getElementById('installImageModalPreviewBlock');
    cropHint = document.getElementById('installImageModalCropHint');
    modeCropRadio = document.getElementById('installImageModalModeCrop');
    modeBlock = dlg.querySelector('.logo-modal-mode');
    frameWrap = document.getElementById('installImageModalFrameWrap');
    frameViewport = document.getElementById('installImageModalFrameViewport');
    frameImg = document.getElementById('installImageModalFrameImg');
    frameVideo = document.getElementById('installImageModalFrameVideo');
    frameZoom = document.getElementById('installImageModalFrameZoom');
    applyCropBtn = document.getElementById('installImageModalApplyCropBtn');
    redoCropBtn = document.getElementById('installImageModalRedoCropBtn');
    cancelBtn = document.getElementById('installImageModalCancelBtn');
    acceptBtn = document.getElementById('installImageModalAcceptBtn');

    dlg.addEventListener('close', function () {
      destroyCropper();
      destroyFrameEditor();
      revokeCroppedDisplay();
      if (previewImg && previewImg.src && previewImg.src.indexOf('blob:') === 0) {
        try {
          URL.revokeObjectURL(previewImg.src);
        } catch (e0) {}
        previewImg.removeAttribute('src');
      }
      if (cropImg && cropImg.src && cropImg.src.indexOf('blob:') === 0) {
        try {
          URL.revokeObjectURL(cropImg.src);
        } catch (e1) {}
        cropImg.removeAttribute('src');
      }
      revokeModalUrl();
      if (!closeCommitted && activeBinding) {
        modalPendingFile = null;
        if (activeBinding.fileInput) activeBinding.fileInput.value = '';
        hideBindingPreview(activeBinding);
        if (activeBinding.sourceHidden) activeBinding.sourceHidden.value = 'original';
        activeBinding.cropReady = false;
      }
      modalCroppedBlob = null;
      if (cropWrap) cropWrap.hidden = true;
      if (frameWrap) frameWrap.hidden = true;
      if (previewBlock) previewBlock.hidden = false;
      editorMode = 'image';
      closeCommitted = false;
      activeBinding = null;
    });

    getModeRadios().forEach(function (m) {
      m.addEventListener('change', syncModalModeUi);
    });

    if (applyCropBtn) {
      applyCropBtn.addEventListener('click', function () {
        void applyCropFromCropper().then(function (blob) {
          if (!blob) return;
          modalCroppedBlob = blob;
          showSavedCropInStage();
          if (cropHint) {
            cropHint.textContent =
              'Recorte fijado. «Volver a ajustar» vuelve a marcar el área sobre el original.';
          }
        });
      });
    }

    if (redoCropBtn) {
      redoCropBtn.addEventListener('click', function () {
        if (!modalPendingFile || isGif(modalPendingFile) || !modalObjectUrl || !cropImg) return;
        modalCroppedBlob = null;
        destroyCropper();
        revokeCroppedDisplay();
        var prevCropSrc = cropImg.src || '';
        if (prevCropSrc.indexOf('blob:') === 0 && prevCropSrc !== modalObjectUrl) {
          try {
            URL.revokeObjectURL(prevCropSrc);
          } catch (eRedo) {}
        }
        cropImg.removeAttribute('src');
        if (cropHint) {
          cropHint.textContent = 'Ajusta el encuadre y pulsa «Fijar recorte» (512 px).';
        }
        function bootAfterLoad() {
          bootCropper();
        }
        function attachLoadAndBoot() {
          if (cropImg.complete && cropImg.naturalWidth) {
            bootAfterLoad();
          } else {
            cropImg.onload = function () {
              cropImg.onload = null;
              bootAfterLoad();
            };
          }
        }
        requestAnimationFrame(function () {
          cropImg.src = modalObjectUrl;
          requestAnimationFrame(attachLoadAndBoot);
        });
      });
    }

    if (cancelBtn) {
      cancelBtn.addEventListener('click', function () {
        closeDialog(false);
      });
    }

    if (acceptBtn) {
      acceptBtn.addEventListener('click', function () {
        void (async function () {
          var binding = activeBinding;
          if (!binding || !binding.fileInput || !modalPendingFile) {
            closeDialog(false);
            return;
          }
          if (editorMode === 'frame') {
            var WAC = global.AntaraAvatarSquareCrop;
            binding.mediaFrame = WAC && frameViewport
              ? WAC.exportMediaFrame(frameViewport, { zoomRange: frameZoom })
              : null;
            if (binding.mediaFrame && frameViewport) {
              binding.mediaFrame.editorViewport = frameViewport.clientWidth || 300;
            }
            try {
              var dtFrame = new DataTransfer();
              dtFrame.items.add(modalPendingFile);
              binding.fileInput.files = dtFrame.files;
            } catch (eFrame) {
              await alertMsg('No se pudo confirmar el archivo en este navegador.');
              return;
            }
            if (binding.sourceHidden) binding.sourceHidden.value = 'frame';
            binding.cropReady = true;
          } else {
          var wantCrop = wantCropMode() && !isGif(modalPendingFile);
          if (wantCrop) {
            if (!modalCroppedBlob) {
              if (cropper) {
                var autoBlob = await applyCropFromCropper();
                if (!autoBlob) {
                  await alertMsg('No se pudo generar el recorte. Ajusta el encuadre e inténtalo de nuevo.');
                  return;
                }
                modalCroppedBlob = autoBlob;
              } else {
                await alertMsg(
                  'No hay imagen lista para recortar. Elige otra imagen o usa «Mantener original».'
                );
                return;
              }
            }
            try {
              var dt = new DataTransfer();
              dt.items.add(new File([modalCroppedBlob], 'image_crop.png', { type: 'image/png' }));
              binding.fileInput.files = dt.files;
            } catch (e) {
              await alertMsg('No se pudo aplicar el recorte en este navegador.');
              return;
            }
            if (binding.sourceHidden) binding.sourceHidden.value = 'crop_png';
            binding.cropReady = true;
            binding.mediaFrame = null;
          } else {
            try {
              var dt2 = new DataTransfer();
              dt2.items.add(modalPendingFile);
              binding.fileInput.files = dt2.files;
            } catch (e2) {
              await alertMsg('No se pudo confirmar el archivo en este navegador.');
              return;
            }
            if (binding.sourceHidden) binding.sourceHidden.value = 'original';
            binding.cropReady = true;
            binding.mediaFrame = null;
          }
          }
          if (binding.formPreviewUrl) {
            try {
              URL.revokeObjectURL(binding.formPreviewUrl);
            } catch (e3) {}
            binding.formPreviewUrl = '';
          }
          refreshBindingPreview(binding);
          if (typeof binding.onAccept === 'function') {
            binding.onAccept(binding);
          }
          closeDialog(true);
        })();
      });
    }

    return dlg;
  }

  async function openEditor(file, binding) {
    ensureDialog();
    if (!dlg || !file || !binding) return;
    if (typeof dlg.showModal !== 'function') {
      await alertMsg(
        'Tu navegador no admite el cuadro de diálogo de imagen. Prueba con un navegador actualizado.'
      );
      if (binding.fileInput) binding.fileInput.value = '';
      return;
    }
    activeBinding = binding;
    if (titleEl && binding.dialogTitle) titleEl.textContent = binding.dialogTitle;
    modalPendingFile = file;
    modalCroppedBlob = null;
    binding.cropReady = false;
    revokeCroppedDisplay();
    revokeModalUrl();
    modalObjectUrl = URL.createObjectURL(file);
    editorMode = usesFrameMode(file) ? 'frame' : 'image';
    if (previewImg) previewImg.src = editorMode === 'image' ? modalObjectUrl : '';
    if (cropImg) {
      if (cropImg.src && cropImg.src.indexOf('blob:') === 0) {
        try {
          URL.revokeObjectURL(cropImg.src);
        } catch (eC) {}
      }
      cropImg.removeAttribute('src');
    }
    var orig = dlg.querySelector('input[name="install_image_modal_mode"][value="original"]');
    if (editorMode === 'frame') {
      if (orig) orig.checked = true;
      if (modeCropRadio) modeCropRadio.disabled = true;
    } else {
      if (orig) orig.checked = false;
      if (modeCropRadio) {
        modeCropRadio.disabled = false;
        modeCropRadio.checked = true;
      }
    }
    destroyCropper();
    destroyFrameEditor();
    dlg.showModal();
    syncModalModeUi();
  }

  function bind(options) {
    options = options || {};
    var fileInput = options.fileInput;
    if (!fileInput) return null;
    ensureDialog();
    var binding = {
      fileInput: fileInput,
      sourceHidden: options.sourceHidden || null,
      mediaFrameHidden: options.mediaFrameHidden || null,
      previewWrap: options.previewWrap || null,
      previewImg: options.previewImg || null,
      dialogTitle: options.dialogTitle || 'Imagen',
      onAccept: options.onAccept || null,
      formPreviewUrl: '',
      cropReady: false,
      mediaFrame: null,
      existingUrl: options.existingUrl || '',
      existingFrame: options.existingFrame || null,
      existingKind: options.existingKind || null,
      previewInitial: options.previewInitial || 'L',
    };
    if (options.existingUrl && binding.previewWrap) {
      refreshBindingPreview(binding);
    } else if (options.existingUrl && binding.previewImg && binding.previewWrap) {
      binding.previewImg.src = options.existingUrl;
      binding.previewWrap.classList.add('is-on');
    }
    fileInput.addEventListener('change', function () {
      var f = fileInput.files && fileInput.files[0];
      if (!f) {
        hideBindingPreview(binding);
        if (binding.sourceHidden) binding.sourceHidden.value = 'original';
        binding.cropReady = false;
        modalPendingFile = null;
        return;
      }
      void openEditor(f, binding);
    });
    fileInput._installImageBinding = binding;
    return binding;
  }

  function validateSubmit(binding) {
    if (!binding || !binding.fileInput) return true;
    var f = binding.fileInput.files && binding.fileInput.files[0];
    if (!f) return true;
    if (!binding.cropReady) return false;
    if (binding.mediaFrameHidden) {
      binding.mediaFrameHidden.value = binding.mediaFrame ? JSON.stringify(binding.mediaFrame) : '';
    }
    return true;
  }

  global.InstallImagePicker = {
    ensureDialog: ensureDialog,
    bind: bind,
    validateSubmit: validateSubmit,
    openEditor: openEditor,
    refreshBindingPreview: refreshBindingPreview,
  };
})(typeof window !== 'undefined' ? window : globalThis);
