/**
 * Admin Settings JavaScript
 * Handles admin interface functionality
 */
jQuery(document).ready(function($){
    // Handle template selection using event delegation
    $(document).on("click", ".ckfylt25-template-choose-btn", function(){
        var templateId = $(this).data("template-id");
        var templateCard = $(this).closest(".ckfylt25-template-card");
        
        // Update hidden radio button
        templateCard.find("input[type=\"radio\"]").prop("checked", true);
        
        // Update all cards - remove selected class from all
        $(".ckfylt25-template-card").removeClass("ckfylt25-template-selected");
        templateCard.addClass("ckfylt25-template-selected");
        
        // Update all buttons - reset all to "Choose this template"
        $(".ckfylt25-template-selected-btn").each(function(){
            var btnTemplateId = $(this).data("template-id");
            $(this).replaceWith('<button type="button" class="ckfylt25-template-choose-btn" data-template-id="' + btnTemplateId + '">Choose this template</button>');
        });
        
        // Update current card button to "Selected"
        $(this).replaceWith('<button type="button" class="ckfylt25-template-selected-btn" data-template-id="' + templateId + '" disabled>✓ Selected</button>');
        
        // Save the selection
        $.post(ckfylt25AdminData.ajaxUrl, {
            action: "ckfylt25_save_template_selection",
            template_id: templateId,
            nonce: ckfylt25AdminData.nonce
        });
    });
    
    // Template demo images mapping
    var templateImages = {
        "conversational": ckfylt25AdminData.assetsPreviewBaseUrl + "conversational.webp",
        "fluid": ckfylt25AdminData.assetsPreviewBaseUrl + "fluid.webp",
        "moderna": ckfylt25AdminData.assetsPreviewBaseUrl + "moderna.webp",
        "store-checkout": ckfylt25AdminData.assetsPreviewBaseUrl + "storecheckout.webp",
        "shopper": ckfylt25AdminData.assetsPreviewBaseUrl + "shooper.webp",
        "supra": ckfylt25AdminData.assetsPreviewBaseUrl + "supra.webp",
        "petfood": ckfylt25AdminData.assetsPreviewBaseUrl + "petfood.webp",
        "energy-supplements": ckfylt25AdminData.assetsPreviewBaseUrl + "energy.webp"
    };
    
    // Handle demo modal
    $(document).on("click", ".ckfylt25-view-demo-btn", function(e){
        e.preventDefault();
        var templateId = $(this).data("template-id");
        var templateName = $(this).closest(".ckfylt25-template-card").find("h4").text().replace(" (PRO)", "");
        var imageUrl = templateImages[templateId];
        
        if (imageUrl) {
            $("#ckfylt25-modal-title").text(templateName + " Template Preview");
            $("#ckfylt25-modal-image").attr("src", imageUrl);
            $("#ckfylt25-demo-modal").fadeIn(300);
        }
    });
    
    // Close modal
    $(document).on("click", ".ckfylt25-modal-close, .ckfylt25-modal-overlay", function(){
        $("#ckfylt25-demo-modal").fadeOut(300);
    });
    
    // Close modal with Escape key
    $(document).on("keydown", function(e){
        if (e.keyCode === 27 && $("#ckfylt25-demo-modal").is(":visible")) {
            $("#ckfylt25-demo-modal").fadeOut(300);
        }
    });

    // Remove any existing event handlers to prevent loops
    $(document).off("change", "input[name='ckfylt25_selected_template']");
    $(document).off("click", ".ckfylt25-template-pro");
    $(document).off("mouseenter mouseleave", ".ckfylt25-template-card");
    $(document).off("click", "#ckfylt25-sidebar-toggle");
    
    // Handle template selection
    $(document).on("change", "input[name='ckfylt25_selected_template']", function() {
        $(".ckfylt25-template-card").removeClass("ckfylt25-template-selected");
        $(this).closest(".ckfylt25-template-card").addClass("ckfylt25-template-selected");
    });
    
    // Handle PRO template clicks (but not demo buttons)
    $(document).on("click", ".ckfylt25-template-pro", function(e) {
        // Don't handle clicks on demo buttons or other interactive elements
        if ($(e.target).hasClass('ckfylt25-view-demo-btn') ||
            $(e.target).closest('.ckfylt25-view-demo-btn').length > 0 ||
            $(e.target).hasClass('ckfylt25-template-pro-actions') ||
            $(e.target).closest('.ckfylt25-template-pro-actions').length > 0) {
            return;
        }
        e.preventDefault();
        window.open("https://checkoutify.net/#demos", "_blank");
    });
    
    // Add hover effects
    $(document).on("mouseenter", ".ckfylt25-template-card", function() {
        if (!$(this).hasClass("ckfylt25-template-pro")) {
            $(this).css("transform", "translateY(-2px)");
        }
    }).on("mouseleave", ".ckfylt25-template-card", function() {
        if (!$(this).hasClass("ckfylt25-template-pro")) {
            $(this).css("transform", "translateY(0)");
        }
    });

    // Force show toggle button on mobile
    function showToggleButtonOnMobile() {
        if ($(window).width() <= 768) {
            $("#ckfylt25-sidebar-toggle").show().css({
                'display': 'block',
                'visibility': 'visible',
                'opacity': '1'
            });
        } else {
            $("#ckfylt25-sidebar-toggle").hide();
        }
    }
    
    // Run on page load and resize
    showToggleButtonOnMobile();
    $(window).resize(showToggleButtonOnMobile);
    
    // Handle sidebar toggle (mobile only)
    $(document).on("click", "#ckfylt25-sidebar-toggle", function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(".ckfylt25-sidebar").toggleClass("collapsed");
        $("#ckfylt25-sidebar-overlay").toggleClass("active");
    });
    
    // Close sidebar when clicking overlay
    $(document).on("click", "#ckfylt25-sidebar-overlay", function() {
        $(".ckfylt25-sidebar").removeClass("collapsed");
        $("#ckfylt25-sidebar-overlay").removeClass("active");
    });
    
    // Close sidebar when clicking on a nav link (mobile)
    $(document).on("click", ".ckfylt25-nav-link", function() {
        if ($(window).width() <= 768) {
            $(".ckfylt25-sidebar").removeClass("collapsed");
            $("#ckfylt25-sidebar-overlay").removeClass("active");
        }
    });

    // Handle tab navigation: allow real links to navigate; only intercept when href is '#'
    $(document).on("click", ".ckfylt25-nav-link", function(e) {
        var href = $(this).attr('href');
        // If the link does not have a real URL, fall back to JS-based tab switching
        if (!href || href === '#') {
            e.preventDefault();
            var tab = $(this).data('tab');

            // Update active tab
            $(".ckfylt25-nav-link").removeClass("ckfylt25-nav-active");
            $(this).addClass("ckfylt25-nav-active");

            // Show/hide tab content
            $(".ckfylt25-tab-content").hide();
            $("#ckfylt25-tab-" + tab).show();

            // Update URL without reload (for consistency)
            var newUrl = window.location.pathname + '?page=checkoutify-settings&tab=' + tab;
            window.history.pushState({}, '', newUrl);
        }
        // else: let the browser navigate to the real admin.php URL
    });

    // Media uploader functionality
    var mediaUploader;
    $('body').on('click', '.upload-image-button, #ckfylt25-upload-logo-button', function(e) {
        e.preventDefault();
        var $button = $(this);
        var isLogo = $button.attr('id') === 'ckfylt25-upload-logo-button';
        if (mediaUploader) { mediaUploader.open(); return; }
        mediaUploader = wp.media({ title: 'Choose Image', library: { type: 'image' }, button: { text: 'Choose Image' }, multiple: false });
        mediaUploader.on('select', function() {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            if (isLogo) {
                $('#ckfylt25_header_logo_id').val(attachment.id);
                $('#ckfylt25-logo-preview').attr('src', attachment.url).show();
                $('#ckfylt25-remove-logo-button').show();
            } else {
                $button.siblings('.image-id-field').val(attachment.id);
                $button.siblings('.image-url-field').val(attachment.url);
                $button.siblings('.image-preview').attr('src', attachment.url).show();
                $button.siblings('.remove-image-button').show();
            }
        });
        mediaUploader.open();
    });
    $('body').on('click', '.remove-image-button, #ckfylt25-remove-logo-button', function(e) {
        e.preventDefault();
        var $button = $(this);
        var isLogo = $button.attr('id') === 'ckfylt25-remove-logo-button';
        if (isLogo) {
            $('#ckfylt25_header_logo_id').val('');
            $('#ckfylt25-logo-preview').attr('src', '').hide();
        } else {
            $button.siblings('.image-id-field').val('');
            $button.siblings('.image-url-field').val('');
            $button.siblings('.image-preview').attr('src', '').hide();
        }
        $button.hide();
    });

    $(document).on("click", ".ckfylt25-review-leave", function(e){
        e.preventDefault();
        $.post(ckfylt25AdminData.ajaxUrl, { action: "ckfylt25_review_done", nonce: ckfylt25AdminData.nonce }, function(){
            $("#ckfylt25-review-banner").fadeOut(200);
            window.open("https://wordpress.org/support/plugin/checkoutify-lite/reviews/", "_blank");
        });
    });
    $(document).on("click", ".ckfylt25-review-support", function(e){
        e.preventDefault();
        window.open("https://checkoutify.net/customer-support/", "_blank");
    });
    $(document).on("click", ".ckfylt25-review-dismiss", function(e){
        e.preventDefault();
        $.post(ckfylt25AdminData.ajaxUrl, { action: "ckfylt25_review_dismiss", nonce: ckfylt25AdminData.nonce }, function(){
            $("#ckfylt25-review-banner").fadeOut(200);
        });
    });
});
