/**
 * MediaTasker — Floating Action Menu Logic
 *
 * Manages bulk actions, selection tracking, and dynamic UI updates.
 * Promotes high code quality through DRY and unified API helpers.
 *
 * @package MediaTasker
 */

/* global jQuery, mediat_ajax_obj, MEDIAT_Dialog */

(function ($) {
    'use strict';

    $(document).ready(function () {
        const $floatingMenu = $('.mediat_floating-controls');
        const $selectionCountBadge = $('.mediat_selection-count');
        const $mainWorkspace = $('#media-viewport');
        

        // State management for selections
        let selectedIds = [];
        let downloadInProgress = false;

        /**
         * Helper to show errors via custom dialog
         */
        function showErrorDialog(message) {
            if (window.MEDIAT_Dialog) {
                window.MEDIAT_Dialog.show({
                    type: 'alert',
                    title: 'Error',
                    message: message
                });
            } else {
                console.error('MediaTasker Error:', message);
            }
        }

        /**
         * Updates the floating menu state based on current card selection.
         */
        function updateSelectionState() {
            selectedIds = [];
            $('.mediat_asset-card.is-selected').each(function () {
                const id = $(this).data('post-id');
                if (id) selectedIds.push(id);
            });

            const count = selectedIds.length;
            $selectionCountBadge.text(count);

            if (count > 0) {
                $floatingMenu.addClass('is-visible');
                $mainWorkspace.addClass('selection-mode');
            } else {
                $floatingMenu.removeClass('is-visible');
                $mainWorkspace.removeClass('selection-mode');
            }
        }

        /**
         * Recalculates and updates the status breakdown and total counters for both views.
         */
        function updateStatusMetrics() {
            // Helper for Original view
            const $originalGrid = $('#mediat_grid-original');
            const totalOriginal = $originalGrid.find('.mediat_asset-card').length;
            const pendingOriginal = $originalGrid.find('.mediat_asset-card.status-pending').length;
            const inProgressOriginal = $originalGrid.find('.mediat_asset-card.status-in-progress').length;
            const completedOriginal = $originalGrid.find('.mediat_asset-card.status-completed').length;

            const $summaryOriginal = $('#mediat_summary-original');
            $summaryOriginal.find('.mediat_metric-value').text(totalOriginal);
            $summaryOriginal.find('.status-pending .mediat_block-value').text(pendingOriginal);
            $summaryOriginal.find('.status-in-progress .mediat_block-value').text(inProgressOriginal);
            $summaryOriginal.find('.status-completed .mediat_block-value').text(completedOriginal);

            // Update Original tab counter
            $('.mediat_switch-btn[data-view="original"] .mediat_counter').text(totalOriginal);

            // Helper for Edited view
            const $editedGrid = $('#mediat_grid-edited');
            const totalEdited = $editedGrid.find('.mediat_asset-card').length;
            const downloadedEdited = $editedGrid.find('.mediat_asset-card.status-downloaded').length;
            const notDownloadedEdited = $editedGrid.find('.mediat_asset-card.status-not-dl').length;

            const $summaryEdited = $('#mediat_summary-edited');
            $summaryEdited.find('.mediat_metric-value').text(totalEdited);
            $summaryEdited.find('.status-downloaded .mediat_block-value').text(downloadedEdited);
            $summaryEdited.find('.status-not-dl .mediat_block-value').text(notDownloadedEdited);

            // Update Edited tab counter
            $('.mediat_switch-btn[data-view="edited"] .mediat_counter').text(totalEdited);

            // Also update "Download All" buttons if they exist
            $('#mediat_actions-original .btn-download-all .mediat_btn-counter').text(totalOriginal);
            $('#mediat_actions-edited .btn-download-all .mediat_btn-counter').text(totalEdited);
            $('.btn-download-pending .mediat_btn-counter').text(pendingOriginal);
            $('.btn-download-unread .mediat_btn-counter').text(notDownloadedEdited);
        }

        // Initial update
        updateSelectionState();
        updateStatusMetrics();

        /* ==================================================================
           Reusable Bulk Action Functions (Core API Integrations)
           ================================================================== */

        /**
         * Performs a bulk status change on the provided array of task IDs.
         *
         * @param {Array} taskIds Array of post IDs to update.
         * @param {string} newState The target status (e.g. 'pending', 'in-progress').
         * @param {jQuery} $visualBtn Optional button to attach loading animations.
         */
        function performBulkStatusChange(taskIds, newState, $visualBtn) {
            if (!taskIds || taskIds.length === 0) return;

            // Visual feedback: briefly scale up the button
            if ($visualBtn) {
                $visualBtn.css('transform', 'scale(1.2)');
                setTimeout(() => $visualBtn.css('transform', ''), 300);
            }

            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'mediat_bulk_status_change',
                    nonce: mediat_ajax_obj.nonce,
                    task_ids: taskIds,
                    new_status: 'mediat_' + newState.replace(/-/g, '_')
                },
                beforeSend: function () {
                    if ($visualBtn) $visualBtn.find('.dashicons').addClass('is-spinning');
                },
                success: function (response) {
                    if (response.success) {
                        taskIds.forEach(id => {
                            const $card = $(`.mediat_asset-card[data-post-id="${id}"]`);
                            $card.removeClass('status-pending status-in-progress status-completed');
                            $card.addClass(`status-${newState}`);
                            // Deselect cards after update
                            $card.removeClass('is-selected');
                        });
                        updateSelectionState();
                        updateStatusMetrics();
                    } else {
                        showErrorDialog(response.data.message || 'Error updating status.');
                    }
                },
                error: function () {
                    showErrorDialog('Failed to update tasks.');
                },
                complete: function () {
                    if ($visualBtn) $visualBtn.find('.dashicons').removeClass('is-spinning');
                }
            });
        }

        /**
         * Initiates a bulk download for the provided task IDs.
         *
         * @param {Array} taskIds Array of post IDs to download.
         * @param {jQuery} $btn Optional button to attach loading animations.
         */
        function performBulkDownload(taskIds, $btn) {
            console.log('performBulkDownload', taskIds);
            if (!taskIds || taskIds.length === 0) return;
            if (downloadInProgress) return;
            downloadInProgress = true;

            let originalHtml = '';
            if ($btn) {
                originalHtml = $btn.html();
                $btn.prop('disabled', true);
                $btn.html('<span class="dashicons dashicons-update is-spinning"></span> Sending…');
            }

            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'mediat_bulk_download',
                    nonce: mediat_ajax_obj.nonce,
                    task_ids: taskIds
                },
                success: function (response) {
                    if (response.success && response.data.download_url) {
                        window.location.href = response.data.download_url;

                        // UI Update for downloaded items
                        if (response.data.updated_ids && response.data.updated_ids.length > 0) {
                            response.data.updated_ids.forEach(id => {
                                const $card = $(`.mediat_asset-card[data-post-id="${id}"]`);
                                if ($card.hasClass('status-not-dl')) {
                                    $card.removeClass('status-not-dl').addClass('status-downloaded');
                                } else if ($card.hasClass('status-pending')) {
                                    $card.removeClass('status-pending').addClass('status-in-progress');

                                    // Update modal if this card is currently open
                                    const $modal = $('.mediat_viewer-modal');
                                    if ($modal.length && $modal.prop('open') && $modal.data('post-id') == id) {
                                        $('.mediat_modal-status-btn').removeClass('is-active');
                                        $('.mediat_modal-status-btn.in-progress').addClass('is-active');
                                        $('.mediat_modal-current-status').text('In-progress');
                                    }
                                }
                            });
                            updateStatusMetrics();
                        }

                        // Deselect cards after download
                        taskIds.forEach(id => {
                            $(`.mediat_asset-card[data-post-id="${id}"]`).removeClass('is-selected');
                        });
                        updateSelectionState();
                    } else {
                        showErrorDialog(response.data.message || 'Error preparing download.');
                    }
                },
                error: function () {
                    showErrorDialog('Failed to process download.');
                },
                complete: function () {
                    downloadInProgress = false;
                    if ($btn) {
                        $btn.prop('disabled', false);
                        $btn.html(originalHtml);
                    }
                }
            });
        }

        

        /**
         * Safely deletes the provided task IDs.
         *
         * @param {Array} idsToProcess Array of post IDs to delete.
         */
        function performBulkDelete(idsToProcess) {
            if (!idsToProcess || idsToProcess.length === 0) return;

            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'mediat_bulk_delete',
                    nonce: mediat_ajax_obj.nonce,
                    task_ids: idsToProcess
                },
                success: function (response) {
                    if (response.success) {
                        // Remove cards from DOM
                        idsToProcess.forEach(id => {
                            $(`.mediat_asset-card[data-post-id="${id}"]`).fadeOut(400, function () {
                                $(this).remove();
                            });
                        });

                        // Clean up empty date sections
                        setTimeout(() => {
                            $('.mediat_date-section').each(function () {
                                if ($(this).find('.mediat_asset-card').length === 0) {
                                    $(this).fadeOut(400, function () { $(this).remove(); });
                                }
                            });
                        }, 500);

                        updateSelectionState();
                        updateStatusMetrics();
                    } else {
                        showErrorDialog(response.data.message || 'Error deleting tasks.');
                    }
                },
                error: function () {
                    showErrorDialog('Failed to delete tasks.');
                }
            });
        }


        /* ==================================================================
           Event Listeners: Selection Toggling
           ================================================================== */

        // Individual Card Selector (Checkbox Overlay)
        $(document).on('click', '.mediat_selector', function (e) {
            e.stopPropagation();
            const $card = $(this).closest('.mediat_asset-card');
            $card.toggleClass('is-selected');
            updateSelectionState();
        });

        // Selection mode: clicking anywhere on the card toggles selection if we are already in selection mode
        $(document).on('click', '.mediat_asset-card', function (e) {
            // Only trigger if we are in selection mode
            if (!$mainWorkspace.hasClass('selection-mode')) return;

            // Skip if clicking interactive elements within the card (except the selector itself)
            if ($(e.target).closest('.mediat_inline-discussion, .mediat_info-trigger').length) return;

            // If we click the selector, the existing handler above will handle it.
            // But if we click the card but NOT the selector, we toggle selection.
            if (!$(e.target).closest('.mediat_selector').length) {
                const $card = $(this);
                $card.toggleClass('is-selected');
                updateSelectionState();
            }
        });

        // Deselect All Button (on floating menu)
        $('.action-deselect').on('click', function () {
            $('.mediat_asset-card').removeClass('is-selected');
            updateSelectionState();
        });

        // Global Select All Button (optional support if present in main UI)
        $('.btn-select-all').on('click', function () {
            $('.mediat_asset-card:visible').addClass('is-selected');
            updateSelectionState();
        });

        // Download All (Global)
        $('.btn-download-all').on('click', function () {
            const $btn = $(this);
            const view = $btn.closest('.mediat_action-toolbar').attr('id').includes('original') ? 'original' : 'edited';
            const $grid = view === 'original' ? $('#mediat_grid-original') : $('#mediat_grid-edited');
            const ids = [];
            $grid.find('.mediat_asset-card').each(function () {
                const id = $(this).data('post-id');
                if (id) ids.push(id);
            });
            if (ids.length > 0) {
                performBulkDownload(ids, $btn);
            }
        });

        // Download All Pending (Global - Original View)
        $('.btn-download-pending').on('click', function () {
            const $btn = $(this);
            const $grid = $('#mediat_grid-original');
            const ids = [];
            $grid.find('.mediat_asset-card.status-pending').each(function () {
                const id = $(this).data('post-id');
                if (id) ids.push(id);
            });
            if (ids.length > 0) {
                performBulkDownload(ids, $btn);
            }
        });

        // Download Not Downloaded (Global - Edited View)
        $('.btn-download-unread').on('click', function () {
            const $btn = $(this);
            const $grid = $('#mediat_grid-edited');
            const ids = [];
            $grid.find('.mediat_asset-card.status-not-dl').each(function () {
                const id = $(this).data('post-id');
                if (id) ids.push(id);
            });
            if (ids.length > 0) {
                performBulkDownload(ids, $btn);
            }
        });

        /* ==================================================================
           Event Listeners: Floating Action Menu (Global Selections)
           ================================================================== */

        $('.mediat_floating-controls .mediat_state-btn').on('click', function () {
            const $btn = $(this);
            const newState = $btn.data('state');
            performBulkStatusChange(selectedIds, newState, $btn);
        });

        $('.action-download').on('click', function () {
            performBulkDownload(selectedIds, $(this));
        });

        

        $('.action-delete').on('click', function () {
            if (selectedIds.length === 0) return;

            // Generate list of names for confirmation
            let namesList = '<ul>';
            $('.mediat_asset-card.is-selected').each(function () {
                namesList += '<li>' + $(this).find('.mediat_asset-name').text() + '</li>';
            });
            namesList += '</ul>';

            if (window.MEDIAT_Dialog) {
                window.MEDIAT_Dialog.show({
                    type: 'confirm',
                    title: 'Bulk Delete',
                    message: `Are you sure you want to delete the following tasks and their associated media? This cannot be undone: ${namesList}`,
                    confirmText: 'Delete Forever',
                    confirmClass: 'mediat_btn-danger',
                    onConfirm: function () {
                        performBulkDelete(selectedIds);
                    }
                });
            } else if (confirm(`Are you sure you want to delete ${selectedIds.length} tasks?`)) {
                performBulkDelete(selectedIds);
            }
        });

        /* ==================================================================
           Event Listeners: Date Header Actions (Grouped Selections)
           ================================================================== */

        /**
         * Helper getting all task IDs from a date section
         */
        function getIdsFromDateSection($btn) {
            const $dateSection = $btn.closest('.mediat_date-section');
            const ids = [];
            $dateSection.find('.mediat_asset-card').each(function () {
                const id = $(this).data('post-id');
                if (id) ids.push(id);
            });
            return ids;
        }

        $(document).on('click', '.mediat_date-header .mediat_state-btn', function (e) {
            e.preventDefault();
            const $btn = $(this);
            const idsProcess = getIdsFromDateSection($btn);
            if (idsProcess.length > 0) {
                performBulkStatusChange(idsProcess, $btn.data('state'), $btn);
            }
        });

        $(document).on('click', '.mediat_date-header .action-dl-date', function (e) {
            e.preventDefault();
            const $btn = $(this);
            const idsProcess = getIdsFromDateSection($btn);
            if (idsProcess.length > 0) {
                performBulkDownload(idsProcess, $btn);
            }
        });

        

        $(document).on('click', '.mediat_date-header .action-rm-date', function (e) {
            e.preventDefault();
            const $btn = $(this);
            const idsProcess = getIdsFromDateSection($btn);
            const $dateSection = $btn.closest('.mediat_date-section');

            if (idsProcess.length > 0) {
                let namesList = '<ul>';
                $dateSection.find('.mediat_asset-name').each(function () {
                    namesList += '<li>' + $(this).text() + '</li>';
                });
                namesList += '</ul>';

                if (window.MEDIAT_Dialog) {
                    window.MEDIAT_Dialog.show({
                        type: 'confirm',
                        title: 'Delete Date Set',
                        message: `Are you sure you want to delete all ${idsProcess.length} tasks from this date? This cannot be undone: ${namesList}`,
                        confirmText: 'Delete Forever',
                        confirmClass: 'mediat_btn-danger',
                        onConfirm: function () {
                            performBulkDelete(idsProcess);
                        }
                    });
                } else if (confirm(`Are you sure you want to delete ${idsProcess.length} tasks?`)) {
                    performBulkDelete(idsProcess);
                }
            }
        });

        /* ==================================================================
           Event Listeners: Modal Actions
           ================================================================== */

        

        // Export public methods
        window.MEDIAT_FloatingMenu = {
            updateStatusMetrics: updateStatusMetrics,
            performBulkDownload: performBulkDownload
        };

    });

})(jQuery);
