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

window.WebpImagePaster.Modal = (function () {
    var el = wp.element.createElement;
    var useState = wp.element.useState;
    var useEffect = wp.element.useEffect;
    var Modal = wp.components.Modal;
    var Button = wp.components.Button;
    var TextControl = wp.components.TextControl;
    var RangeControl = wp.components.RangeControl;
    var CheckboxControl = wp.components.CheckboxControl;
    var Spinner = wp.components.Spinner;
    var __ = wp.i18n.__;
    var sprintf = wp.i18n.sprintf;

    var Utils = window.WebpImagePaster.Utils;
    var Processor = window.WebpImagePaster.Processor;
    var Editor = window.WebpImagePaster.Editor;

    function WebpImagePasterModal(props) {
        var isPro = !!props.isPro;

        var stateBlobs = useState([]);
        var imageBlobs = stateBlobs[0];
        var setImageBlobs = stateBlobs[1];

        var isGalleryMode = imageBlobs && imageBlobs.length > 1;

        var stateName = useState('');
        var fileName = stateName[0];
        var setFileName = stateName[1];

        var stateAlt = useState('');
        var altText = stateAlt[0];
        var setAltText = stateAlt[1];

        var stateDetectedFormat = useState('');
        var detectedFormat = stateDetectedFormat[0];
        var setDetectedFormat = stateDetectedFormat[1];

        var initialWidth = 0;
        var initialQuality = 85;
        var initialFormat = 'webp';
        var initialAllowUpscale = false;
        var initialKeepOriginal = true;

        if (isPro) {
            var savedWidth = Utils.storage.getItem('webp_image_paster_last_width', null);
            if (savedWidth !== null) {
                initialWidth = parseInt(savedWidth, 10);
            }
            var savedQuality = Utils.storage.getItem('webp_image_paster_last_quality', null);
            if (savedQuality !== null) {
                initialQuality = parseInt(savedQuality, 10);
            }
            var savedFormat = Utils.storage.getItem('webp_image_paster_last_format', null);
            if (savedFormat !== null) {
                initialFormat = savedFormat;
            }
            var savedUpscale = Utils.storage.getItem('webp_image_paster_last_allow_upscale', null);
            if (savedUpscale !== null) {
                initialAllowUpscale = (savedUpscale === 'true');
            }
            var savedKeepOriginal = Utils.storage.getItem('webp_image_paster_last_keep_orig_if_larger', null);
            if (savedKeepOriginal !== null) {
                initialKeepOriginal = (savedKeepOriginal === 'true');
            }
        }

        var isAvifSupported = Utils.isFormatSupported('avif');
        if (initialFormat === 'avif' && !isAvifSupported) {
            initialFormat = 'webp';
        }

        var stateFormat = useState(isPro ? initialFormat : 'orig');
        var selectedFormat = stateFormat[0];
        var setSelectedFormat = stateFormat[1];

        var stateWidth = useState(isPro ? initialWidth : 0);
        var selectedWidth = stateWidth[0];
        var setSelectedWidth = stateWidth[1];

        var stateQuality = useState(isPro ? initialQuality : 85);
        var selectedQuality = stateQuality[0];
        var setSelectedQuality = stateQuality[1];

        var stateQualityInput = useState(isPro ? initialQuality : 85);
        var qualityInput = stateQualityInput[0];
        var setQualityInput = stateQualityInput[1];

        var stateOrigWidth = useState(0);
        var origWidth = stateOrigWidth[0];
        var setOrigWidth = stateOrigWidth[1];

        var stateAllowUpscale = useState(isPro ? initialAllowUpscale : false);
        var allowUpscale = stateAllowUpscale[0];
        var setAllowUpscale = stateAllowUpscale[1];

        var stateKeepOriginal = useState(isPro ? initialKeepOriginal : true);
        var keepOriginalIfLarger = stateKeepOriginal[0];
        var setKeepOriginalIfLarger = stateKeepOriginal[1];

        var statePreview = useState('');
        var previewUrl = statePreview[0];
        var setPreviewUrl = statePreview[1];

        var stateFileSize = useState('');
        var fileSizeText = stateFileSize[0];
        var setFileSizeText = stateFileSize[1];

        var stateGalleryThumbnails = useState([]);
        var galleryThumbnails = stateGalleryThumbnails[0];
        var setGalleryThumbnails = stateGalleryThumbnails[1];

        var stateTotalSizeText = useState('');
        var totalSizeText = stateTotalSizeText[0];
        var setTotalSizeText = stateTotalSizeText[1];

        var stateUploading = useState(false);
        var isUploading = stateUploading[0];
        var setIsUploading = stateUploading[1];

        var stateUploadProgress = useState({ current: 0, total: 0 });
        var uploadProgress = stateUploadProgress[0];
        var setUploadProgress = stateUploadProgress[1];

        var stateConvertingHeic = useState(false);
        var isConvertingHeic = stateConvertingHeic[0];
        var setIsConvertingHeic = stateConvertingHeic[1];

        var stateHeicProgress = useState({ current: 0, total: 0 });
        var heicProgress = stateHeicProgress[0];
        var setHeicProgress = stateHeicProgress[1];

        var stateTargetMode = useState('content');
        var targetMode = stateTargetMode[0];
        var setTargetMode = stateTargetMode[1];
        var isFeaturedImageMode = (targetMode === 'featured_image');

        var stateOpen = useState(false);
        var isOpen = stateOpen[0];
        var setIsOpen = stateOpen[1];

        function initBlobs(blobs, wasHeic, currentMode) {
            var activeMode = currentMode || targetMode;
            if (activeMode === 'featured_image' && blobs && blobs.length > 1) {
                blobs = blobs.slice(0, 1);
            }

            setImageBlobs(blobs);
            setIsUploading(false);

            if (blobs.length === 1) {
                var blob = blobs[0];
                var extractedName = '';
                var rawName = (blob && (blob._originalHeicName || blob.name)) ? (blob._originalHeicName || blob.name).replace(/\.[^/.]+$/, '') : '';
                if (rawName.toLowerCase() !== 'image' && rawName.toLowerCase() !== 'blob') {
                    extractedName = Utils.sanitizeFileName(rawName) || rawName;
                }

                setFileName(extractedName);
                if (isPro) {
                    setAltText(extractedName);
                }

                var blobFmt = (wasHeic || (blob && blob._isConvertedFromHeic)) ? 'heic' : Utils.getBlobFormat(blob);
                var isOptimized = (blobFmt !== 'heic') && Utils.isOptimizedFormat(blob);
                setDetectedFormat(blobFmt);

                if (isPro) {
                    if (isOptimized) {
                        setSelectedFormat('orig');
                        setSelectedQuality(100);
                        setQualityInput(100);
                        setSelectedWidth(0);
                    } else {
                        var userQuality = parseInt(Utils.storage.getItem('webp_image_paster_last_quality', '85'), 10);
                        var userWidth = parseInt(Utils.storage.getItem('webp_image_paster_last_width', '0'), 10);
                        var userFormat = Utils.storage.getItem('webp_image_paster_last_format', 'webp');
                        if (userFormat === 'avif' && !isAvifSupported) {
                            userFormat = 'webp';
                        }
                        setSelectedQuality(userQuality);
                        setQualityInput(userQuality);
                        setSelectedWidth(userWidth);
                        setSelectedFormat(userFormat);
                    }
                } else {
                    setSelectedWidth(0);
                    setAllowUpscale(false);
                    if (isOptimized) {
                        setSelectedFormat('orig');
                    } else {
                        setSelectedFormat('webp');
                    }
                }

                var tempImg = new Image();
                var tempUrl = URL.createObjectURL(blob);
                tempImg.onload = function () {
                    var naturalW = tempImg.width;
                    setOrigWidth(naturalW);
                    URL.revokeObjectURL(tempUrl);

                    var isUpscaleAllowed = isPro ? (Utils.storage.getItem('webp_image_paster_last_allow_upscale', 'false') === 'true') : false;
                    if (!isUpscaleAllowed && naturalW > 0) {
                        setSelectedWidth(function (prevW) {
                            return prevW > naturalW ? 0 : prevW;
                        });
                    }
                };
                tempImg.onerror = function () {
                    URL.revokeObjectURL(tempUrl);
                };
                tempImg.src = tempUrl;
            } else {
                // 다중 이미지 (갤러리) 모드
                var totalBytes = 0;
                var detectedFmts = [];
                for (var i = 0; i < blobs.length; i++) {
                    totalBytes += (blobs[i]._originalHeicSize || blobs[i].size || 0);
                    var fmt = (wasHeic || blobs[i]._isConvertedFromHeic) ? 'HEIC' : (Utils.getBlobFormat(blobs[i]) || '').toUpperCase();
                    if (fmt && detectedFmts.indexOf(fmt) === -1) {
                        detectedFmts.push(fmt);
                    }
                }
                setDetectedFormat(detectedFmts.join(', '));
                setTotalSizeText(Utils.formatFileSize(totalBytes));

                if (isPro) {
                    var userQualityBulk = parseInt(Utils.storage.getItem('webp_image_paster_last_quality', '85'), 10);
                    var userWidthBulk = parseInt(Utils.storage.getItem('webp_image_paster_last_width', '0'), 10);
                    var userFormatBulk = Utils.storage.getItem('webp_image_paster_last_format', 'webp');
                    if (userFormatBulk === 'avif' && !isAvifSupported) {
                        userFormatBulk = 'webp';
                    }
                    setSelectedQuality(userQualityBulk);
                    setQualityInput(userQualityBulk);
                    setSelectedWidth(userWidthBulk);
                    setSelectedFormat(userFormatBulk);
                } else {
                    setSelectedWidth(0);
                    setSelectedFormat(wasHeic ? 'webp' : 'orig');
                    setAllowUpscale(false);
                }
                setOrigWidth(0);
            }
        }

        // 1. 붙여넣기 및 드래그 앤 드롭 이벤트 리스너 등록
        useEffect(function () {
            if (!Editor || !Editor.attachPasteListeners) {
                return;
            }

            var cleanup = Editor.attachPasteListeners(function (rawBlobs, mode) {
                if (!rawBlobs || rawBlobs.length === 0) {
                    return;
                }

                var currentMode = mode || 'content';
                setTargetMode(currentMode);

                if (currentMode === 'featured_image' && rawBlobs.length > 1) {
                    rawBlobs = rawBlobs.slice(0, 1);
                }

                var hasHeic = false;
                for (var h = 0; h < rawBlobs.length; h++) {
                    if (Utils.isHeic(rawBlobs[h])) {
                        hasHeic = true;
                        break;
                    }
                }

                if (hasHeic) {
                    setIsOpen(true);
                    setIsConvertingHeic(true);
                    setHeicProgress({ current: 0, total: rawBlobs.length });

                    Utils.convertHeicBlobs(rawBlobs, function (completed, total) {
                        setHeicProgress({ current: completed, total: total });
                    }).then(function (convertedBlobs) {
                        setIsConvertingHeic(false);
                        initBlobs(convertedBlobs, true, currentMode);
                    }).catch(function (err) {
                        setIsConvertingHeic(false);
                        setIsOpen(false);
                        alert(__('Failed to convert HEIC image: ', 'webp-image-paster') + (err ? err.message : ''));
                    });
                } else {
                    initBlobs(rawBlobs, false, currentMode);
                    setIsOpen(true);
                }
            });

            return cleanup;
        }, [isPro, isAvifSupported]);

        // 2. 단일 이미지 실시간 미리보기 생성
        useEffect(function () {
            if (!imageBlobs || imageBlobs.length === 0 || isGalleryMode || !isOpen) {
                return;
            }

            var singleBlob = imageBlobs[0];
            var timer = setTimeout(function () {
                Processor.generatePreview(singleBlob, {
                    width: selectedWidth,
                    quality: isPro ? selectedQuality : 85,
                    format: selectedFormat,
                    detectedFormat: detectedFormat,
                    keepOriginalIfLarger: keepOriginalIfLarger
                }, function (result) {
                    if (result.url) {
                        setPreviewUrl(function (prev) {
                            if (prev && prev.indexOf('blob:') === 0) {
                                URL.revokeObjectURL(prev);
                            }
                            return result.url;
                        });
                    }
                    if (result.sizeText !== undefined) {
                        setFileSizeText(result.sizeText);
                    }
                });
            }, 300);

            return function () {
                clearTimeout(timer);
            };
        }, [imageBlobs, selectedWidth, selectedQuality, selectedFormat, detectedFormat, isOpen, isPro, isGalleryMode, keepOriginalIfLarger]);

        // 3. 다중 이미지(갤러리) 실시간 미리보기 및 용량 계산
        useEffect(function () {
            if (!isGalleryMode || !isOpen || !imageBlobs || imageBlobs.length === 0) {
                return;
            }

            var timer = setTimeout(function () {
                Processor.generateMultiPreview(imageBlobs, {
                    width: selectedWidth,
                    quality: isPro ? selectedQuality : 85,
                    format: selectedFormat,
                    allowUpscale: allowUpscale,
                    keepOriginalIfLarger: keepOriginalIfLarger
                }, function (result) {
                    if (result && result.thumbnails) {
                        setGalleryThumbnails(function (prev) {
                            if (prev) {
                                for (var p = 0; p < prev.length; p++) {
                                    if (prev[p] && prev[p].url && prev[p].url.indexOf('blob:') === 0) {
                                        URL.revokeObjectURL(prev[p].url);
                                    }
                                }
                            }
                            return result.thumbnails;
                        });
                    }
                    if (result && result.totalSizeText) {
                        setTotalSizeText(result.totalSizeText);
                    }
                });
            }, 300);

            return function () {
                clearTimeout(timer);
            };
        }, [imageBlobs, selectedWidth, selectedQuality, selectedFormat, allowUpscale, keepOriginalIfLarger, isGalleryMode, isOpen, isPro]);

        function handleFileNameChange(val) {
            var prevName = fileName;
            var altSanitized = Utils.sanitizeFileName(altText);
            setFileName(val);

            if (isPro) {
                var shouldSyncAlt = !altText || altText === prevName || altSanitized === prevName;
                if (shouldSyncAlt) {
                    setAltText(val);
                }
            }
        }

        function handleAltTextChange(val) {
            var prevAlt = altText;
            var prevSanitized = Utils.sanitizeFileName(prevAlt);
            setAltText(val);

            if (isPro) {
                var shouldSyncName = !fileName || fileName === prevAlt || fileName === prevSanitized;
                if (shouldSyncName) {
                    setFileName(Utils.sanitizeFileName(val));
                }
            }
        }

        function handleWidthSelect(w) {
            setSelectedWidth(w);
            if (isPro) {
                Utils.storage.setItem('webp_image_paster_last_width', w);
            }
        }

        function handleUpscaleToggle(val) {
            setAllowUpscale(val);
            if (isPro) {
                Utils.storage.setItem('webp_image_paster_last_allow_upscale', val ? 'true' : 'false');
            }
            if (!val && origWidth > 0 && selectedWidth > origWidth) {
                handleWidthSelect(0);
            }
        }

        function handleKeepOriginalToggle(val) {
            setKeepOriginalIfLarger(val);
            if (isPro) {
                Utils.storage.setItem('webp_image_paster_last_keep_orig_if_larger', val ? 'true' : 'false');
            }
        }

        function handleQualitySelect(q) {
            setSelectedQuality(q);
            setQualityInput(q);
            if (isPro) {
                Utils.storage.setItem('webp_image_paster_last_quality', q);
            }
        }

        function handleFormatSelect(f) {
            setSelectedFormat(f);
            if (isPro) {
                Utils.storage.setItem('webp_image_paster_last_format', f);
            }
        }

        function handleConfirm() {
            if (isGalleryMode) {
                setIsUploading(true);
                setUploadProgress({ current: 0, total: imageBlobs.length });

                var finalQualityBulk = isPro ? selectedQuality : 85;

                Processor.processMultipleImages(imageBlobs, {
                    width: selectedWidth,
                    quality: finalQualityBulk,
                    format: selectedFormat,
                    allowUpscale: allowUpscale,
                    keepOriginalIfLarger: keepOriginalIfLarger
                }, function (processedItems) {
                    Editor.uploadAndInsertGallery(processedItems, function (current, total) {
                        setUploadProgress({ current: current, total: total });
                    }).then(function () {
                        setIsUploading(false);
                        setIsOpen(false);
                    }).catch(function () {
                        setIsUploading(false);
                    });
                });
            } else {
                if (!fileName) {
                    alert(__('Please enter a file name.', 'webp-image-paster'));
                    return;
                }

                setIsUploading(true);
                var singleBlob = imageBlobs[0];
                var finalAlt = isPro ? altText : fileName;
                var finalQualitySingle = isPro ? selectedQuality : 85;

                Processor.processImage(singleBlob, {
                    name: fileName,
                    alt: finalAlt,
                    width: selectedWidth,
                    quality: finalQualitySingle,
                    format: selectedFormat,
                    allowUpscale: allowUpscale,
                    keepOriginalIfLarger: keepOriginalIfLarger
                }, function (convertedBlob, cleanFileName, cleanAlt) {
                    var uploadPromise = isFeaturedImageMode
                        ? Editor.uploadAndSetFeaturedImage(convertedBlob, cleanFileName, cleanAlt)
                        : Editor.uploadAndInsert(convertedBlob, cleanFileName, cleanAlt);

                    uploadPromise.then(function () {
                        setIsUploading(false);
                        setIsOpen(false);
                    }).catch(function () {
                        setIsUploading(false);
                    });
                });
            }
        }

        if (!isOpen) {
            return null;
        }

        if (isConvertingHeic) {
            var heicMessage = heicProgress.total > 1
                ? __('Converting HEIC images (%d/%d)...', 'webp-image-paster').replace('%d', heicProgress.current).replace('%d', heicProgress.total)
                : __('Converting HEIC image...', 'webp-image-paster');

            return el(
                Modal,
                {
                    title: __('WebP Image Paster', 'webp-image-paster'),
                    overlayClassName: 'webp-paster-modal-overlay',
                    onRequestClose: function () {
                        setIsConvertingHeic(false);
                        setIsOpen(false);
                    },
                    style: { width: '400px', maxWidth: '90vw' }
                },
                el('div', {
                    style: {
                        padding: '30px 16px',
                        textAlign: 'center',
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        gap: '12px'
                    }
                },
                    Spinner ? el(Spinner, null) : el('div', { className: 'components-spinner' }),
                    el('div', { style: { fontSize: '14px', fontWeight: '600', color: '#1e1e1e' } }, heicMessage),
                    el('div', { style: { fontSize: '12px', color: '#666' } },
                        __('Optimizing HEIC photo for web display...', 'webp-image-paster')
                    ),
                    el(Button, {
                        isSecondary: true,
                        isSmall: true,
                        style: { marginTop: '8px' },
                        onClick: function () {
                            setIsConvertingHeic(false);
                            setIsOpen(false);
                        }
                    }, __('Cancel', 'webp-image-paster'))
                )
            );
        }

        var modalChildren = [];

        // UI 1. 상단 미리보기
        if (isGalleryMode) {
            // 다중 이미지 (갤러리) 썸네일 그리드
            var thumbElements = [];
            for (var tIdx = 0; tIdx < galleryThumbnails.length; tIdx++) {
                var thumb = galleryThumbnails[tIdx];
                thumbElements.push(
                    el('div', {
                        key: 'thumb-' + tIdx,
                        style: {
                            display: 'flex',
                            flexDirection: 'column',
                            alignItems: 'center',
                            width: '110px',
                            padding: '6px',
                            backgroundColor: '#fff',
                            border: '1px solid #ddd',
                            borderRadius: '4px',
                            boxSizing: 'border-box',
                            flexShrink: 0
                        }
                    },
                        el('img', {
                            src: thumb.url,
                            style: { width: '96px', height: '70px', objectFit: 'cover', borderRadius: '3px' }
                        }),
                        el('span', {
                            style: {
                                fontSize: '10px',
                                color: '#555',
                                marginTop: '4px',
                                width: '96px',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                                textAlign: 'center'
                            },
                            title: thumb.name
                        }, thumb.name),
                        el('span', { style: { fontSize: '11px', color: '#007cba', fontWeight: 'bold', marginTop: '3px' } }, thumb.sizeText),
                        thumb.formatBadge ? el('span', {
                            style: {
                                fontSize: '9px',
                                padding: '1px 4px',
                                marginTop: '2px',
                                backgroundColor: thumb.isReverted ? '#e7f5fa' : '#f0f0f1',
                                color: thumb.isReverted ? '#007cba' : '#555',
                                borderRadius: '3px',
                                fontWeight: '500',
                                textAlign: 'center',
                                maxWidth: '96px',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                                display: 'inline-block'
                            }
                        }, thumb.formatBadge) : null
                    )
                );
            }

            modalChildren.push(
                el('div', {
                    key: 'gallery-preview-box',
                    style: {
                        marginBottom: '10px',
                        padding: '10px',
                        backgroundColor: '#f9f9f9',
                        border: '1px solid #eee',
                        borderRadius: '6px'
                    }
                },
                    el('div', {
                        style: {
                            display: 'flex',
                            gap: '8px',
                            overflowX: 'auto',
                            paddingBottom: '6px'
                        }
                    }, thumbElements),
                    el('div', {
                        style: {
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                            marginTop: '6px',
                            fontSize: '12px',
                            color: '#333',
                            fontWeight: '500'
                        }
                    },
                        el('span', null, imageBlobs.length + __(' images', 'webp-image-paster')),
                        el('span', { style: { color: '#007cba', fontWeight: 'bold' } }, __('Est. Size: ', 'webp-image-paster') + totalSizeText)
                    )
                )
            );
        } else if (previewUrl) {
            // 단일 이미지 미리보기
            modalChildren.push(
                el('div', {
                    key: 'preview-box',
                    style: {
                        height: '220px',
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        marginBottom: '10px',
                        padding: '8px',
                        backgroundColor: '#f9f9f9',
                        border: '1px solid #eee',
                        borderRadius: '6px',
                        textAlign: 'center',
                        boxSizing: 'border-box'
                    }
                },
                    el('img', {
                        src: previewUrl,
                        style: { maxHeight: '180px', maxWidth: '360px', objectFit: 'contain', borderRadius: '4px', border: '1px solid #ddd' }
                    }),
                    fileSizeText ? el('div', { style: { marginTop: '6px', fontSize: '12px', color: '#007cba', fontWeight: 'bold' } }, __('Est. Size: ', 'webp-image-paster') + fileSizeText) : null
                )
            );
        }

        // Featured Image 모드 안내 배너
        if (isFeaturedImageMode) {
            modalChildren.push(
                el('div', {
                    key: 'featured-image-notice',
                    style: {
                        padding: '8px 12px',
                        backgroundColor: '#e7f5fa',
                        borderLeft: '4px solid #00a0d2',
                        borderRadius: '3px',
                        marginBottom: '10px',
                        fontSize: '12px',
                        color: '#1e3a5f',
                        fontWeight: '500'
                    }
                },
                    __('⭐ This image will be converted and set as the Featured Image.', 'webp-image-paster')
                )
            );
        }

        // UI 2. 파일 형식 선택 버튼 그룹
        var origLabel = __('ORIG', 'webp-image-paster');
        if (detectedFormat && !isGalleryMode) {
            if (detectedFormat.toLowerCase() === 'heic' || detectedFormat.toLowerCase() === 'heif') {
                origLabel = __('ORIG', 'webp-image-paster') + ' (HEIC -> JPG)';
            } else {
                origLabel = __('ORIG', 'webp-image-paster') + ' (' + detectedFormat.toUpperCase() + ')';
            }
        }

        var formatPresets = [
            { label: origLabel, val: 'orig', disabled: false },
            { label: 'WEBP', val: 'webp', disabled: false },
            { label: 'PNG', val: 'png', disabled: false }
        ];

        if (isPro) {
            formatPresets.push({
                label: isAvifSupported ? 'AVIF' : __('AVIF (Not Supported)', 'webp-image-paster'),
                val: 'avif',
                disabled: !isAvifSupported
            });
        }

        var formatButtons = [];
        for (var fIdx = 0; fIdx < formatPresets.length; fIdx++) {
            (function (preset) {
                formatButtons.push(
                    el(Button, {
                        key: 'fmt-' + preset.val,
                        isPrimary: selectedFormat === preset.val,
                        isSecondary: selectedFormat !== preset.val,
                        isSmall: true,
                        disabled: preset.disabled,
                        onClick: function () {
                            if (!preset.disabled) {
                                handleFormatSelect(preset.val);
                            }
                        },
                        style: { flex: '1', textAlign: 'center' }
                    }, preset.label)
                );
            })(formatPresets[fIdx]);
        }

        modalChildren.push(
            el('div', { key: 'format-section', style: { marginBottom: '12px' } },
                el('span', { style: { fontWeight: '500', fontSize: '12px', display: 'block', marginBottom: '4px' } }, __('Format:', 'webp-image-paster')),
                el('div', { style: { display: 'flex', gap: '4px', marginBottom: '6px' } }, formatButtons),
                // [신규] 용량 증가 방지 체크박스
                el(CheckboxControl, {
                    label: __('Keep original format if converted file size is larger', 'webp-image-paster'),
                    checked: keepOriginalIfLarger,
                    onChange: handleKeepOriginalToggle
                })
            )
        );

        // UI 3. 파일명 & Alt 텍스트 (단일/갤러리 모드 분기)
        if (isGalleryMode) {
            // 갤러리 모드: 자동 네이밍 안내 배너
            modalChildren.push(
                el('div', {
                    key: 'gallery-notice',
                    style: {
                        padding: '8px 12px',
                        backgroundColor: '#e7f5fa',
                        borderLeft: '4px solid #00a0d2',
                        borderRadius: '3px',
                        marginBottom: '10px',
                        fontSize: '12px',
                        color: '#1e3a5f'
                    }
                },
                    __('Original file names and alt texts will be automatically generated for each image.', 'webp-image-paster')
                )
            );
        } else {
            // 단일 모드: 파일명 입력란
            modalChildren.push(
                el('div', { key: 'filename-section', style: { marginBottom: '8px' } },
                    el('div', { style: { display: 'flex', alignItems: 'flex-end', gap: '5px' } },
                        el('div', { style: { flex: '1' } },
                            el(TextControl, {
                                label: __('File Name (no ext):', 'webp-image-paster'),
                                value: fileName,
                                onChange: handleFileNameChange
                            })
                        ),
                        el(Button, {
                            isSecondary: true,
                            onClick: function () { setFileName(''); },
                            style: { marginBottom: '8px', padding: '0 6px', height: '30px', minWidth: 'auto' }
                        }, '✕')
                    )
                )
            );

            // Alt 텍스트 입력란 (Pro 전용)
            if (isPro) {
                modalChildren.push(
                    el('div', { key: 'alt-section', style: { marginBottom: '8px' } },
                        el('div', { style: { display: 'flex', alignItems: 'flex-end', gap: '5px' } },
                            el('div', { style: { flex: '1' } },
                                el(TextControl, {
                                    label: __('Alt Text (Description):', 'webp-image-paster'),
                                    value: altText,
                                    placeholder: __('Entering Alt text automatically generates the file name.', 'webp-image-paster'),
                                    onChange: handleAltTextChange
                                })
                            ),
                            el(Button, {
                                isSecondary: true,
                                onClick: function () { setAltText(''); },
                                style: { marginBottom: '8px', padding: '0 6px', height: '30px', minWidth: 'auto' }
                            }, '✕')
                        )
                    )
                );
            }
        }

        // UI 4. 너비 선택
        var origWidthLabel = __('Orig', 'webp-image-paster');
        if (!isGalleryMode && origWidth > 0) {
            origWidthLabel = __('Orig', 'webp-image-paster') + ' (' + origWidth + 'px)';
        }

        var widthPresets = [
            { label: origWidthLabel, val: 0 },
            { label: '360px', val: 360 },
            { label: '540px', val: 540 },
            { label: '720px', val: 720 },
            { label: '1080px', val: 1080 },
            { label: '1440px', val: 1440 }
        ];

        var widthButtons = [];
        for (var wIdx = 0; wIdx < widthPresets.length; wIdx++) {
            (function (preset) {
                var isBtnDisabled = false;
                if (!isGalleryMode && !allowUpscale && preset.val > 0 && origWidth > 0 && preset.val > origWidth) {
                    isBtnDisabled = true;
                }

                widthButtons.push(
                    el(Button, {
                        key: 'w-' + preset.val,
                        isPrimary: selectedWidth === preset.val,
                        isSecondary: selectedWidth !== preset.val,
                        isSmall: true,
                        disabled: isBtnDisabled,
                        onClick: function () {
                            if (!isBtnDisabled) {
                                handleWidthSelect(preset.val);
                            }
                        },
                        style: { flex: '1', textAlign: 'center' }
                    }, preset.label)
                );
            })(widthPresets[wIdx]);
        }

        var customPlaceholder = __('Custom px', 'webp-image-paster');
        if (!isGalleryMode && !allowUpscale && origWidth > 0) {
            customPlaceholder = __('Max ', 'webp-image-paster') + origWidth + 'px';
        }

        modalChildren.push(
            el('div', { key: 'width-section', style: { marginBottom: '8px' } },
                el('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' } },
                    el('span', { style: { fontWeight: '500', fontSize: '12px' } }, __('Width:', 'webp-image-paster')),
                    el('div', { style: { width: '125px' } },
                        el(TextControl, {
                            type: 'number',
                            value: selectedWidth === 0 ? '' : selectedWidth,
                            placeholder: customPlaceholder,
                            onChange: function (val) {
                                var num = parseInt(val, 10);
                                if (isNaN(num)) {
                                    handleWidthSelect(0);
                                } else {
                                    if (!isGalleryMode && !allowUpscale && origWidth > 0 && num > origWidth) {
                                        num = 0;
                                    }
                                    handleWidthSelect(num);
                                }
                            }
                        })
                    )
                ),
                el('div', { style: { display: 'flex', gap: '4px', marginBottom: '6px' } }, widthButtons),
                el(CheckboxControl, {
                    label: __('Allow resizing smaller images to larger sizes', 'webp-image-paster'),
                    checked: allowUpscale,
                    onChange: handleUpscaleToggle
                })
            )
        );

        // UI 5. 품질 선택 (Pro 전용)
        if (isPro) {
            var qualityPresets = [
                { label: '50%', val: 50 },
                { label: '60%', val: 60 },
                { label: '75%', val: 75 },
                { label: '85%', val: 85 },
                { label: '90%', val: 90 },
                { label: '95%', val: 95 }
            ];

            var qualityButtons = [];
            for (var qIdx = 0; qIdx < qualityPresets.length; qIdx++) {
                (function (preset) {
                    qualityButtons.push(
                        el(Button, {
                            key: 'q-' + preset.val,
                            isPrimary: selectedQuality === preset.val,
                            isSecondary: selectedQuality !== preset.val,
                            isSmall: true,
                            onClick: function () { handleQualitySelect(preset.val); },
                            style: { flex: '1', textAlign: 'center' }
                        }, preset.label)
                    );
                })(qualityPresets[qIdx]);
            }

            modalChildren.push(
                el('div', { key: 'quality-section', style: { marginBottom: '8px' } },
                    el('style', { key: 'quality-slider-style' },
                        '.webp-paster-quality-slider .components-base-control { margin-bottom: 0 !important; }' +
                        '.webp-paster-quality-slider .components-range-control__tooltip { bottom: calc(100% + 4px) !important; top: auto !important; }'
                    ),
                    el('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' } },
                        el('span', { style: { fontWeight: '500', fontSize: '12px' } },
                            __('Quality:', 'webp-image-paster') + ' ' + selectedQuality + '%'
                        ),
                        el('div', { style: { width: '125px' } },
                            el(TextControl, {
                                type: 'number',
                                min: 10,
                                max: 100,
                                step: 1,
                                value: qualityInput !== undefined ? qualityInput : selectedQuality,
                                placeholder: '10 - 100',
                                onChange: function (val) {
                                    setQualityInput(val);
                                    var num = parseInt(val, 10);
                                    if (!isNaN(num) && num >= 10 && num <= 100) {
                                        setSelectedQuality(num);
                                        if (isPro) {
                                            Utils.storage.setItem('webp_image_paster_last_quality', num);
                                        }
                                    }
                                },
                                onBlur: function () {
                                    var num = parseInt(qualityInput, 10);
                                    if (isNaN(num) || num < 10) {
                                        num = 10;
                                    } else if (num > 100) {
                                        num = 100;
                                    }
                                    handleQualitySelect(num);
                                }
                            })
                        )
                    ),
                    el('div', { style: { display: 'flex', gap: '4px', marginBottom: '4px' } }, qualityButtons),
                    el('div', {
                        className: 'webp-paster-quality-slider-row',
                        style: { display: 'flex', alignItems: 'center', gap: '6px' }
                    },
                        el(Button, {
                            isSecondary: true,
                            isSmall: true,
                            disabled: selectedQuality <= 10,
                            onClick: function () {
                                handleQualitySelect(Math.max(10, selectedQuality - 1));
                            },
                            style: {
                                minWidth: '28px',
                                height: '28px',
                                padding: '0',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: '16px',
                                fontWeight: '600',
                                lineHeight: '1',
                                borderRadius: '3px'
                            },
                            title: __('Decrease by 1%', 'webp-image-paster')
                        }, '−'),
                        el('div', {
                            className: 'webp-paster-quality-slider',
                            style: { flex: '1' }
                        },
                            el(RangeControl, {
                                value: selectedQuality,
                                onChange: function (val) {
                                    if (typeof val === 'number') {
                                        handleQualitySelect(val);
                                    }
                                },
                                min: 10,
                                max: 100,
                                step: 1,
                                withInputField: false
                            })
                        ),
                        el(Button, {
                            isSecondary: true,
                            isSmall: true,
                            disabled: selectedQuality >= 100,
                            onClick: function () {
                                handleQualitySelect(Math.min(100, selectedQuality + 1));
                            },
                            style: {
                                minWidth: '28px',
                                height: '28px',
                                padding: '0',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                fontSize: '16px',
                                fontWeight: '600',
                                lineHeight: '1',
                                borderRadius: '3px'
                            },
                            title: __('Increase by 1%', 'webp-image-paster')
                        }, '+')
                    )
                )
            );
        } else {
            // Free 버전 Pro 안내 문구
            modalChildren.push(
                el('p', { key: 'pro-notice', style: { marginBottom: '8px', color: '#666', fontSize: '11px' } },
                    __('🔒 Custom Alt text, quality slider, and option memory are available for Pro users.', 'webp-image-paster')
                )
            );
        }

        // UI 6. 하단 액션 버튼
        var confirmButtonText = __('Confirm', 'webp-image-paster');
        if (isUploading) {
            if (isFeaturedImageMode) {
                confirmButtonText = __('Setting Featured Image...', 'webp-image-paster');
            } else if (isGalleryMode) {
                confirmButtonText = __('Uploading (%d/%d)...', 'webp-image-paster')
                    .replace('%d', uploadProgress.current)
                    .replace('%d', uploadProgress.total || imageBlobs.length);
            } else {
                confirmButtonText = __('Uploading...', 'webp-image-paster');
            }
        } else if (isFeaturedImageMode) {
            confirmButtonText = __('Set as Featured Image', 'webp-image-paster');
        } else if (isGalleryMode) {
            confirmButtonText = __('Upload as Gallery', 'webp-image-paster');
        }

        modalChildren.push(
            el('div', { key: 'actions-section', style: { display: 'flex', justifyContent: 'flex-end', gap: '8px', borderTop: '1px solid #eee', paddingTop: '8px' } },
                el(Button, {
                    isSecondary: true,
                    disabled: isUploading,
                    onClick: function () { setIsOpen(false); }
                }, __('Cancel', 'webp-image-paster')),
                el(Button, {
                    isPrimary: true,
                    isBusy: isUploading,
                    disabled: isUploading,
                    onClick: handleConfirm
                }, confirmButtonText)
            )
        );

        var modalTitle = isPro ? __('Upload Image (Pro)', 'webp-image-paster') : __('Upload Image', 'webp-image-paster');
        if (isFeaturedImageMode) {
            modalTitle = isPro ? __('Set Featured Image (Pro)', 'webp-image-paster') : __('Set Featured Image', 'webp-image-paster');
        } else if (isGalleryMode) {
            var titlePattern = isPro ? __('Upload Images as Gallery (%d images) (Pro)', 'webp-image-paster') : __('Upload Images as Gallery (%d images)', 'webp-image-paster');
            modalTitle = titlePattern.replace('%d', imageBlobs.length);
        }

        return el(
            Modal,
            {
                title: modalTitle,
                overlayClassName: 'webp-paster-modal-overlay',
                onRequestClose: function () {
                    if (!isUploading) {
                        setIsOpen(false);
                    }
                },
                style: { width: '600px', maxWidth: '90vw' }
            },
            el('div', { style: { padding: '5px 0' } }, modalChildren)
        );
    }

    // 하위 호환성을 위한 WebpImagePasterCore 프록시 객체 제공
    window.WebpImagePasterCore = {
        formatFileSize: Utils.formatFileSize,
        sanitizeFileName: Utils.sanitizeFileName,
        sanitizeAltText: Utils.sanitizeAltText,
        isFormatSupported: Utils.isFormatSupported,
        getBlobFormat: Utils.getBlobFormat,
        isOptimizedFormat: Utils.isOptimizedFormat,
        attachPasteListeners: Editor.attachPasteListeners,
        processAndUpload: function (blob, name, alt, widthVal, qualityVal, formatVal) {
            Processor.processImage(blob, {
                name: name,
                alt: alt,
                width: widthVal,
                quality: qualityVal,
                format: formatVal
            }, function (convertedBlob, cleanFileName, cleanAlt) {
                Editor.uploadAndInsert(convertedBlob, cleanFileName, cleanAlt);
            });
        }
    };

    return WebpImagePasterModal;
})();
