jQuery(document).ready(function ($) {
    if (wcv_general.require_featured_image) {
        $('.product-feat-image-upload')
            .find('.blue-title')
            .append(' <span class="required">*</span>');
    }

    if (wcv_general.require_gallery_image) {
        $('#product-imgs-gallery-parent')
            .find('.blue-title')
            .append(' <span class="required">*</span>');
    }

    const requiredFields = $(
        'input[required], select[required], textarea[required]'
    );

    requiredFields.each(function () {
        const $field = $(this);
        const id = $field.attr('id');

        const label = $('label[for="' + id + '"]');
        if (label.length) {
            label.append(' <span class="required">*</span>');
        }
    });

    // Initialize modal once
    const modalElement = document.getElementById('wcv-product-thumbnail-popup');
    let modal = null;
    let currentZoom = 1;
    const zoomStep = 0.25;
    const minZoom = 0.25;
    const maxZoom = 3;

    if (modalElement && window.Ink && window.Ink.UI && window.Ink.UI.Modal_1) {
        modal = new window.Ink.UI.Modal_1(modalElement);
    }

    // Only register event handlers if modal element exists
    if (modalElement) {
        $('.open-product-thumb-modal').on('click', function (e) {
            e.preventDefault();
            const href = $(this).data('href');
            if (href) {
                const modalContentImage = modalElement.querySelector(
                    '#wcv-product-thumbnail-popup-image'
                );
                if (modalContentImage) {
                    modalContentImage.src = href;
                    currentZoom = 1;
                    modalContentImage.style.transform = 'scale(1)';
                    if (modal) {
                        modal.open();
                    }
                }
            }
        });

        // Zoom in button
        $('#wcv-zoom-in').on('click', function () {
            const modalContentImage = modalElement.querySelector(
                '#wcv-product-thumbnail-popup-image'
            );
            if (modalContentImage && currentZoom < maxZoom) {
                currentZoom += zoomStep;
                modalContentImage.style.transform = `scale(${currentZoom})`;
                modalContentImage.style.cursor = 'zoom-out';
            }
        });

        // Zoom out button
        $('#wcv-zoom-out').on('click', function () {
            const modalContentImage = modalElement.querySelector(
                '#wcv-product-thumbnail-popup-image'
            );
            if (modalContentImage && currentZoom > minZoom) {
                currentZoom -= zoomStep;
                modalContentImage.style.transform = `scale(${currentZoom})`;
                if (currentZoom === 1) {
                    modalContentImage.style.cursor = 'zoom-in';
                }
            }
        });

        // Reset zoom button
        $('#wcv-zoom-reset').on('click', function () {
            const modalContentImage = modalElement.querySelector(
                '#wcv-product-thumbnail-popup-image'
            );
            if (modalContentImage) {
                currentZoom = 1;
                modalContentImage.style.transform = 'scale(1)';
                modalContentImage.style.cursor = 'zoom-in';
            }
        });
    }

    // Handle pro file uploader (for images and other file types)
    // Handle image uploader add button
    $(document).on('click', '[class*="wcv-pro-file-uploader-add"]', function (e) {
        e.preventDefault();
        const $button = $(this);
        const classes = $button.attr('class').split(' ');
        let metaKey = '';

        // Extract meta key from class name (e.g., wcv-pro-file-uploader-add_wcv_image_id)
        classes.forEach(function (className) {
            if (className.indexOf('wcv-pro-file-uploader-add') === 0) {
                metaKey = className.replace('wcv-pro-file-uploader-add', '');
            }
        });

        if (!metaKey) {
            return false;
        }

        const $input = $('input#' + metaKey);
        if (!$input.length) {
            return false;
        }

        proFileUploader($input, metaKey, 'image');
        return false;
    });

    // Handle image uploader delete button
    $(document).on('click', '[class*="wcv-pro-file-uploader-delete"]', function (e) {
        e.preventDefault();
        const $button = $(this);
        const classes = $button.attr('class').split(' ');
        let metaKey = '';

        // Extract meta key from class name
        classes.forEach(function (className) {
            if (className.indexOf('wcv-pro-file-uploader-delete') === 0) {
                metaKey = className.replace('wcv-pro-file-uploader-delete', '');
            }
        });

        if (!metaKey) {
            return false;
        }

        const $input = $('input#' + metaKey);
        const $container = $('.wcv-file-uploader' + metaKey);

        // Clear the container
        $container.html('');
        $input.val('0');

        // Show add button, hide delete button
        $('.wcv-pro-file-uploader-add' + metaKey).removeClass('hidden');
        $('.wcv-pro-file-uploader-delete' + metaKey).addClass('hidden');

        // Clear validation message
        const msgId = $input.data('msg-id');
        if (msgId) {
            $('#' + msgId).html('').removeClass('parsley-error');
        }

        // Trigger change event for validation
        $input.trigger('change');

        return false;
    });

    // Handle file uploader add button (for non-image files)
    $(document).on('click', '[class*="wcv-file-uploader-add"]', function (e) {
        e.preventDefault();
        const $button = $(this);
        const classes = $button.attr('class').split(' ');
        let metaKey = '';

        // Extract meta key from class name (e.g., wcv-file-uploader-add_wcv_file_id)
        classes.forEach(function (className) {
            if (className.indexOf('wcv-file-uploader-add') === 0 && className !== 'wcv-file-uploader-add') {
                metaKey = className.replace('wcv-file-uploader-add', '');
            }
        });

        if (!metaKey) {
            return false;
        }

        const $input = $('input#' + metaKey);
        if (!$input.length) {
            return false;
        }

        const fileType = $input.data('type') || 'file';
        proFileUploader($input, metaKey, fileType);
        return false;
    });

    // Handle file uploader delete button (for non-image files)
    $(document).on('click', '[class*="wcv-file-uploader-delete"]', function (e) {
        e.preventDefault();
        const $button = $(this);
        const classes = $button.attr('class').split(' ');
        let metaKey = '';

        // Extract meta key from class name
        classes.forEach(function (className) {
            if (className.indexOf('wcv-file-uploader-delete') === 0 && className !== 'wcv-file-uploader-delete') {
                metaKey = className.replace('wcv-file-uploader-delete', '');
            }
        });

        if (!metaKey) {
            return false;
        }

        const $input = $('input#' + metaKey);
        const $container = $('.wcv-file-uploader' + metaKey);
        const fileType = $input.data('type') || 'file';

        // Clear the container
        $container.html('');
        $input.val('0');

        // Show add button, hide delete button
        $('.wcv-file-uploader-add' + metaKey).removeClass('hidden');
        $('.wcv-file-uploader-delete' + metaKey).addClass('hidden');

        // Clear validation message
        const msgId = $input.data('msg-id');
        if (msgId) {
            $('#' + msgId).html('').removeClass('parsley-error');
        }

        // Trigger change event for validation
        $input.trigger('change');

        return false;
    });

    /**
     * Pro file uploader function
     * Handles WordPress media library integration for file uploads
     *
     * @param {jQuery} $input The hidden input field
     * @param {string} metaKey The meta key for the field
     * @param {string} fileType The type of file (image, video, audio, document, file)
     */
    function proFileUploader($input, metaKey, fileType) {
        // jQuery data() handles both data-window_title and data-window-title
        const windowTitle = $input.data('window_title') || $input.data('window-title') || 'Select a File';
        const saveButton = $input.data('save_button') || $input.data('save-button') || 'Add File';
        const $container = $('.wcv-file-uploader' + metaKey);

        // Check if wp.media is available
        if (typeof wp === 'undefined' || typeof wp.media === 'undefined') {
            return;
        }

        // Configure media library based on file type
        const mediaConfig = {
            title: windowTitle,
            button: {
                text: saveButton,
            },
            multiple: false,
        };

        // Add library filter for specific file types
        if (fileType === 'image') {
            mediaConfig.library = {
                type: 'image',
            };
        } else if (fileType === 'video') {
            mediaConfig.library = {
                type: 'video',
            };
        } else if (fileType === 'audio') {
            mediaConfig.library = {
                type: 'audio',
            };
        }

        // Create media uploader instance (create new instance each time to avoid scope issues)
        const mediaUploader = wp.media(mediaConfig);

        // Handle file selection
        mediaUploader.on('select', function () {
            const attachment = mediaUploader.state().get('selection').first().toJSON();
            const attachmentId = attachment.id;
            const attachmentUrl = attachment.url;

            if (!attachmentId || !attachmentUrl) {
                return;
            }

            // Update hidden input
            $input.val(attachmentId);

            // Update UI based on file type - use jQuery to create elements safely
            let $fileDisplay;

            if (fileType === 'image') {
                // For images, show thumbnail or full image
                const thumbnailUrl = attachment.sizes && attachment.sizes.thumbnail
                    ? attachment.sizes.thumbnail.url
                    : attachmentUrl;
                const $img = $('<img>')
                    .attr('src', thumbnailUrl)
                    .attr('alt', attachment.alt || '')
                    .css({
                        'max-width': '100%',
                        'margin-bottom': '16px'
                    });
                $fileDisplay = $('<div>').append($img);
            } else if (fileType === 'video') {
                // For videos, use HTML5 video element (matching PHP do_shortcode output)
                const $video = $('<video>')
                    .attr('src', attachmentUrl)
                    .attr('controls', true)
                    .css({
                        'max-width': '100%',
                        'margin-bottom': '16px'
                    });
                $fileDisplay = $('<div>').append($video);
            } else if (fileType === 'audio') {
                // For audio, use HTML5 audio element (matching PHP do_shortcode output)
                const $audio = $('<audio>')
                    .attr('src', attachmentUrl)
                    .attr('controls', true)
                    .css({
                        'max-width': '100%',
                        'margin-bottom': '16px'
                    });
                $fileDisplay = $('<div>').append($audio);
            } else if (fileType === 'document') {
                // For documents, show link - escape URL properly
                const $link = $('<a>')
                    .attr('href', attachmentUrl)
                    .attr('target', '_blank')
                    .text(attachmentUrl);
                $fileDisplay = $('<div>').append($link);
            } else {
                // Default: show readonly input with URL
                const $inputWrapper = $('<div>').addClass('control-group');
                const $control = $('<div>').addClass('control');
                const $urlInput = $('<input>')
                    .attr('type', 'text')
                    .attr('readonly', true)
                    .val(attachmentUrl);
                $control.append($urlInput);
                $inputWrapper.append($control);
                $fileDisplay = $('<div>').append($inputWrapper);
            }

            // Update container safely
            $container.empty().append($fileDisplay);

            // Show delete button, hide add button
            if (fileType === 'image') {
                $('.wcv-pro-file-uploader-add' + metaKey).addClass('hidden');
                $('.wcv-pro-file-uploader-delete' + metaKey).removeClass('hidden');
            } else {
                $('.wcv-file-uploader-add' + metaKey).addClass('hidden');
                $('.wcv-file-uploader-delete' + metaKey).removeClass('hidden');
            }

            // Clear validation message
            const msgId = $input.data('msg-id');
            if (msgId) {
                $('#' + msgId).html('').removeClass('parsley-error');
            }

            // Trigger change event for validation
            $input.trigger('change');
        });

        // Open media uploader
        mediaUploader.open();
    }
});
