jQuery(document).ready(function ($) {
    // Logo uploader
    $('.pdfinvx-upload-logo').on('click', function (e) {
        e.preventDefault();
        if (typeof wp === 'undefined' || !wp.media) {
            alert(pdfInvoiceXAdmin.i18n.mediaError);
            return;
        }
        const uploader = wp.media({
            title: wp.i18n.__('Select Store Logo', 'pdf-invoicex'),
            button: { text: wp.i18n.__('Use this logo', 'pdf-invoicex') },
            multiple: false,
        }).on('select', function () {
            const attachment = uploader.state().get('selection').first().toJSON();
            $('#pdfinvx_store_logo_id').val(attachment.id);
            $('#pdfinvx_store_logo_url').val(attachment.url);
            $('.pdfinvx-logo-preview').html(
                `<img src="${attachment.url}" alt="${wp.i18n.__('Logo Preview', 'pdf-invoicex')}">`
            );
        }).open();
    });

    // Settings tabs
    $('.woo-nav-tab-wrapper .nav-tab').on('click', function (e) {
        e.preventDefault();
        const $this = $(this);
        const tabId = $this.data('tab');

        $('.woo-nav-tab-wrapper .nav-tab').removeClass('nav-tab-active');
        $this.addClass('nav-tab-active');

        $('.pdfinvx-tab-content').hide();
        $('#' + tabId).show();

        window.location.hash = $this.attr('href');
    });

    if (window.location.hash) {
        const hash = window.location.hash;
        const $tab = $(`.woo-nav-tab-wrapper .nav-tab[href="${hash}"]`);
        if ($tab.length) {
            $tab.trigger('click');
        } else {
            $('.woo-nav-tab-wrapper .nav-tab:first').trigger('click');
        }
    } else {
        $('.woo-nav-tab-wrapper .nav-tab:first').trigger('click');
    }

    // PDF download
    $(document).on('click', '.pdfinvx-download-pdf', function (e) {
        e.preventDefault();
        const $button = $(this);
        const url = $button.attr('href');
        const originalText = $button.text();

        $button
            .addClass('disabled')
            .text(pdfInvoiceXAdmin.i18n.generating)
            .prepend('<span class="spinner is-active"></span>');

        $.ajax({
            url: url,
            method: 'GET',
            dataType: 'json',
            success: function (response) {
                if (response.success && response.data.file_url) {
                    const downloadFrame = $('<iframe>', {
                        src: response.data.file_url,
                        style: 'display:none;'
                    }).appendTo('body');
                    setTimeout(function () {
                        downloadFrame.remove();
                    }, 5000);
                } else {
                    alert(response.data.message || pdfInvoiceXAdmin.i18n.error);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error('PDFInvoiceX AJAX Error: ' + textStatus + ' - ' + errorThrown);
                alert(pdfInvoiceXAdmin.i18n.error);
            },
            complete: function () {
                $button
                    .removeClass('disabled')
                    .text(originalText)
                    .find('.spinner')
                    .remove();
            },
        });
    });

    // Template selection
    $('.pdfinvx-template-card').on('click', function (e) {
        if (!$(e.target).hasClass('pdfinvx-preview-template') && !$(e.target).closest('.pdfinvx-preview-template').length) {
            const templateId = $(this).data('template');

            $('.pdfinvx-template-card').removeClass('pdfinvx-template-selected');
            $(this).addClass('pdfinvx-template-selected');

            $('.pdfinvx-template-selected-badge').remove();
            $(this).find('.pdfinvx-template-preview').append(
                '<div class="pdfinvx-template-selected-badge"><span class="dashicons dashicons-yes-alt"></span></div>'
            );

            $(`input[name="pdfinvx_settings[template]"][value="${templateId}"]`).prop('checked', true);
        }
    });

    // Template preview button
    $('.pdfinvx-preview-template').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        const templateId = $(this).data('template');
        const $templateCard = $(this).closest('.pdfinvx-template-card');
        const templateName = $templateCard.find('h3').text();
        const templateImage = $templateCard.find('.pdfinvx-template-preview img').attr('src');

        $('#pdfinvx-preview-image').attr('src', templateImage);
        $('.pdfinvx-modal-title').text(templateName + ' - ' + wp.i18n.__('Preview', 'pdf-invoicex'));

        $('#pdfinvx-template-preview-modal').data('template-id', templateId);
        $('#pdfinvx-template-preview-modal').show();
    });

    // Close modal
    $('.pdfinvx-modal-close, .pdfinvx-modal-close-btn').on('click', function () {
        $('#pdfinvx-template-preview-modal').hide();
    });

    $(window).on('click', function (e) {
        if ($(e.target).is('.pdfinvx-modal')) {
            $('.pdfinvx-modal').hide();
        }
    });

    // Use template button in modal
    $('.pdfinvx-use-template').on('click', function () {
        const templateId = $('#pdfinvx-template-preview-modal').data('template-id');
        $(`.pdfinvx-template-card[data-template="${templateId}"]`).trigger('click');
        $('#pdfinvx-template-preview-modal').hide();
    });

    // Keyboard navigation for modal
    $(document).on('keydown', function (e) {
        if (e.key === 'Escape' && $('#pdfinvx-template-preview-modal').is(':visible')) {
            $('#pdfinvx-template-preview-modal').hide();
        }
    });

    // Template radio button handling
    $('.pdfinvx-template-select input[type="radio"]').on('change', function () {
        const templateId = $(this).val();
        $(`.pdfinvx-template-card[data-template="${templateId}"]`).trigger('click');
    });

    // Initialize tooltips
    if (typeof $.fn.tipTip === 'function') {
        $('.pdfinvx-help-tip').tipTip({
            'attribute': 'data-tip',
            'fadeIn': 50,
            'fadeOut': 50,
            'delay': 200
        });
    }

    // Template hover effects
    $('.pdfinvx-template-card').hover(
        function () {
            $(this).addClass('pdfinvx-template-hover');
        },
        function () {
            $(this).removeClass('pdfinvx-template-hover');
        }
    );
});