/**
 * MediaTasker — Task Modal & Comments
 *
 * Handles the viewer modal (single task details), status changes from modal,
 * modal download/delete actions, and all comment CRUD (modal + inline).
 *
 * @package MediaTasker
 */

/* global jQuery, mediat_ajax_obj */

(function ($) {
    'use strict';

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

        /* ==================================================================
           Modals & Comments
           ================================================================== */
        var $overlay = $('.mediat_overlay-backdrop');
        var $viewerModal = $('.mediat_viewer-modal');
        var modifiedPosts = new Set(); // Track posts with comment changes in modal

        // Close modals on overlay click
        $overlay.on('click', function () {
            hideModals();
        });

        // Open viewer modal (Single Task Details)
        $(document).on('click', '.mediat_info-trigger, .mediat_asset-visual', function (e) {
            if ($workspace.hasClass('selection-mode')) return; // Skip if in selection mode
            if ($(e.target).closest('.mediat_selector').length) return; // Ignore if clicking checkbox overlay
            
            e.stopPropagation();

            var $card = $(this).closest('.mediat_asset-card');
            var nameHtml = $card.find('.mediat_asset-name').html();
            var $img = $card.find('.mediat_preview-img');
            var fullSrc = $img.data('full-img') || $img.attr('src');
            var postId = $card.data('post-id');

            if (fullSrc) {
                var $threadList = $viewerModal.find('.mediat_thread-list');
                var $threadForm = $viewerModal.find('.mediat_thread-form');


                var $currentStatusText = $viewerModal.find('.mediat_modal-current-status');
                var $statusButtons = $viewerModal.find('.mediat_modal-status-btn');

                $viewerModal.find('.mediat_asset-preview').attr('src', fullSrc);
                $viewerModal.find('.mediat_asset-title').html(nameHtml).attr('title', $card.find('.mediat_asset-name').text());
                $threadForm.data('post-id', postId);
                $viewerModal.data('post-id', postId); // Store post ID on modal for actions

                // Clear previous info
                $threadList.html('<p class="mediat_loading-msg" style="padding:15px;text-align:center;">Loading discussion...</p>');



                $overlay.addClass('is-active');
                $viewerModal.prop('open', true);

                

                // Fetch details via AJAX
                $.ajax({
                    url: mediat_ajax_obj.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'mediat_get_task_details',
                        nonce: mediat_ajax_obj.nonce,
                        post_id: postId
                    },
                    success: function (response) {
                        if (response.success && response.data) {
                            var info = response.data.image_info;

                            // Populate Info
                            

                            

                            // Status handling
                            var simplifiedStatus = info.status.replace('mediat_', '').replace('_', '-');
                            $statusButtons.removeClass('is-active');
                            $statusButtons.filter('.' + simplifiedStatus).addClass('is-active');
                            $currentStatusText.text(simplifiedStatus.charAt(0).toUpperCase() + simplifiedStatus.slice(1));



                            // Comments handling
                            $threadList.html(response.data.comments_html);
                            $threadList.scrollTop($threadList[0].scrollHeight);
                        } else {
                            $threadList.html('<p class="mediat_error-msg" style="padding:15px;color:red;text-align:center;">Error loading details.</p>');
                        }
                    },
                    error: function () {
                        $threadList.html('<p class="mediat_error-msg" style="padding:15px;color:red;text-align:center;">Failed to load details.</p>');
                    }
                });
            }
        });

        // Modal Status Change
        $(document).on('click', '.mediat_modal-status-btn', function () {
            var $btn = $(this);
            var status = $btn.data('status');
            var postId = $viewerModal.data('post-id');
            var fullStatus = (status === 'pending' || status === 'completed' || status === 'in-progress') ? 'mediat_' + status.replace('-', '_') : status;

            if ($btn.hasClass('is-active') || !postId) return;

            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'mediat_bulk_status_change',
                    nonce: mediat_ajax_obj.nonce,
                    task_ids: [postId],
                    new_status: fullStatus
                },
                success: function (response) {
                    if (response.success) {
                        $('.mediat_modal-status-btn').removeClass('is-active');
                        $btn.addClass('is-active');
                        $('.mediat_modal-current-status').text(status.charAt(0).toUpperCase() + status.slice(1));

                        // Update visual card in grid
                        var $card = $(`.mediat_asset-card[data-post-id="${postId}"]`);
                        $card.removeClass('status-pending status-in-progress status-completed status-downloaded status-not-dl')
                            .addClass('status-' + status);

                        if (window.MEDIAT_FloatingMenu && window.MEDIAT_FloatingMenu.updateStatusMetrics) {
                            window.MEDIAT_FloatingMenu.updateStatusMetrics();
                        }
                    }
                }
            });
        });



        // Submit comment from Modal
        $(document).on('submit', '.mediat_thread-form', function (e) {
            e.preventDefault();
            var $form = $(this);
            var $input = $form.find('.mediat_thread-input');
            var $btn = $form.find('.mediat_thread-submit');
            var $threadList = $form.siblings('.mediat_thread-list');
            var postId = $form.data('post-id');
            var comment = $input.val().trim();

            if (!comment || !postId || $btn.prop('disabled')) return;

            $btn.prop('disabled', true).text('...');

            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'mediat_add_comment',
                    nonce: mediat_ajax_obj.nonce,
                    post_id: postId,
                    comment: comment
                },
                success: function (response) {
                    if (response.success && response.data) {
                        $threadList.find('.mediat_no-comments').remove();
                        $threadList.append(response.data.comment_html);
                        $input.val('');
                        $threadList.scrollTop($threadList[0].scrollHeight);
                        modifiedPosts.add(postId);
                    } else {
                        window.MEDIAT_Dialog.show({
                            title: 'Error',
                            message: response.data.message || 'Error posting comment.',
                            confirmClass: 'mediat_btn-danger'
                        });
                    }
                },
                error: function () {
                    window.MEDIAT_Dialog.show({
                        title: 'Error',
                        message: 'Error posting comment.',
                        confirmClass: 'mediat_btn-danger'
                    });
                },
                complete: function () {
                    $btn.prop('disabled', false).text('Send');
                }
            });
        });

        // Inline quick comment form
        $(document).on('submit', '.mediat_inline-thread-form', function (e) {
            e.preventDefault();
            var $form = $(this);
            var $input = $form.find('textarea[name="comment"]');
            var $btn = $form.find('button[type="submit"]');
            var $threadList = $form.siblings('.mediat_thread-list');
            var postId = $form.data('post-id');
            var comment = $input.val().trim();

            if (!comment || !postId || $btn.prop('disabled')) return;

            $btn.prop('disabled', true);
            var originalPlaceholder = $input.attr('placeholder');
            $input.attr('placeholder', 'Sending...').val('');

            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'mediat_add_comment',
                    nonce: mediat_ajax_obj.nonce,
                    post_id: postId,
                    comment: comment
                },
                success: function (response) {
                    if (response.success && response.data) {
                        $threadList.append(response.data.comment_html);
                        $input.attr('placeholder', 'Sent!');
                        setTimeout(function () {
                            $input.attr('placeholder', originalPlaceholder);
                        }, 2000);
                        // Scroll to bottom
                        $threadList.scrollTop($threadList[0].scrollHeight);
                    } else {
                        window.MEDIAT_Dialog.show({
                            title: 'Error',
                            message: response.data.message || 'Error posting comment.',
                            confirmClass: 'mediat_btn-danger'
                        });
                        $input.val(comment).attr('placeholder', originalPlaceholder);
                    }
                },
                error: function () {
                    window.MEDIAT_Dialog.show({
                        title: 'Error',
                        message: 'Error posting comment.',
                        confirmClass: 'mediat_btn-danger'
                    });
                    $input.val(comment).attr('placeholder', originalPlaceholder);
                },
                complete: function () {
                    $btn.prop('disabled', false);
                }
            });
        });

        // Edit Comment
        $(document).on('click', '.mediat_edit-comment', function (e) {
            e.preventDefault();
            var $btn = $(this);
            var $commentItem = $btn.closest('.mediat_thread-item');
            var $textDiv = $commentItem.find('.mediat_thread-text');
            var commentId = $commentItem.data('comment-id');

            // Avoid multiple edit forms
            if ($commentItem.hasClass('is-editing')) return;
            $commentItem.addClass('is-editing');

            // Get current text, normalize breaks to newlines roughly
            var currentHtml = $textDiv.html();
            // Simple br to newline conversion
            var currentText = currentHtml.replace(/<br\s*[\/]?>/gi, "\n").replace(/<p[^>]*>/g, "").replace(/<\/p>/g, "\n\n").trim();
            // Basic stripping of remaining tags for edit mode
            var div = document.createElement("div");
            div.innerHTML = currentText;
            var cleanText = div.textContent || div.innerText || "";

            var $editForm = $('<form class="mediat_edit-form" style="margin-top:10px;"></form>');
            var $textarea = $('<textarea class="mediat_edit-input" style="width:100%; min-height:60px;"></textarea>').val(cleanText);
            var $saveBtn = $('<button type="submit" class="mediat_btn-primary" style="padding: 4px 10px; font-size: 12px; margin-right: 5px;">Save</button>');
            var $cancelBtn = $('<button type="button" class="mediat_btn-neutral mediat_cancel-edit" style="padding: 4px 10px; font-size: 12px;">Cancel</button>');

            $editForm.append($textarea).append('<div style="margin-top:5px;"></div>').find('div').append($saveBtn).append($cancelBtn);

            $textDiv.hide().after($editForm);

            $cancelBtn.on('click', function () {
                $editForm.remove();
                $textDiv.show();
                $commentItem.removeClass('is-editing');
            });

            $editForm.on('submit', function (e) {
                e.preventDefault();
                var newText = $textarea.val().trim();
                if (!newText) return;

                $saveBtn.prop('disabled', true).text('Saving...');
                $cancelBtn.prop('disabled', true);

                $.ajax({
                    url: mediat_ajax_obj.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'mediat_edit_comment',
                        nonce: mediat_ajax_obj.nonce,
                        comment_id: commentId,
                        comment: newText
                    },
                    success: function (response) {
                        if (response.success && response.data) {
                            var $newComment = $(response.data.comment_html);
                            $commentItem.replaceWith($newComment);
                            var postId = $viewerModal.data('post-id');
                            if (postId) modifiedPosts.add(postId);
                        } else {
                            window.MEDIAT_Dialog.show({
                                title: 'Error',
                                message: response.data.message || 'Error updating comment.',
                                confirmClass: 'mediat_btn-danger'
                            });
                            $saveBtn.prop('disabled', false).text('Save');
                            $cancelBtn.prop('disabled', false);
                        }
                    },
                    error: function () {
                        window.MEDIAT_Dialog.show({
                            title: 'Error',
                            message: 'Error updating comment.',
                            confirmClass: 'mediat_btn-danger'
                        });
                        $saveBtn.prop('disabled', false).text('Save');
                        $cancelBtn.prop('disabled', false);
                    }
                });
            });
        });

        // Delete Comment
        $(document).on('click', '.mediat_delete-comment', function (e) {
            e.preventDefault();
            var $btn = $(this);
            var $commentItem = $btn.closest('.mediat_thread-item');
            var commentId = $commentItem.data('comment-id');

            var originalHtml = $btn.html();

            window.MEDIAT_Dialog.show({
                type: 'confirm',
                title: 'Delete Comment',
                message: 'Are you sure you want to delete this comment?',
                confirmText: 'Yes, delete',
                cancelText: 'No, keep it',
                confirmClass: 'mediat_btn-danger',
                onConfirm: function () {
                    $btn.html('...').prop('disabled', true);

                    $.ajax({
                        url: mediat_ajax_obj.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'mediat_delete_comment',
                            nonce: mediat_ajax_obj.nonce,
                            comment_id: commentId
                        },
                        success: function (response) {
                            if (response.success) {
                                var $threadList = $commentItem.closest('.mediat_thread-list');
                                $commentItem.fadeOut(300, function () {
                                    $(this).remove();
                                    var postId = $viewerModal.data('post-id');
                                    if (postId) modifiedPosts.add(postId);
                                    // If it was the last comment, we could show the "No comments yet" message
                                    if ($threadList.find('.mediat_thread-item').length === 0) {
                                        $threadList.html('<p class="mediat_no-comments" style="padding:15px; text-align:center; color:#646970;">No comments yet. Be the first to start the discussion!</p>');
                                    }
                                });
                            } else {
                                window.MEDIAT_Dialog.show({
                                    title: 'Error',
                                    message: response.data.message || 'Error deleting comment.',
                                    confirmClass: 'mediat_btn-danger'
                                });
                                $btn.html(originalHtml).prop('disabled', false);
                            }
                        },
                        error: function () {
                            window.MEDIAT_Dialog.show({
                                title: 'Error',
                                message: 'Error deleting comment.',
                                confirmClass: 'mediat_btn-danger'
                            });
                            $btn.html(originalHtml).prop('disabled', false);
                        }
                    });
                }
            });
        });

        $('.mediat_viewer-close').on('click', hideModals);

        // Viewer navigation (Prev / Next)
        $(document).on('click', '.mediat_nav-btn', function () {
            var $btn = $(this);
            var direction = $btn.hasClass('nav-next') ? 'next' : 'prev';

            var currentPostId = $viewerModal.data('post-id');
            if (!currentPostId) return;

            // Collect visible cards in DOM order
            var $visibleCards = $workspace.find('.mediat_asset-card:visible');
            if ($visibleCards.length < 2) return; // Nothing to navigate to

            // Find current index
            var currentIndex = -1;
            $visibleCards.each(function (i) {
                if ($(this).data('post-id') == currentPostId) {
                    currentIndex = i;
                    return false;
                }
            });

            if (currentIndex === -1) return;

            // Determine next index (wrap around)
            var nextIndex;
            if (direction === 'next') {
                nextIndex = (currentIndex + 1) % $visibleCards.length;
            } else {
                nextIndex = (currentIndex - 1 + $visibleCards.length) % $visibleCards.length;
            }

            var $nextCard = $visibleCards.eq(nextIndex);
            var $img = $nextCard.find('.mediat_preview-img');
            var fullSrc = $img.data('full-img') || $img.attr('src');
            var postId = $nextCard.data('post-id');
            var nameHtml = $nextCard.find('.mediat_asset-name').html();

            if (!fullSrc) return;

            // Update modal visuals
            $viewerModal.find('.mediat_asset-preview').attr('src', fullSrc);
            $viewerModal.find('.mediat_asset-title').html(nameHtml).attr('title', $nextCard.find('.mediat_asset-name').text());
            $viewerModal.find('.mediat_thread-form').data('post-id', postId);
            $viewerModal.data('post-id', postId);

            var $threadList = $viewerModal.find('.mediat_thread-list');
            $threadList.html('<p class="mediat_loading-msg" style="padding:15px;text-align:center;">Loading discussion...</p>');

            // Fetch details for new card
            $.ajax({
                url: mediat_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'mediat_get_task_details',
                    nonce: mediat_ajax_obj.nonce,
                    post_id: postId
                },
                success: function (response) {
                    if (response.success && response.data) {
                        var info = response.data.image_info;

                        

                        

                        var simplifiedStatus = info.status.replace('mediat_', '').replace('_', '-');
                        $viewerModal.find('.mediat_modal-status-btn').removeClass('is-active');
                        $viewerModal.find('.mediat_modal-status-btn').filter('.' + simplifiedStatus).addClass('is-active');
                        $viewerModal.find('.mediat_modal-current-status').text(simplifiedStatus.charAt(0).toUpperCase() + simplifiedStatus.slice(1));

                        $threadList.html(response.data.comments_html);
                        $threadList.scrollTop($threadList[0].scrollHeight);
                    } else {
                        $threadList.html('<p class="mediat_error-msg" style="padding:15px;color:red;text-align:center;">Error loading details.</p>');
                    }
                },
                error: function () {
                    $threadList.html('<p class="mediat_error-msg" style="padding:15px;color:red;text-align:center;">Failed to load details.</p>');
                }
            });
        });

        // Download from Modal
        $(document).on('click', '.mediat_viewer-footer .action-dl', function () {
            var postId = $viewerModal.data('post-id');
            if (!postId) return;

            // Trigger bulk download mechanism for single ID
            if (window.MEDIAT_FloatingMenu && window.MEDIAT_FloatingMenu.performBulkDownload) {
                window.MEDIAT_FloatingMenu.performBulkDownload([postId]);
            }
        });

        // Delete from Modal
        $(document).on('click', '.mediat_viewer-footer .action-rm', function () {
            var postId = $viewerModal.data('post-id');
            if (!postId) return;

            window.MEDIAT_Dialog.show({
                type: 'confirm',
                title: 'Delete Image',
                message: 'Are you sure you want to delete this image? This action cannot be undone.',
                confirmText: 'Yes, delete it',
                confirmClass: 'mediat_btn-danger',
                onConfirm: function () {
                    $.ajax({
                        url: mediat_ajax_obj.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'mediat_bulk_delete',
                            nonce: mediat_ajax_obj.nonce,
                            task_ids: [postId]
                        },
                        success: function (response) {
                            if (response.success) {
                                hideModals();
                                $(`.mediat_asset-card[data-post-id="${postId}"]`).fadeOut(400, function () {
                                    $(this).remove();
                                });
                                if (window.MEDIAT_FloatingMenu && window.MEDIAT_FloatingMenu.updateStatusMetrics) {
                                    window.MEDIAT_FloatingMenu.updateStatusMetrics();
                                }
                            }
                        }
                    });
                }
            });
        });

        function hideModals() {
            $overlay.removeClass('is-active');
            $viewerModal.prop('open', false);
            $('.mediat_dialog').prop('open', false);

            if (modifiedPosts.size > 0) {
                modifiedPosts.forEach(function (postId) {
                    if (window.MEDIAT_Frontend && window.MEDIAT_Frontend.refreshComments) {
                        window.MEDIAT_Frontend.refreshComments(postId);
                    }
                });
                modifiedPosts.clear();
            }
        }

        /**
         * Refreshes the comments list for a specific task card.
         * Useful for updating UI after bulk actions.
         */
        window.MEDIAT_Frontend = {
            refreshComments: function (postId) {
                var $card = $(`.mediat_asset-card[data-post-id="${postId}"]`);
                if (!$card.length) return;

                var $threadList = $card.find('.mediat_thread-list');

                $.ajax({
                    url: mediat_ajax_obj.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'mediat_get_task_details',
                        nonce: mediat_ajax_obj.nonce,
                        post_id: postId
                    },
                    success: function (response) {
                        if (response.success && response.data) {
                            $threadList.html(response.data.comments_html);
                            $threadList.scrollTop($threadList[0].scrollHeight);
                        }
                    }
                });
            }
        };
    });
})(jQuery);
