/**
 * ImageUtils — Shared image compression utility.
 *
 * MR-01 FIX: Extracts the canvas-based JPEG compression pattern that was
 * duplicated across MouldDetectService.compressImage(), ThumbnailService.generate(),
 * and MouldDetectService.compressForPreview(). Bug fixes and improvements
 * (canvas cleanup, handler nulling, aspect-ratio rounding) now apply everywhere.
 *
 * Public API:
 *   ImageUtils.compressToJpeg(dataURL, maxDim, quality) → Promise<string>
 *
 * No dependencies. No React. Loaded before MouldDetectService and ThumbnailService.
 * ES5 — no const, let, arrow functions, template literals, optional chaining.
 */
var ImageUtils = (function () {

    /**
     * Compress a dataURL to a JPEG string at the given maximum dimension and quality.
     *
     * @param {string} dataURL  — Source image as base64 data URL
     * @param {number} maxDim   — Max width or height in pixels (default: 200)
     * @param {number} quality  — JPEG quality 0–1 (default: 0.7)
     * @returns {Promise<string>} — Compressed JPEG as base64 data URL
     */
    function compressToJpeg(dataURL, maxDim, quality) {
        maxDim  = maxDim  || 200;
        quality = quality || 0.7;

        return new Promise(function (resolve, reject) {
            var img = new Image();

            img.onerror = function () {
                img.onload = img.onerror = null;
                reject(new Error('Could not open this image. Please try a different photo.'));
            };

            img.onload = function () {
                img.onload = img.onerror = null; // release handler refs — prevents GC retention
                try {
                    var w = img.width;
                    var h = img.height;

                    // Scale down preserving aspect ratio — integer rounding prevents
                    // sub-pixel canvas dimensions which cause blurry output on some browsers
                    if (w > h && w > maxDim) {
                        h = Math.round(h * maxDim / w);
                        w = maxDim;
                    } else if (h > maxDim) {
                        w = Math.round(w * maxDim / h);
                        h = maxDim;
                    }

                    var canvas = document.createElement('canvas');
                    canvas.width  = w;
                    canvas.height = h;
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, w, h);
                    var result = canvas.toDataURL('image/jpeg', quality);

                    // Release canvas backing store before returning
                    ctx.clearRect(0, 0, w, h);
                    canvas.width  = 0;
                    canvas.height = 0;

                    resolve(result);
                } catch (e) {
                    reject(e);
                }
            };

            img.src = dataURL;
        });
    }

    return { compressToJpeg: compressToJpeg };

})();

window.ImageUtils = ImageUtils;
