window.WebpImagePaster = window.WebpImagePaster || {};

window.WebpImagePaster.Utils = (function () {
    function formatFileSize(bytes) {
        if (!bytes) {
            return '0 KB';
        }
        if (bytes < 1024) {
            return bytes + ' B';
        }
        if (bytes < 1024 * 1024) {
            return (bytes / 1024).toFixed(1) + ' KB';
        }
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }

    function sanitizeFileName(text) {
        if (!text) {
            return '';
        }
        return text.replace(/[^a-zA-Z0-9가-힣\-]/g, '_').replace(/_+/g, '_');
    }

    function sanitizeAltText(text) {
        if (!text) {
            return '';
        }
        return String(text).replace(/<[^>]*>?/gm, '').trim();
    }

    function isFormatSupported(format) {
        try {
            var dummyCanvas = document.createElement('canvas');
            dummyCanvas.width = 1;
            dummyCanvas.height = 1;
            var dataUrl = dummyCanvas.toDataURL('image/' + format);
            return dataUrl.indexOf('data:image/' + format) === 0;
        } catch (e) {
            return false;
        }
    }

    function getBlobFormat(blob) {
        if (!blob) {
            return '';
        }
        if (blob.type) {
            if (blob.type.indexOf('webp') !== -1) { return 'webp'; }
            if (blob.type.indexOf('avif') !== -1) { return 'avif'; }
            if (blob.type.indexOf('png') !== -1) { return 'png'; }
            if (blob.type.indexOf('jpeg') !== -1) { return 'jpeg'; }
            if (blob.type.indexOf('jpg') !== -1) { return 'jpeg'; }
            if (blob.type.indexOf('gif') !== -1) { return 'gif'; }
            if (blob.type.indexOf('svg') !== -1) { return 'svg'; }
            if (blob.type.indexOf('bmp') !== -1) { return 'bmp'; }
            if (blob.type.indexOf('icon') !== -1) { return 'ico'; }
            if (blob.type.indexOf('heic') !== -1) { return 'heic'; }
            if (blob.type.indexOf('heif') !== -1) { return 'heif'; }
        }
        if (blob.name) {
            var match = blob.name.match(/\.([a-zA-Z0-9]+)$/);
            if (match) {
                var ext = match[1].toLowerCase();
                if (ext === 'jpg' || ext === 'jfif' || ext === 'pjpeg' || ext === 'pjp' || ext === 'jpe') {
                    return 'jpeg';
                }
                return ext;
            }
        }
        return '';
    }

    function isOptimizedFormat(blob) {
        if (!blob) {
            return false;
        }
        var fmt = getBlobFormat(blob);
        return fmt === 'webp' || fmt === 'avif' || fmt === 'gif' || fmt === 'svg';
    }

    function isImageFile(file) {
        if (!file) {
            return false;
        }
        if (file.type && file.type.indexOf('image') !== -1) {
            return true;
        }
        var fmt = getBlobFormat(file);
        var supportedFormats = ['webp', 'avif', 'png', 'jpeg', 'gif', 'svg', 'bmp', 'ico', 'heic', 'heif'];
        return supportedFormats.indexOf(fmt) !== -1;
    }

    function isHeic(blob) {
        if (!blob) {
            return false;
        }
        var fmt = getBlobFormat(blob);
        if (fmt === 'heic' || fmt === 'heif') {
            return true;
        }
        if (blob.name && /\.(heic|heif)$/i.test(blob.name)) {
            return true;
        }
        return false;
    }

    var heicScriptLoadingPromise = null;
    function loadHeic2Any() {
        if (typeof window.heic2any === 'function') {
            return Promise.resolve(window.heic2any);
        }
        if (heicScriptLoadingPromise) {
            return heicScriptLoadingPromise;
        }

        heicScriptLoadingPromise = new Promise(function (resolve, reject) {
            var script = document.createElement('script');
            var localUrl = (window.WebpImagePasterSettings && window.WebpImagePasterSettings.heic2anyUrl)
                ? window.WebpImagePasterSettings.heic2anyUrl
                : '';
            var cdnUrl = 'https://cdn.jsdelivr.net/npm/heic2any@0.0.4/dist/heic2any.min.js';

            script.src = localUrl || cdnUrl;
            script.async = true;

            script.onload = function () {
                if (typeof window.heic2any === 'function') {
                    resolve(window.heic2any);
                } else {
                    reject(new Error('heic2any loaded but window.heic2any is not available'));
                }
            };

            script.onerror = function () {
                // If local script load fails, attempt CDN fallback
                if (localUrl && script.src !== cdnUrl) {
                    var cdnScript = document.createElement('script');
                    cdnScript.src = cdnUrl;
                    cdnScript.async = true;
                    cdnScript.onload = function () {
                        if (typeof window.heic2any === 'function') {
                            resolve(window.heic2any);
                        } else {
                            reject(new Error('heic2any loaded from CDN but window.heic2any is not available'));
                        }
                    };
                    cdnScript.onerror = function (e) {
                        heicScriptLoadingPromise = null;
                        reject(new Error('Failed to load heic2any from both local and CDN sources'));
                    };
                    document.head.appendChild(cdnScript);
                } else {
                    heicScriptLoadingPromise = null;
                    reject(new Error('Failed to load heic2any script'));
                }
            };

            document.head.appendChild(script);
        });

        return heicScriptLoadingPromise;
    }

    function convertSingleHeic(blob) {
        if (!isHeic(blob)) {
            return Promise.resolve(blob);
        }

        return loadHeic2Any().then(function (heic2any) {
            return heic2any({
                blob: blob,
                toType: 'image/jpeg',
                quality: 0.95
            });
        }).then(function (result) {
            var converted = Array.isArray(result) ? result[0] : result;
            var originalName = blob.name || 'image.heic';
            var newName = originalName.replace(/\.(heic|heif)$/i, '.jpg');

            var finalBlob = null;
            try {
                finalBlob = new File([converted], newName, { type: 'image/jpeg' });
            } catch (e) {
                finalBlob = converted;
                finalBlob.name = newName;
            }

            finalBlob._isConvertedFromHeic = true;
            finalBlob._originalHeicSize = blob.size;
            finalBlob._originalHeicName = originalName;

            return finalBlob;
        });
    }

    function convertHeicBlobs(blobs, onProgress) {
        if (!blobs || blobs.length === 0) {
            return Promise.resolve([]);
        }

        var results = [];
        var total = blobs.length;
        var completed = 0;

        function processNext(index) {
            if (index >= total) {
                return Promise.resolve(results);
            }

            var currentBlob = blobs[index];
            var promise = isHeic(currentBlob) ? convertSingleHeic(currentBlob) : Promise.resolve(currentBlob);

            return promise.then(function (converted) {
                results[index] = converted;
                completed++;
                if (onProgress) {
                    onProgress(completed, total);
                }
                return processNext(index + 1);
            });
        }

        return processNext(0);
    }

    var storage = {
        getItem: function (key, defaultValue) {
            try {
                var val = localStorage.getItem(key);
                return val !== null ? val : defaultValue;
            } catch (e) {
                return defaultValue;
            }
        },
        setItem: function (key, val) {
            try {
                localStorage.setItem(key, val);
            } catch (e) {
                // Ignore storage exceptions
            }
        }
    };

    return {
        formatFileSize: formatFileSize,
        sanitizeFileName: sanitizeFileName,
        sanitizeAltText: sanitizeAltText,
        isFormatSupported: isFormatSupported,
        getBlobFormat: getBlobFormat,
        isOptimizedFormat: isOptimizedFormat,
        isImageFile: isImageFile,
        isHeic: isHeic,
        loadHeic2Any: loadHeic2Any,
        convertSingleHeic: convertSingleHeic,
        convertHeicBlobs: convertHeicBlobs,
        storage: storage
    };
})();
