let cropper = null;

function showCropModal(imageUrl) {
    const modalHtml = `
    <div class="modal fade" id="cropModal" tabindex="-1" aria-labelledby="cropModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header bg-gradient-purple text-white">
            <h5 class="modal-title" id="cropModalLabel">Crop Cover Image</h5>
            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="text-center">
              <img id="cropperImage" src="${imageUrl}" style="max-width:100%; max-height:400px;">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn1" id="cropImageBtn">Crop & Use</button>
          </div>
        </div>
      </div>
    </div>`;
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    const cropModal = new bootstrap.Modal(document.getElementById('cropModal'));
    cropModal.show();
    return cropModal;
}

function handleCoverInputChange(e) {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function(event) {
        // Mostrar modal de crop
        const cropModal = showCropModal(event.target.result);
        cropModal._element.addEventListener('shown.bs.modal', function() {
            const image = document.getElementById('cropperImage');
            cropper = new Cropper(image, {
                aspectRatio: 640/359,
                viewMode: 1,
                autoCropArea: 1,
                minCropBoxWidth: 640,
                minCropBoxHeight: 359,
                ready() {
                    // Opcional: centrar crop box
                }
            });
        });
        // Al hacer crop
        document.getElementById('cropImageBtn').onclick = function() {
            if (cropper) {
                const canvas = cropper.getCroppedCanvas({ width: 640, height: 359 });
                canvas.toBlob(function(blob) {
                    // Reemplazar el archivo en el input file
                    const dataTransfer = new DataTransfer();
                    const croppedFile = new File([blob], file.name, { type: blob.type });
                    dataTransfer.items.add(croppedFile);
                    document.getElementById('cover').files = dataTransfer.files;
                    // Mostrar preview
                    const preview = document.querySelector('.mb-3.text-center img');
                    if (preview) {
                        preview.src = canvas.toDataURL();
                    }
                    // Cerrar modal
                    cropper.destroy();
                    cropper = null;
                    cropModal.hide();
                    document.getElementById('cropModal').remove();
                }, file.type);
            }
        };
        // Limpiar al cerrar
        cropModal._element.addEventListener('hidden.bs.modal', function() {
            if (cropper) {
                cropper.destroy();
                cropper = null;
            }
            const modalEl = document.getElementById('cropModal');
            if (modalEl) {
                modalEl.remove();
            }
        });
    };
    reader.readAsDataURL(file);
}

document.addEventListener('DOMContentLoaded', function() {
    const coverInput = document.getElementById('cover');
    if (coverInput) {
        coverInput.addEventListener('change', handleCoverInputChange);
    }
});
