/**
 * Public facing JavaScript for Universal ID Card Generator
 */
(function($) {
    'use strict';

    /**
     * Download ID Card sides
     * @param {string} target - The selector for the element to capture
     * @param {string} filename - The name of the downloaded file
     */
    window.cloudi7_icg_download_card = function(target, filename) {
        var $wrapper = $(target);
        if (!$wrapper.length) return;

        // Add loading state to button
        var $btn = $(event.currentTarget);
        var originalHtml = $btn.html();
        $btn.html('<span class="dashicons dashicons-update spin"></span> Downloading...').prop('disabled', true);

        // Add a temporary style to ensure the capture is clean
        var originalStyle = $wrapper.attr('style');
        $wrapper.css({
            'padding': '0',
            'background': 'transparent',
            'box-shadow': 'none',
            'border': 'none',
            'border-radius': '0',
            'margin': '0',
            'display': 'flex',
            'width': 'max-content'
        });

        html2canvas($wrapper[0], {
            scale: 3, // Higher quality
            useCORS: true,
            backgroundColor: null, // Transparent background
            logging: false,
            allowTaint: true
        }).then(function(canvas) {
            var link = document.createElement('a');
            link.download = filename + '.png';
            link.href = canvas.toDataURL('image/png', 1.0);
            link.click();

            // Restore state
            $btn.html(originalHtml).prop('disabled', false);
            if (originalStyle) {
                $wrapper.attr('style', originalStyle);
            } else {
                $wrapper.removeAttr('style');
            }
        }).catch(function(error) {
            console.error('Download failed:', error);
            $btn.html(originalHtml).prop('disabled', false);
            alert('Failed to generate image. Please try again.');
        });
    };

})(jQuery);
