jQuery(document).ready(function($) {
    var $fontSelect = $('#bangla-font-select');
    var $fontSize = $('#bangla-font-size');
    var $lineHeight = $('#bangla-line-height');
    var $letterSpacing = $('#bangla-letter-spacing');
    var $previewText = $('#font-preview p');

    // Load initial font and typography
    loadFont($fontSelect.val());
    updateTypography();

    // Update preview on font change
    $fontSelect.on('change', function() {
        loadFont($(this).val());
    });

    // Update preview on typography changes
    $fontSize.on('input', updateTypography);
    $lineHeight.on('input', updateTypography);
    $letterSpacing.on('input', updateTypography);

    // Handle notice dismissal
    $(document).on('click', '#bangla-font-cdn-notice .notice-dismiss', function() {
        $.ajax({
            url: bangfocdData.ajaxurl,
            method: 'POST',
            data: {
                action: 'bangla_font_cdn_dismiss_notice',
                _wpnonce: bangfocdData.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#bangla-font-cdn-notice').slideUp(300, function() {
                        $(this).remove();
                    });
                }
            }
        });
    });

    function loadFont(fontKey) {
        var fontData = bangfocdData.fonts[fontKey];
        if (!fontData) return;

        // Remove existing font styles
        $('link[data-bangla-font]').remove();

        // Add new font stylesheet
        $('<link>', {
            rel: 'stylesheet',
            href: fontData.url,
            'data-bangla-font': fontKey
        }).appendTo('head');

        // Update preview font
        $previewText.css('font-family', getFontName(fontKey));
    }

    function updateTypography() {
        $previewText.css({
            'font-size': $fontSize.val() + 'px',
            'line-height': $lineHeight.val(),
            'letter-spacing': $letterSpacing.val() + 'px'
        });
    }

    function getFontName(fontKey) {
        var names = {
            'adorsho-lipi': 'Adorsho Lipi',
            'apona-lohit': 'Apona Lohit',
            'baloo-da-2': 'Baloo Da 2',
            'bangla': 'Bangla',
            'ekushey-lohit': 'Ekushey Lohit',
            'kalpurush': 'Kalpurush',
            'mukti': 'Mukti',
            'noto-serif-bengali': 'Noto Serif Bengali',
            'siyam-rupali': 'Siyam Rupali',
            'solaiman-lipi': 'SolaimanLipi',
            'tiro-bangla': 'Tiro Bangla'
        };
        return names[fontKey] || 'sans-serif';
    }
});