jQuery(document).ready(function($) {
    const previewImg = $('#loginlook_logo_preview img');
    const backgroundPreviewImg = $('#loginlook_background_preview img');
    const brandingNotice = $('.loginlook-settings-branding .loginlook-settings-notice');
    const noticeRow = $('.loginlook-notice-row');

    if (brandingNotice.length) {
        if (noticeRow.length) {
            noticeRow.append(brandingNotice);
        } else {
            $('<div class="loginlook-notice-row"></div>')
                .insertAfter('.loginlook-settings-branding')
                .append(brandingNotice);
        }
    }

    // Media uploader for logo
    $('#loginlook_upload_logo').click(function(e) {
        e.preventDefault();
        var custom_uploader = wp.media({
            title: 'Choose Logo',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        custom_uploader.on('select', function() {
            var attachment = custom_uploader.state().get('selection').first().toJSON();
            $('#loginlook_logo_url').val(attachment.url);
            previewImg.attr('src', attachment.url).show();
        });

        custom_uploader.open();
    });

    // Live preview for logo
    $('#loginlook_logo_url').on('input', function() {
        var url = $(this).val();
        if (url) {
            previewImg.attr('src', url).show();
        } else {
            previewImg.hide();
        }
    });

    // Media uploader for background image
    $('#loginlook_upload_background').click(function(e) {
        e.preventDefault();
        var background_uploader = wp.media({
            title: 'Choose Background',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        background_uploader.on('select', function() {
            var attachment = background_uploader.state().get('selection').first().toJSON();
            $('#loginlook_background_image_url').val(attachment.url);
            backgroundPreviewImg.attr('src', attachment.url).show();
        });

        background_uploader.open();
    });

    // Live preview for background image
    $('#loginlook_background_image_url').on('input', function() {
        var url = $(this).val();
        if (url) {
            backgroundPreviewImg.attr('src', url).show();
        } else {
            backgroundPreviewImg.hide();
        }
    });

    // Update preview on width/height change
    $('#loginlook_logo_width, #loginlook_logo_height').on('input', function() {
        var width = $('#loginlook_logo_width').val();
        var height = $('#loginlook_logo_height').val();
        previewImg.css({
            'width': width + 'px',
            'height': height + 'px'
        });
    });

    // Apply saved width/height on load
    (function initLogoPreview() {
        var width = $('#loginlook_logo_width').val();
        var height = $('#loginlook_logo_height').val();
        if (width || height) {
            previewImg.css({
                'width': width ? width + 'px' : '',
                'height': height ? height + 'px' : ''
            });
        }
    })();

    // Reset color fields
    $('.loginlook-reset-color').on('click', function() {
        var target = $(this).data('target');
        if (!target) return;

        $(target).val('');

        if (target === '#loginlook_background_color') {
            $('#loginlook_background_color_picker').val('#0f172a');
        }

        if (target === '#loginlook_background_overlay_color') {
            $('#loginlook_background_overlay_color_picker').val('#0f172a');
        }

        if (target === '#loginlook_text_color') {
            $('#loginlook_text_color_picker').val('#0f172a');
        }
    });

    // Reset background image
    $('.loginlook-reset-image').on('click', function() {
        var target = $(this).data('target');
        if (target) {
            $(target).val('');
            backgroundPreviewImg.hide();
        }
    });

    // Sync color picker to text input
    $('#loginlook_background_color_picker').on('input change', function() {
        $('#loginlook_background_color').val($(this).val());
    });

    // Sync overlay color picker to text input
    $('#loginlook_background_overlay_color_picker').on('input change', function() {
        $('#loginlook_background_overlay_color').val($(this).val());
    });

    // Sync text color picker to text input
    $('#loginlook_text_color_picker').on('input change', function() {
        $('#loginlook_text_color').val($(this).val());
    });

    // Sync overlay opacity range to number input
    $('#loginlook_background_overlay_opacity_range').on('input change', function() {
        $('#loginlook_background_overlay_opacity').val($(this).val());
    });

    // Sync text input to color picker
    $('#loginlook_background_color').on('input', function() {
        var val = $(this).val();
        if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(val)) {
            $('#loginlook_background_color_picker').val(val);
        }
    });

    // Sync overlay text input to color picker
    $('#loginlook_background_overlay_color').on('input', function() {
        var val = $(this).val();
        if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(val)) {
            $('#loginlook_background_overlay_color_picker').val(val);
        }
    });

    // Sync text color input to color picker
    $('#loginlook_text_color').on('input', function() {
        var val = $(this).val();
        if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(val)) {
            $('#loginlook_text_color_picker').val(val);
        }
    });

    // Sync overlay opacity number to range input
    $('#loginlook_background_overlay_opacity').on('input change', function() {
        var val = $(this).val();
        if (val === '') return;
        var num = Math.max(0, Math.min(1, parseFloat(val)));
        if (!isNaN(num)) {
            $('#loginlook_background_overlay_opacity_range').val(num);
        }
    });

    // Theme card selection state
    $('.loginlook-theme-card input[type="radio"]').on('change', function() {
        $('.loginlook-theme-card').removeClass('active').find('.loginlook-activate-btn').text('Activate');

        var selectedCard = $(this).closest('.loginlook-theme-card');
        selectedCard.addClass('active');
        selectedCard.find('.loginlook-activate-btn').text('Selected');
    });

    // Reset individual fields
    $('.loginlook-reset-icon').on('click', function() {
        const target = $(this).data('target');
        if (!target) return;
        const $field = $(target);
        const defaultVal = $field.data('default');
        $field.val(defaultVal !== undefined ? defaultVal : '');

        if ($(this).data('clear-preview')) {
            previewImg.hide();
        }

        if (target === '#loginlook_logo_width' || target === '#loginlook_logo_height') {
            const width = $('#loginlook_logo_width').val();
            const height = $('#loginlook_logo_height').val();
            if (previewImg.length && previewImg.is(':visible')) {
                previewImg.css({
                    'width': width ? width + 'px' : '',
                    'height': height ? height + 'px' : ''
                });
            }
        }
    });

});
