{{-- Cropper.js JS logic (shared by category and product admin views) --}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js"></script>
<script>
(function () {
    var cropperInstance = null;
    var cropModal       = new bootstrap.Modal(document.getElementById('cropModal'));
    var cropImage       = document.getElementById('crop-image');
    var fileInput       = document.getElementById('img-file-input');
    var selectBtn       = document.getElementById('select-img-btn');
    var confirmBtn      = document.getElementById('crop-confirm-btn');
    var imageData       = document.getElementById('image-data');
    var previewWrap     = document.getElementById('img-preview-wrap');
    var previewImg      = document.getElementById('img-preview');
    var noImageText     = document.getElementById('no-image-text');

    selectBtn.addEventListener('click', function () { fileInput.click(); });

    fileInput.addEventListener('change', function () {
        if (!this.files || !this.files[0]) return;
        var reader = new FileReader();
        reader.onload = function (e) {
            cropImage.src = e.target.result;
            cropModal.show();
            document.getElementById('cropModal').addEventListener('shown.bs.modal', function onShown() {
                this.removeEventListener('shown.bs.modal', onShown);
                if (cropperInstance) { cropperInstance.destroy(); }
                cropperInstance = new Cropper(cropImage, {
                    viewMode: 1,
                    aspectRatio: 1,
                    autoCropArea: 0.9,
                    responsive: true,
                });
            });
        };
        reader.readAsDataURL(this.files[0]);
        this.value = '';
    });

    confirmBtn.addEventListener('click', function () {
        if (!cropperInstance) return;
        var canvas = cropperInstance.getCroppedCanvas({ width: 600, height: 600 });
        var dataUrl = canvas.toDataURL('image/jpeg', 0.85);
        imageData.value = dataUrl;
        previewImg.src = dataUrl;
        previewWrap.classList.remove('d-none');
        if (noImageText) noImageText.classList.add('d-none');
        cropModal.hide();
        cropperInstance.destroy();
        cropperInstance = null;
    });

    document.getElementById('cropModal').addEventListener('hidden.bs.modal', function () {
        if (cropperInstance) { cropperInstance.destroy(); cropperInstance = null; }
    });
})();
</script>
