// Structure Viewer 2.2 – Export and Copy Functionality
(function($) {
    'use strict';

    window.StructureViewerExport = {

        // Stored while the modal is open
        _pendingItem: null,
        _pendingType: null,

        init: function() {
            this.setupEventListeners();
        },

        setupEventListeners: function() {
            // Export button → open modal
            $(document).on('click', '.sv-export', this.handleExportButtonClick.bind(this));

            // Export modal: card click → trigger export
            $(document).on('click', '.sv-export-card', this.handleExportCardClick.bind(this));

            // Copy to clipboard
            $(document).on('click', '.sv-copy-clipboard', this.handleCopyToClipboard.bind(this));
        },

        // ── Export button opens the modal ─────────────────────────────
        handleExportButtonClick: function(e) {
            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            var $btn = $(e.currentTarget);
            this._pendingItem = $btn.attr('data-item');
            this._pendingType = $btn.attr('data-type');

            if (!this._pendingItem || !this._pendingType) {
                alert('Error: Could not determine which item to export. Please select a specific plugin or theme.');
                return;
            }

            $('#sv-export-modal').fadeIn(180);
        },

        // ── Card click → route to correct exporter ────────────────────
        handleExportCardClick: function(e) {
            var format = $(e.currentTarget).attr('data-format');
            if (!format) return;

            $('#sv-export-modal').fadeOut(180);

            if (format === 'pdf') {
                this.performPdfExport(this._pendingItem, this._pendingType);
            } else {
                this.performExport(this._pendingItem, this._pendingType, format);
            }
        },

        performExport: function(item, type, format) {
            StructureViewerUtils.showLoading();

            $.ajax({
                url:  structureviewerSettings.ajaxurl + '?t=' + Date.now(),
                type: 'POST',
                data: {
                    action: 'structureviewer_export',
                    nonce:  structureviewerSettings.nonce,
                    item:   item,
                    type:   type,
                    format: format,
                },
                success: function(response) {
                    StructureViewerUtils.hideLoading();

                    if (response.success && response.data) {
                        try {
                            var blob = new Blob([response.data.data], {
                                type: response.data.mime_type || 'text/plain',
                            });
                            var url = window.URL.createObjectURL(blob);
                            var a   = document.createElement('a');
                            a.style.display = 'none';
                            a.href     = url;
                            a.download = response.data.filename;
                            document.body.appendChild(a);
                            a.click();
                            setTimeout(function() {
                                window.URL.revokeObjectURL(url);
                                document.body.removeChild(a);
                            }, 100);
                        } catch (err) {
                            alert('Export failed during file creation.');
                        }
                    } else {
                        var msg = (response.data && response.data.message) || 'Unknown error';
                        alert('Export failed: ' + msg);
                    }
                },
                error: function(xhr) {
                    StructureViewerUtils.hideLoading();
                    alert('Export failed: Server error (HTTP ' + xhr.status + ').');
                },
            });
        },

        // v2.1: Fetch TXT then render PDF client-side
        performPdfExport: function(item, type) {
            if (!window.jspdf || !window.jspdf.jsPDF) {
                alert('PDF library is not loaded. Please refresh the page and try again.');
                return;
            }

            StructureViewerUtils.showLoading();

            $.ajax({
                url:  structureviewerSettings.ajaxurl + '?t=' + Date.now(),
                type: 'POST',
                data: {
                    action: 'structureviewer_export',
                    nonce:  structureviewerSettings.nonce,
                    item:   item,
                    type:   type,
                    format: 'txt',
                },
                success: (response) => {
                    StructureViewerUtils.hideLoading();

                    if (response.success && response.data && response.data.data) {
                        var filename = response.data.filename
                            ? response.data.filename.replace(/\.txt$/, '.pdf')
                            : 'structure-' + item + '.pdf';
                        this.generatePDF(response.data.data, item, filename);
                    } else {
                        var msg = (response.data && response.data.message) || 'Unknown error';
                        alert('PDF export failed: ' + msg);
                    }
                },
                error: function(xhr) {
                    StructureViewerUtils.hideLoading();
                    alert('PDF export failed: Server error (HTTP ' + xhr.status + ').');
                },
            });
        },

        // v2.1 jsPDF renderer
        generatePDF: function(textContent, itemName, filename) {
            try {
                var jsPDF = window.jspdf.jsPDF;
                var doc   = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
                var pageW = doc.internal.pageSize.getWidth();
                var pageH = doc.internal.pageSize.getHeight();
                var mx    = 15, mt = 20, mb = 18, lh = 4.5;
                var maxW  = pageW - mx * 2;
                var y     = mt;

                doc.setFont('helvetica', 'bold');
                doc.setFontSize(14);
                doc.setTextColor(124, 58, 237);
                doc.text('Structure Viewer', mx, y);
                y += 7;

                doc.setFont('helvetica', 'normal');
                doc.setFontSize(10);
                doc.setTextColor(80, 87, 94);
                doc.text('Plugin/Theme: ' + itemName, mx, y);   y += 5;
                doc.text('Exported: ' + new Date().toLocaleString(), mx, y); y += 4;
                doc.setDrawColor(229, 229, 229);
                doc.line(mx, y, pageW - mx, y);
                y += 6;

                doc.setFont('courier', 'normal');
                doc.setFontSize(8);
                doc.setTextColor(44, 51, 56);

                textContent.split('\n').forEach(function(raw) {
                    doc.splitTextToSize(raw, maxW).forEach(function(line) {
                        if (y + lh > pageH - mb) {
                            doc.addPage();
                            y = mt;
                            doc.setFont('helvetica', 'normal');
                            doc.setFontSize(7);
                            doc.setTextColor(140, 143, 148);
                            doc.text(itemName + ' — continued', mx, y);
                            y += 5;
                            doc.setFont('courier', 'normal');
                            doc.setFontSize(8);
                            doc.setTextColor(44, 51, 56);
                        }
                        doc.text(line, mx, y);
                        y += lh;
                    });
                });

                var total = doc.internal.getNumberOfPages();
                for (var i = 1; i <= total; i++) {
                    doc.setPage(i);
                    doc.setDrawColor(220, 220, 220);
                    doc.line(mx, pageH - 16, pageW - mx, pageH - 16);
                    doc.setFont('helvetica', 'italic');
                    doc.setFontSize(6.5);
                    doc.setTextColor(120, 125, 132);
                    doc.text('Generated by Structure Viewer  •  wordpress.org/plugins/structure-viewer',
                        pageW / 2, pageH - 12, { align: 'center' });
                    doc.setFont('helvetica', 'normal');
                    doc.setFontSize(7);
                    doc.setTextColor(140, 143, 148);
                    doc.text('Page ' + i + ' of ' + total, pageW / 2, pageH - 7, { align: 'center' });
                }
                doc.save(filename);
            } catch (err) {
                alert('PDF generation failed.');
            }
        },

        // ── Copy structure to clipboard ───────────────────────────────
        handleCopyToClipboard: function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $btn       = $(e.currentTarget);
            var item       = $btn.attr('data-item');
            var type       = $btn.attr('data-type');
            var origText   = $btn.text();

            if (!item || !type) {
                alert('Error: Please select a specific plugin or theme to copy structure.');
                return;
            }

            var onSuccess = function() {
                StructureViewerUtils.hideLoading();
                $btn.text('Copied!');
                setTimeout(function() { $btn.text(origText); }, 2000);
            };

            var onError = function(msg) {
                StructureViewerUtils.hideLoading();
                alert('Copy failed: ' + msg);
            };

            var fetchStructure = function() {
                return new Promise(function(resolve, reject) {
                    $.ajax({
                        url:  structureviewerSettings.ajaxurl,
                        type: 'POST',
                        data: {
                            action:      'structureviewer_copy_clipboard',
                            nonce:       structureviewerSettings.nonce,
                            item:        item,
                            type:        type,
                            copy_format: $('input[name="sv_copy_format"]:checked').val() || 'json',
                        },
                        success: function(response) {
                            if (response.success && response.data) {
                                resolve(response.data.data);
                            } else {
                                reject((response.data && response.data.message) || 'Unknown error');
                            }
                        },
                        error: function(xhr) { reject('Server error (HTTP ' + xhr.status + ').'); },
                    });
                });
            };

            var execFallback = function(text) {
                try {
                    var ta = document.createElement('textarea');
                    ta.value = text;
                    ta.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;';
                    document.body.appendChild(ta);
                    ta.focus(); ta.select(); ta.setSelectionRange(0, text.length);
                    var ok = document.execCommand('copy');
                    document.body.removeChild(ta);
                    if (ok) { onSuccess(); } else { onError('execCommand returned false.'); }
                } catch (err) { onError('Clipboard not supported.'); }
            };

            StructureViewerUtils.showLoading();

            if (typeof ClipboardItem !== 'undefined' && navigator.clipboard && navigator.clipboard.write) {
                navigator.clipboard.write([
                    new ClipboardItem({
                        'text/plain': fetchStructure().then(function(t) { return new Blob([t], { type: 'text/plain' }); }),
                    }),
                ]).then(onSuccess).catch(function() {
                    fetchStructure().then(function(t) {
                        if (navigator.clipboard && navigator.clipboard.writeText) {
                            navigator.clipboard.writeText(t).then(onSuccess).catch(function() { execFallback(t); });
                        } else { execFallback(t); }
                    }).catch(onError);
                });
            } else if (navigator.clipboard && navigator.clipboard.writeText) {
                fetchStructure().then(function(t) {
                    return navigator.clipboard.writeText(t);
                }).then(onSuccess).catch(function() {
                    fetchStructure().then(execFallback).catch(onError);
                });
            } else {
                fetchStructure().then(execFallback).catch(onError);
            }
        },
    };

    $(document).ready(function() {
        StructureViewerExport.init();
    });

})(jQuery);