/**
 * MediaTasker — Upload Module
 *
 * Handles drag-and-drop file uploads with progress tracking for both
 * Original and Edited upload zones.
 *
 * @package MediaTasker
 */

/* global jQuery, mediat_ajax_obj */

(function ($) {
    'use strict';

    $(document).ready(function () {
        var $workspace = $('#media-viewport');
        if (!$workspace.length) return;

        /* ==================================================================
           Drag & Drop Upload (Generalized for dual zones)
           ================================================================== */
        function initDropzone($dropzone, viewType) {
            if (!$dropzone.length) return;

            var $fileInput = $dropzone.find('.mediat_hidden-input');
            var $browseBtn = $dropzone.find('.mediat_btn-neutral');
            var $progressWrap = $dropzone.closest('.mediat_upload-panel').find('.mediat_progress-container');
            var $progressBar = $progressWrap.find('.mediat_progress-fill');

            // Temporary status area until proper structure is made
            var $uploadStatus = $('<div class="mediat_upload-status" style="margin-top:10px;"></div>');
            $progressWrap.after($uploadStatus);

            $browseBtn.on('click', function (e) {
                e.stopPropagation();
                $fileInput.trigger('click');
            });

            $dropzone.on('click', function (e) {
                if ($(e.target).closest('.mediat_btn').length) return;
                $fileInput.trigger('click');
            });

            $fileInput.on('change', function () {
                if (this.files && this.files.length) {
                    handleFiles(this.files, $uploadStatus, $progressWrap, $progressBar, viewType);
                    this.value = '';
                }
            });

            $dropzone.on('dragenter dragover', function (e) {
                e.preventDefault(); e.stopPropagation();
                $dropzone.addClass('is-dragover');
            });

            $dropzone.on('dragleave drop', function (e) {
                e.preventDefault(); e.stopPropagation();
                $dropzone.removeClass('is-dragover');
            });

            $dropzone.on('drop', function (e) {
                var files = e.originalEvent.dataTransfer.files;
                if (files && files.length) {
                    handleFiles(files, $uploadStatus, $progressWrap, $progressBar, viewType);
                }
            });
        }

        initDropzone($('#dropzone-primary'), 'original');
        initDropzone($('#dropzone-secondary'), 'edited');

        function handleFiles(files, $uploadStatus, $progressWrap, $progressBar, viewType) {
            $uploadStatus.empty();
            var queue = [];
            var $dropzone = viewType === 'original' ? $('#dropzone-primary') : $('#dropzone-secondary');
            var allowedTypes = ($dropzone.attr('data-allowed') || '').split(',').map(t => t.trim().toLowerCase());
            var maxSizeMB = parseInt($dropzone.attr('data-max-size'), 10) || 5;

            var totalBytes = 0;

            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                var ext = file.name.split('.').pop().toLowerCase();

                if (allowedTypes.length && allowedTypes.indexOf(ext) === -1 && allowedTypes[0] !== '') {
                    addStatusMsg($uploadStatus, file.name + ': type not allowed.', 'error');
                    continue;
                }
                if (file.size > maxSizeMB * 1024 * 1024) {
                    addStatusMsg($uploadStatus, file.name + ': exceeds ' + maxSizeMB + ' MB.', 'error');
                    continue;
                }
                queue.push(file);
                totalBytes += file.size;
            }

            if (queue.length) {
                var uploadedPostIds = [];
                uploadQueue(queue, 0, $uploadStatus, $progressWrap, $progressBar, viewType, 0, totalBytes, uploadedPostIds);
            }
        }

        function uploadQueue(queue, idx, $uploadStatus, $progressWrap, $progressBar, viewType, uploadedBytesSoFar, totalBytes, uploadedPostIds) {
            if (idx >= queue.length) {
                var finishAndReload = function () {
                    setTimeout(function () {
                        $progressWrap.hide();
                        if (window.MEDIAT_FloatingMenu && window.MEDIAT_FloatingMenu.updateStatusMetrics) {
                            window.MEDIAT_FloatingMenu.updateStatusMetrics();
                        }
                        window.location.reload();
                    }, 1000);
                };

                // 

                finishAndReload();
                return;
            }

            var file = queue[idx];
            var formData = new FormData();
            formData.append('action', 'mediat_upload_task');
            formData.append('nonce', mediat_ajax_obj.nonce);
            formData.append('mediat_file', file);
            formData.append('view_type', viewType); // Send type context if needed

            addStatusMsg($uploadStatus, file.name + ': uploading…', 'info');
            if (idx === 0) {
                $progressWrap.show();
                $progressBar.css('width', '0%');
                $progressWrap.find('.mediat_progress-label').text('0%');
            }

            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function () {
                    var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function (evt) {
                        if (evt.lengthComputable) {
                            var currentFileUploaded = evt.loaded;
                            var overallUploaded = uploadedBytesSoFar + currentFileUploaded;
                            var pct = Math.round((overallUploaded / totalBytes) * 100);
                            var finalPct = Math.min(pct, 100);
                            $progressBar.css('width', finalPct + '%');
                            $progressWrap.find('.mediat_progress-label').text(finalPct + '%');
                        }
                    });
                    return xhr;
                },
                success: function (response) {
                    if (response.success && response.data) {
                        if (response.data.post_id) {
                            uploadedPostIds.push(response.data.post_id);
                        }
                        addStatusMsg($uploadStatus, file.name + ': ✓ uploaded', 'success');
                        // The gallery safely reloads once the full upload queue is completely processed.
                    } else {
                        var msg = (response.data && response.data.message) ? response.data.message : 'Upload failed.';
                        addStatusMsg($uploadStatus, file.name + ': ' + msg, 'error');
                    }
                },
                error: function () {
                    addStatusMsg($uploadStatus, file.name + ': upload failed.', 'error');
                },
                complete: function () {
                    uploadedBytesSoFar += file.size;
                    uploadQueue(queue, idx + 1, $uploadStatus, $progressWrap, $progressBar, viewType, uploadedBytesSoFar, totalBytes, uploadedPostIds);
                }
            });
        }

        function addStatusMsg($container, text, type) {
            var color = type === 'success' ? '#00a32a' : (type === 'error' ? '#d63638' : '#3c434a');
            var icon = type === 'success' ? '✓ ' : (type === 'error' ? '✕ ' : 'ℹ ');
            var $msg = $('<p style="margin:4px 0; font-size:13px; font-weight:500; color:' + color + ';"></p>').text(icon + text);
            $container.prepend($msg);

            // Remove message after 5 seconds to keep clean UI
            setTimeout(function () {
                $msg.fadeOut(300, function () { $(this).remove(); });
            }, 5000);
        }
    });
})(jQuery);
