var saveImages = [];
var deleteAttachmentUrl = window.partesDeleteAttachmentUrl || null;
var deletedAttachmentTracker = {};

function escapeHtml(text) {
  if (text === null || text === undefined) {
    return '';
  }
  return String(text)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}

function guardarImagen(idtarea, archivo) {
  // evita archivos duplicados para la misma tarea
  if (saveImages.some(function(img) {
    return img.idtarea === idtarea && img.archivo.name === archivo.name;
  })) {
    return false;
  }

  saveImages.push({ idtarea: idtarea, archivo: archivo });
  return true;
}

async function partesUploadPendingImages(options) {
  options = options || {};
  var endpoint = options.endpoint;
  if (!endpoint) {
    throw new Error('endpoint requerido');
  }

  if (!Array.isArray(saveImages) || saveImages.length === 0) {
    return { success: true, remaining: saveImages ? saveImages.slice() : [] };
  }

  var mainId = options.mainId !== undefined ? String(options.mainId) : '';
  var baseId = options.baseId !== undefined ? options.baseId : '';
  var formData = new FormData();
  var hasUploads = false;

  saveImages.forEach(function(item) {
    if (!item || !item.archivo) {
      return;
    }

    var relacionado = item.idtarea !== undefined && item.idtarea !== null ? String(item.idtarea) : '';
    var isMain = relacionado === mainId || (relacionado === '' && (mainId === '' || mainId === 'null'));

    if (isMain) {
      formData.append('files[]', item.archivo);
      hasUploads = true;
    } else {
      formData.append('filesSubtarea[]', item.archivo);
      formData.append('idtareaSubtarea[]', relacionado);
      hasUploads = true;
    }
  });

  if (!hasUploads) {
    return { success: true, remaining: saveImages.slice() };
  }

  formData.append('idtarea', mainId);
  if (baseId !== undefined) {
    formData.append('baseidtareaimagen', baseId);
  }

  if (options.extraData) {
    Object.keys(options.extraData).forEach(function(key) {
      var value = options.extraData[key];
      if (Array.isArray(value)) {
        value.forEach(function(item) {
          formData.append(key + '[]', item);
        });
        return;
      }
      formData.append(key, value == null ? '' : value);
    });
  }

  var response = await $.ajax({
    type: 'POST',
    url: endpoint,
    data: formData,
    contentType: false,
    processData: false,
    dataType: 'json'
  });

  var success = response && response.success === true;
  return {
    success: success,
    payload: response,
    remaining: success ? [] : saveImages.slice()
  };
}

function mostrarImagenesGuardadas(idtarea, name, src, fileId){
  var contenedorImagenes = document.getElementById('presentation' + idtarea);
  if (!contenedorImagenes) {
    return;
  }
  var id = generarIdLargo(33);
  var html = crearHtmlImagen(id, name, src, idtarea, fileId);
  contenedorImagenes.insertAdjacentHTML('beforeend', html);
}

function generarIdLargo(longitud) {
  const caracteres = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let id = '';

  for (let i = 0; i < longitud; i++) {
    const indiceAleatorio = Math.floor(Math.random() * caracteres.length);
    id += caracteres.charAt(indiceAleatorio);
  }

  return id;
}

