jQuery(document).ready(function($) {
    // Tab filter
    $('.crt-theme-builder-tab').on('click', function() {
        var tab = $(this).data('tab');
        $('.crt-theme-builder-tab').removeClass('active');
        $(this).addClass('active');
        if (tab === 'all') {
            $('.crt-theme-builder-item').removeClass('crt-tab-hidden');
        } else {
            $('.crt-theme-builder-item').each(function() {
                if ($(this).data('tab') === tab) {
                    $(this).removeClass('crt-tab-hidden');
                } else {
                    $(this).addClass('crt-tab-hidden');
                }
            });
        }
    });

    $('.crt-theme-builder-item').on('click', function() {
        var $item = $(this);
        var action = $item.data('action');
        var postType = $item.data('post-type');
        var metaKey = $item.data('meta-key');
        var postId = $item.data('post-id');
        var url = $item.data('url');

        if (action === 'create_edit') {
            if (postId && url) {
                window.location.href = url;
            } else {
                $item.css('opacity', '0.6').css('pointer-events', 'none');
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'crt_manage_theme_builder_action',
                        post_type: postType,
                        meta_key: metaKey || '',
                        _wpnonce: crtThemeBuilder.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data.edit_url) {
                            window.location.href = response.data.edit_url;
                        } else {
                            $item.css('opacity', '1').css('pointer-events', '');
                            alert(response.data.message || 'Error creating template.');
                        }
                    },
                    error: function() {
                        $item.css('opacity', '1').css('pointer-events', '');
                        alert('Request failed. Please try again.');
                    }
                });
            }
        }
    });
});
