jQuery(document).ready(function($) {
    let mediaUploader;

    $(document).on('click', '.cv-upload-image', function(e) {
        e.preventDefault();
        const button = $(this);
        const imageIdInput = button.siblings('input[type="hidden"]');
        const imagePreview = button.siblings('.cv-image-preview');
        const removeButton = button.siblings('.cv-remove-image');

        if (mediaUploader) {
            mediaUploader.open();
            return;
        }
        mediaUploader = wp.media({
            title: 'Choose Product Image',
            button: {
                text: 'Set as product image'
            },
            multiple: false
        });

        mediaUploader.on('select', function() {
            const attachment = mediaUploader.state().get('selection').first().toJSON();
            imageIdInput.val(attachment.id);
            const imageUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
            imagePreview.html('<img src="' + imageUrl + '" alt="" style="max-width: 150px; height: auto;" />');
            removeButton.show();
        });
        mediaUploader.open();
    });

    $(document).on('click', '.cv-remove-image', function(e) {
        e.preventDefault();
        const button = $(this);
        const imageIdInput = button.siblings('input[type="hidden"]');
        const imagePreview = button.siblings('.cv-image-preview');
        imageIdInput.val('');
        imagePreview.html('');
        button.hide();
    });
    function toggleSubscriptionFields() {
        const $billingPeriod = $('#subscription_billing_period');
        const $downloadNumber = $('#subscription_per_download');
        const $billingPeriodRow = $billingPeriod.closest('tr');
        const $downloadNumberRow = $downloadNumber.closest('tr');

        const billingPeriodValue = $billingPeriod.val()?.trim();
        const downloadNumberValue = parseInt($downloadNumber.val()) || 0;

        $billingPeriod.removeAttr('required').removeClass('invalid-field');
        $downloadNumber.removeAttr('required').removeClass('invalid-field');

        if (!billingPeriodValue && downloadNumberValue <= 0) {
            $billingPeriodRow.show();
            $downloadNumberRow.show();
            $billingPeriod.attr('required', true);
            return;
        }

        if (billingPeriodValue) {
            $billingPeriodRow.show();
            $downloadNumberRow.hide();
            $downloadNumber.val('');
            $billingPeriod.attr('required', true);
            return;
        }

        if (downloadNumberValue > 0) {
            $billingPeriodRow.hide();
            $billingPeriod.val('');
            $downloadNumberRow.show();
            $downloadNumber.attr('required', true);
            return;
        }
    }

    function validateSubscriptionFields() {

        const $billingPeriod = $('#subscription_billing_period');
        const $downloadNumber = $('#subscription_per_download');

        // If neither field exists on this page, skip validation
        if (!$billingPeriod.length && !$downloadNumber.length) {
            return true;
        }

        const billingPeriodValue = $billingPeriod.val().trim();
        const downloadNumberValue = parseInt($downloadNumber.val()) || 0;

        const isValid = billingPeriodValue || downloadNumberValue > 0;

        if (!isValid) {
            if ($billingPeriod.is(':visible')) {
                $billingPeriod.addClass('invalid-field');
            }
            if ($downloadNumber.is(':visible')) {
                $downloadNumber.addClass('invalid-field');
            }

            showValidationMessage('Please select either a billing period or enter a download number.');
            return false;
        }

        return true;
    }

    function showValidationMessage(message) {
        $('.subscription-validation-error').remove();

        const errorHtml = `
            <tr class="subscription-validation-error">
                <td colspan="2">
                    <div class="notice notice-error inline">
                        <p style="color: #d63638; font-weight: 500;">${message}</p>
                    </div>
                </td>
            </tr>
        `;

        $('#subscription_per_download').closest('tr').after(errorHtml);
    }

    // Initial fix for zero value
    const $downloadField = $('#subscription_per_download');
    if ($downloadField.val() === '0') {
        $downloadField.val('');
    }

    toggleSubscriptionFields();

    $('#subscription_billing_period, #subscription_per_download').on('input change keyup', function () {
        setTimeout(() => {
            toggleSubscriptionFields();
            $('.subscription-validation-error').remove();
        }, 10);
    });

    $('#subscription_billing_period, #subscription_per_download').on('focus', function () {
        $(this).removeClass('invalid-field');
        $('.subscription-validation-error').remove();
    });

    $('form').on('submit', function (e) {
        if (!validateSubscriptionFields()) {
            e.preventDefault();
        }
    });

    $('._subscription_billing_period_field').hide();

    // Inject CSS styles if not already present
    if (!document.getElementById('subscription-validation-styles')) {
        const style = document.createElement('style');
        style.id = 'subscription-validation-styles';
        style.textContent = `
            .invalid-field {
                border-color: #d63638 !important;
                box-shadow: 0 0 0 1px #d63638 !important;
            }
            .subscription-validation-error .notice {
                margin: 5px 0 !important;
                padding: 8px 12px !important;
            }
        `;
        document.head.appendChild(style);
    }

});