function crearHtmlImagen(id, name, src, idtarea, fileId) {
  const safeName = JSON.stringify(name || '');
  const safeSrc = JSON.stringify(src || '');
  const safeIdTarea = JSON.stringify(idtarea);
  const safeFileId = fileId !== undefined && fileId !== null && fileId !== '' ? JSON.stringify(String(fileId)) : 'null';
  const nameHtml = escapeHtml(name || '');

  return `
        <div id="${id}" class="uppy-Dashboard-Item is-resumable">
        <div class="uppy-Dashboard-Item-preview">
        <div class="uppy-Dashboard-Item-previewInnerWrap" style="background-color: rgb(104, 109, 224);">
        <img class="uppy-Dashboard-Item-previewImg" alt=${safeName} src=${safeSrc} onclick='showImageModal(${safeSrc}, ${safeName})'>
        </div>
        </div>
        <div class="uppy-Dashboard-Item-fileInfoAndButtons">
          <div class="uppy-Dashboard-Item-fileInfo" data-uppy-file-source="Dashboard">
            <div class="uppy-Dashboard-Item-fileName">
              <div class="uppy-Dashboard-Item-name" title=${safeName}>${nameHtml}</div>
              </div>
            </div>
            <div class="uppy-Dashboard-Item-actionWrapper">
              <button onclick='removeFile("${id}", ${safeName}, ${safeSrc}, ${safeIdTarea}, ${safeFileId})' class="uppy-u-reset uppy-Dashboard-Item-action uppy-Dashboard-Item-action--remove" type="button" aria-label="Remove file" title="Remove file">
                <i class="fa-solid fa-circle-xmark"></i>
              </button>
            </div>
        </div>
        </div>`;
}

function mostrarImagenes(input, idtarea) {
  var contenedorImagenes = document.getElementById('presentation' + idtarea);
  if (!contenedorImagenes || !input.files) {
    return;
  }

  var archivos = input.files;
  for (let i = 0; i < archivos.length; i++) {
    let archivo = archivos[i];

    if (!guardarImagen(idtarea, archivo)) {
      continue;
    }

    var reader = new FileReader();

    let id = Math.random().toString(36).substr(2, 9);

    reader.onload = function(e) {
      var html = crearHtmlImagen(id, archivo.name, e.target.result, idtarea, null);
      contenedorImagenes.insertAdjacentHTML('beforeend', html);
    };
    reader.readAsDataURL(archivo);
  }
}

function removeFile(id, nombreArchivo, src, idtarea, fileId) {
  var elemento = document.getElementById(id);
  if (elemento) {
    elemento.remove();
  }

  if (fileId === null || fileId === undefined || fileId === 'null' || fileId === '') {
    var index = saveImages.findIndex(function(imagen) {
      return imagen.idtarea === idtarea && imagen.archivo.name === nombreArchivo;
    });

    if (index !== -1) {
      saveImages.splice(index, 1);
    }
  }

  var inputOculto =
    document.getElementById('imagenesBorradas' + idtarea) ||
    document.getElementById('imagenesBorradas');
  if (inputOculto) {
    var identifier = obtenerIdentificadorAdjunto(fileId, src);

    if (identifier) {
      agregarIdentificadorBorrado(inputOculto, identifier);
      enviarEliminacionAdjunto(identifier);
    }
  }
}

function showImageModal(src, name){
  var modal = document.getElementById('imagePreviewModal');
  if(modal){
    modal.querySelector('img').src = src;
    modal.querySelector('.modal-title').textContent = name || '';
    $('#imagePreviewModal').modal('show');
  }
}

function obtenerIdentificadorAdjunto(fileId, src) {
  if (fileId !== null && fileId !== undefined && fileId !== 'null' && fileId !== '') {
    return String(fileId);
  }

  if (typeof src === 'string' && src && !src.startsWith('data:')) {
    return src;
  }

  return null;
}

function agregarIdentificadorBorrado(input, identifier) {
  var valoresActuales = input.value ? input.value.split(',').map(function(item) {
    return item.trim();
  }).filter(Boolean) : [];

  if (valoresActuales.indexOf(identifier) === -1) {
    valoresActuales.push(identifier);
    input.value = valoresActuales.join(',');
  }
}

function enviarEliminacionAdjunto(identifier) {
  if (!identifier) {
    return;
  }

  if (!deleteAttachmentUrl && window.partesDeleteAttachmentUrl) {
    deleteAttachmentUrl = window.partesDeleteAttachmentUrl;
  }

  if (!deleteAttachmentUrl) {
    return;
  }

  if (deletedAttachmentTracker[identifier]) {
    return;
  }
  deletedAttachmentTracker[identifier] = true;

  $.ajax({
    type: 'POST',
    url: deleteAttachmentUrl,
    data: { identifier: identifier },
    dataType: 'json'
  }).fail(function() {
    delete deletedAttachmentTracker[identifier];
    console.error('No se pudo eliminar el adjunto', identifier);
  });
}

