jQuery(document).ready(function($) {
    
    function printSpecificArea(targetId, title, exclusions) {
        var $target = $('#' + targetId);
        
        if ($target.length === 0) {
            alert('Print Error: Target ID "#' + targetId + '" not found on this page.');
            return;
        }

        var printWindow = window.open('', '_blank', 'height=600,width=800');
        
        if(!printWindow) {
            alert('Please allow popups to print specific areas.');
            return;
        }

        var styles = '';
        $('link[rel="stylesheet"], style').each(function() {
            styles += this.outerHTML;
        });

        styles += '<style>';
        styles += '';
        if(exclusions) {
            styles += exclusions + ' { display: none !important; }';
        }
        styles += '</style>';

        var content = $target.html();
        
        printWindow.document.write('<html><head>');
        printWindow.document.write('<title>' + (title || document.title) + '</title>');
        printWindow.document.write(styles);
        printWindow.document.write('</head><body>');
        printWindow.document.write('<div class="sifency-print-output">' + content + '</div>');
        printWindow.document.write('</body></html>');
        
        printWindow.document.close();
        printWindow.focus();

        setTimeout(function() {
            printWindow.print();
            printWindow.close();
        }, 1000);
    }

    function printWholePage(title, exclusions) {
        var originalTitle = document.title;
        if(title) {
            document.title = title;
        }

        var $style = null;
        if(exclusions) {
            $style = $('<style>@media print { ' + exclusions + ' { display: none !important; } }</style>');
            $('head').append($style);
        }

        window.print();

        if(title) document.title = originalTitle;
        if($style) $style.remove();
    }

    $(document).on('click', '.sifency-print-btn', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var type = $btn.data('type');
        var title = $btn.data('title');
        var exclude = $btn.data('exclude') || '';
        
        var selfExclude = '.sifency-print-btn';
        var finalExclude = exclude ? exclude + ', ' + selfExclude : selfExclude;

        if (type === 'custom') {
            var target = $btn.data('target');
            printSpecificArea(target, title, finalExclude);
        } else {
            printWholePage(title, finalExclude);
        }
    });

});