// Structure Viewer 2.2 – File Viewer Modal
(function($) {
    'use strict';

    window.StructureViewerFileViewer = {

        currentFile: {
            type:     null,
            item:     null,
            filePath: null,
            fileName: null,
        },

        // Maps file extensions to icon colours and SVG paths
        fileIconMap: {
            php:  { color: '#7c3aed', bg: 'rgba(124,58,237,0.18)', svg: '<path d="M16 18l6-6-6-6M8 6l-6 6 6 6" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/>' },
            js:   { color: '#f59e0b', bg: 'rgba(245,158,11,0.18)', svg: '<path d="M7 8l-4 4 4 4M17 8l4 4-4 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 4l-4 16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>' },
            css:  { color: '#3b82f6', bg: 'rgba(59,130,246,0.18)', svg: '<rect x="3" y="3" width="18" height="18" rx="2" stroke="currentColor" stroke-width="1.9"/><path d="M8 12h8M8 8h5M8 16h6" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>' },
            html: { color: '#f97316', bg: 'rgba(249,115,22,0.18)', svg: '<path d="M4 4l2 14 6 2 6-2 2-14H4z" stroke="currentColor" stroke-width="1.9" stroke-linejoin="round"/><path d="M8 8h8l-1 8-3 1-3-1-0.5-5" stroke="currentColor" stroke-width="1.7"/>' },
            json: { color: '#f59e0b', bg: 'rgba(245,158,11,0.18)', svg: '<path d="M7 8l-4 4 4 4M17 8l4 4-4 4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 4l-4 16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>' },
            xml:  { color: '#10b981', bg: 'rgba(16,185,129,0.18)', svg: '<path d="M9 14l1.5 2L9 18M15 14l-1.5 2 1.5 2" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M13 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V9z" stroke="currentColor" stroke-width="1.9" stroke-linejoin="round"/>' },
            txt:  { color: '#94a3b8', bg: 'rgba(148,163,184,0.15)', svg: '<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" stroke="currentColor" stroke-width="1.9" stroke-linejoin="round"/><path d="M16 13H8M16 17H8M10 9H8" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>' },
            md:   { color: '#6366f1', bg: 'rgba(99,102,241,0.18)', svg: '<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" stroke="currentColor" stroke-width="1.9" stroke-linejoin="round"/><path d="M8 14v-4l2 2 2-2v4M15 10l-1 4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>' },
            sql:  { color: '#06b6d4', bg: 'rgba(6,182,212,0.18)', svg: '<ellipse cx="12" cy="7" rx="8" ry="3" stroke="currentColor" stroke-width="1.9"/><path d="M4 7v10c0 1.66 3.58 3 8 3s8-1.34 8-3V7" stroke="currentColor" stroke-width="1.9"/><path d="M4 12c0 1.66 3.58 3 8 3s8-1.34 8-3" stroke="currentColor" stroke-width="1.9"/>' },
            default: { color: '#64748b', bg: 'rgba(100,116,139,0.15)', svg: '<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" stroke="currentColor" stroke-width="1.9" stroke-linejoin="round"/><path d="M14 2v6h6" stroke="currentColor" stroke-width="1.9"/>' },
        },

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

        setupEventListeners: function() {
            $(document).on('click', '.sv-file-name', this.handleFileViewer.bind(this));
            $('#sv-copy-file-content').on('click', this.handleCopyFileContent.bind(this));
            $('#sv-download-file').on('click', this.handleDownloadFile.bind(this));
        },

        handleFileViewer: function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $link    = $(e.currentTarget);
            var fileUrl  = $link.attr('href');
            var fileName = $link.text().trim();

            if (StructureViewerUtils.isImageFile(fileName)) {
                window.open(fileUrl, '_blank');
                return;
            }

            if (!fileUrl || fileUrl.includes('#')) return;

            var urlParts = fileUrl.split('/wp-content/');
            if (urlParts.length < 2) return;

            var relativePath = urlParts[1];
            var pathParts    = relativePath.split('/');

            var type, item, filePath;
            if (pathParts[0] === 'plugins') {
                type = 'plugin'; item = pathParts[1]; filePath = pathParts.slice(2).join('/');
            } else if (pathParts[0] === 'themes') {
                type = 'theme';  item = pathParts[1]; filePath = pathParts.slice(2).join('/');
            } else { return; }

            StructureViewerUtils.showLoading();

            $.ajax({
                url:  structureviewerSettings.ajaxurl,
                type: 'POST',
                data: { action: 'structureviewer_view_file', nonce: structureviewerSettings.nonce, type, item, file_path: filePath },
                success: (response) => {
                    StructureViewerUtils.hideLoading();
                    if (response.success && response.data) {
                        this.currentFile = { type, item, filePath, fileName: response.data.file_name };
                        this.showFileModal(response.data);
                    } else {
                        var msg = (response.data && response.data.message) || 'Unknown error';
                        alert('Could not load file: ' + msg);
                    }
                },
                error: (xhr) => {
                    StructureViewerUtils.hideLoading();
                    window.open(fileUrl, '_blank');
                },
            });
        },

        // Populate and open the redesigned modal
        showFileModal: function(data) {
            var fileName = data.file_name;
            var ext      = fileName.split('.').pop().toLowerCase();
            var icon     = this.fileIconMap[ext] || this.fileIconMap.default;

            // File type icon bubble
            var $iconEl = $('#sv-modal-file-icon');
            $iconEl.css({ background: 'linear-gradient(135deg, ' + icon.color + ', ' + icon.color + 'aa)' });
            $iconEl.html('<svg viewBox="0 0 24 24" fill="none" style="width:22px;height:22px;color:#fff;">' + icon.svg + '</svg>');

            // Title and path
            $('#sv-file-viewer-title').text(fileName);
            $('#sv-file-viewer-path').text(this.currentFile.item ? '/wp-content/' + (this.currentFile.type === 'plugin' ? 'plugins/' : 'themes/') + this.currentFile.item + '/' + this.currentFile.filePath : '');

            // Metadata
            $('#sv-file-meta-size').text(data.size || '—');
            $('#sv-file-meta-modified').text(data.modified || '—');
            $('#sv-file-meta-lines').text(data.lines !== undefined ? data.lines.toLocaleString() : '—');

            // Content
            $('#sv-file-content').text(data.content).removeClass().addClass('language-' + ext);

            // Reset download button
            $('#sv-download-file').prop('disabled', false).find('svg').show();

            $('#sv-file-viewer-modal').fadeIn(200);
        },

        closeFileModal: function() {
            $('#sv-file-viewer-modal').fadeOut(200);
            this.currentFile = { type: null, item: null, filePath: null, fileName: null };
        },

        handleCopyFileContent: function() {
            var $btn      = $('#sv-copy-file-content');
            var origSvg   = $btn.html();
            var content   = $('#sv-file-content').text();

            navigator.clipboard.writeText(content).then(function() {
                $btn.html('<svg viewBox="0 0 24 24" fill="none" width="15" height="15"><path d="M20 6L9 17l-5-5" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>');
                setTimeout(function() { $btn.html(origSvg); }, 2000);
            }, function() {
                var ta = document.createElement('textarea');
                ta.value = content;
                document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
                $btn.html('<svg viewBox="0 0 24 24" fill="none" width="15" height="15"><path d="M20 6L9 17l-5-5" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>');
                setTimeout(function() { $btn.html(origSvg); }, 2000);
            });
        },

        handleDownloadFile: function() {
            var { type, item, filePath } = this.currentFile;
            if (!type || !item || !filePath) { alert('No file is currently open.'); return; }

            var $btn    = $('#sv-download-file');
            var origHtml = $btn.html();
            $btn.prop('disabled', true).css('opacity', 0.5);

            $.ajax({
                url: structureviewerSettings.ajaxurl,
                type: 'POST',
                data: { action: 'structureviewer_download_file', nonce: structureviewerSettings.nonce, type, item, file_path: filePath },
                success: (response) => {
                    $btn.prop('disabled', false).css('opacity', '');

                    if (response.success && response.data) {
                        try {
                            var byteChars = atob(response.data.content);
                            var arrays    = [];
                            for (var off = 0; off < byteChars.length; off += 512) {
                                var slice = byteChars.slice(off, off + 512);
                                var bytes = new Uint8Array(slice.length);
                                for (var i = 0; i < slice.length; i++) bytes[i] = slice.charCodeAt(i);
                                arrays.push(bytes);
                            }
                            var blob = new Blob(arrays, { type: response.data.mime_type });
                            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('Download failed during file creation.');
                        }
                    } else {
                        var msg = (response.data && response.data.message) || 'Unknown error';
                        alert('Download failed: ' + msg);
                    }
                },
                error: (xhr) => {
                    $btn.prop('disabled', false).css('opacity', '');
                    alert('Download failed: Server error (HTTP ' + xhr.status + ').');
                },
            });
        },

        // Called by sv-app.js via trigger on file modal open
        _fireOpenEvent: function () { $(document).trigger('sv:file-modal-open'); }
    };

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

})(jQuery);