function imprimirModalCamara(idTarea) {
    var modalHTML = `
        <div dir="ltr" class="modal fade" id="modalCamara${idTarea}" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body text-center">
                                    <div id="drag-drop-area">
                                        <div class="uppy-Root">
                                            <div class="uppy-Dashboard uppy-Dashboard--animateOpenClose uppy-size--md uppy-size--lg uppy-size--height-md uppy-Dashboard--isInnerWrapVisible" data-uppy-theme=" light" data-uppy-num-acquirers="0" data-uppy-drag-drop-supported="true" aria-hidden="false" aria-disabled="false" aria-label="Uppy Dashboard">
                                                <div class="uppy-Dashboard-inner" aria-modal="false" role="false" style="width: 1148px; height: 550px;">
                                                    <div class="uppy-Dashboard-innerWrap">
                                                        <div class="uppy-DashboardContent-bar">
                                                            <button data-bs-dismiss="modal" class="uppy-DashboardContent-back" type="button">Cancelar</button>
                                                            <button onclick="document.getElementById('archivos${idTarea}').click()" class="uppy-DashboardContent-addMore" type="button" aria-label="Add more files" title="Add more files">
                                                                <i class="fa-solid fa-circle-xmark"></i>
                                                                <span class="uppy-DashboardContent-addMoreCaption">Agregar más</span>
                                                            </button>
                                                        </div>
                                                        <div class="uppy-Dashboard-files" role="list">
                                                            <div role="presentation" style="position: relative; width: 100%; min-height: 100%; height: 200px;">
                                                                <div role="presentation" style="position: absolute; top: 0px; left: 0px; width: 100%; overflow: visible;">
                                                                    <div role="presentation" id="presentation${idTarea}">

                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="uppy-Dashboard-progressindicators">
                                                            <div class="uppy-StatusBar is-waiting" aria-hidden="false">
                                                                <div class="uppy-StatusBar-progress" role="progressbar" aria-label="0%" aria-valuetext="0%" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width: 0%;"></div>
                                                                <div class="uppy-StatusBar-actions">
                                                                    <button type="button" class="uppy-u-reset uppy-c-btn uppy-StatusBar-actionBtn uppy-StatusBar-actionBtn--upload uppy-c-btn-primary" aria-label="Upload 3 files" data-bs-dismiss="modal" data-uppy-super-focusable="true">Aceptar</button>
                                                                </div>
                                                            </div>
                                                            <div class="uppy uppy-Informer"><span></span></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    if (!document.getElementById("modalCamara" + idTarea)) {
        document.body.insertAdjacentHTML('beforeend', modalHTML);
    }
}
// --- Prevent duplicate submissions -------------------------------------------------
(function() {
  const lockRegistry = {};

  function normalizeKey(rawKey) {
    if (rawKey === null || rawKey === undefined || rawKey === '') {
      return '__default__';
    }
    return String(rawKey);
  }

  function wrapAsyncFunction(fnName, keyResolver) {
    const original = window[fnName];
    if (typeof original !== 'function' || original.__partesWrapped) {
      return;
    }

    const wrapped = async function(...args) {
      const key = normalizeKey(keyResolver(args));
      if (lockRegistry[key]) {
        console.warn('[Partes] Acción ignorada por envío duplicado', fnName, key);
        return;
      }

      lockRegistry[key] = true;
      try {
        return await original.apply(this, args);
      } finally {
        lockRegistry[key] = false;
      }
    };

    wrapped.__partesWrapped = true;
    window[fnName] = wrapped;
  }

  function applyGuards() {
    wrapAsyncFunction('enviarFormulario', args => args[0]);
    wrapAsyncFunction('guardarTarea', () => '__nueva__');
  }

  const kick = () => setTimeout(applyGuards, 0);

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', kick, { once: true });
    window.addEventListener('load', kick, { once: true });
  } else {
    kick();
    if (document.readyState !== 'complete') {
      window.addEventListener('load', kick, { once: true });
    }
  }
})();
