@php
    $videoOwnerId = $video->user_id ?? null;
    $pinnedComments = $comments->filter(function ($comment) use ($videoOwnerId) {
        if (auth()->id() === $videoOwnerId || auth()->id() === $comment->user_id) {
            return $comment->pinned;
        }
        return $comment->pinned && !$comment->is_hidden;
    });

    $otherComments = $comments->filter(function ($comment) use ($videoOwnerId) {
        if (auth()->id() === $videoOwnerId || auth()->id() === $comment->user_id) {
            return !$comment->pinned;
        }
        return !$comment->pinned && !$comment->is_hidden;
    });
@endphp



<h5 class="comment-pinned-title mt-4" @if ($pinnedComments->count() == 0) style="display:none;" @endif>
    <i class="las la-thumbtack"></i> @lang('Pinned Comments')
</h5>

<div class="pinned-comment-section">
    @foreach ($pinnedComments as $comment)
        @include($activeTemplate . 'partials.video.comment', ['comment' => $comment])
    @endforeach
</div>

<h5 class="all-comment-title mt-4 mb-4" @if ($otherComments->count() == 0) style="display:none;" @endif>
    @lang('All Comments')
</h5>

<div class="all-comment-section">
    @foreach ($otherComments as $comment)
        @include($activeTemplate . 'partials.video.comment', ['comment' => $comment])
    @endforeach
</div>


<x-confirmation-modal frontend='true' />

@push('script')
    <script>
        $(document).ready(function() {
            const currentUserId = {{ auth()->id() ?? 'null' }};
            $(document).on('click', '.pin-comment-btn', function() {
                let button = $(this);
                let commentId = button.data('id');
                let commentBox = $('#parent-comment-' + commentId);

                $.ajax({
                    url: '{{ route('user.comment.pin', ':id') }}'.replace(':id', commentId),
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {

                        if (response.data.pinned) {
                            $('.pinned-comment-section .parent-comment-wrapper').each(
                                function() {
                                    let existing = $(this);
                                    if (existing.attr('id') !== 'parent-comment-' +
                                        commentId) {
                                        existing.detach();
                                        if ($('#' + existing.attr('id')).closest(
                                                '.all-comment-section').length === 0) {
                                            $('.all-comment-section').prepend(existing);
                                        }
                                    }
                                });

                            if ($('#' + commentBox.attr('id')).closest(
                                    '.pinned-comment-section').length === 0) {
                                commentBox.detach();
                                $('.pinned-comment-section').prepend(commentBox);
                            }

                        } else {
                            if ($('#' + commentBox.attr('id')).closest('.all-comment-section')
                                .length === 0) {
                                commentBox.detach();
                                $('.all-comment-section').prepend(commentBox);
                            }
                        }

                        $('.pin-comment-btn').each(function() {
                            let btn = $(this);
                            let id = btn.data('id');
                            if (id == commentId && response.data.pinned) {
                                btn.find('i').removeClass('fa-thumbtack pin').addClass(
                                    'fa-thumbtack unpin');
                            } else {
                                btn.find('i').removeClass('fa-thumbtack unpin')
                                    .addClass('fa-thumbtack pin');
                            }
                        });

                        if ($('.pin-comment-btn i.unpin').length === 0) {
                            $('.comment-pinned-title').css('display', 'none');
                        } else {
                            $('.comment-pinned-title').css('display', 'block');
                        }

                        if ($('.pin-comment-btn i.pin').length === 0) {
                            $('.all-comment-title').css('display', 'none');
                        } else {
                            $('.all-comment-title').css('display', 'block');
                        }

                    },
                    error: function(xhr) {
                        console.error(xhr.responseText);
                    }
                });
            });

            $(document).on('click', '.hide-comment-btn', function(e) {
                e.preventDefault();

                let button = $(this);
                let commentId = button.data('id');
                let commentBox = $('#comment-' + commentId);
                let icon = button.find('i');
                let manageOption = commentBox.find('.comment-manage-option');

                let pinWrapper = manageOption.find('.pin-btn-wrapper');
                let editWrapper = manageOption.find('.edit-btn-wrapper');

                $.ajax({
                    url: '{{ route('user.comment.toggleHide', ':id') }}'.replace(':id', commentId),
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.status === 'success') {
                            if (response.data.is_hidden) {
                                commentBox.addClass('hideComment');
                                icon.removeClass('fa-eye-slash').addClass('fa-eye');
                                pinWrapper.remove();
                                editWrapper.remove();
                            } else {
                                commentBox.removeClass('hideComment');
                                icon.removeClass('fa-eye').addClass('fa-eye-slash');

                                if (
                                    manageOption.find('.pin-btn-wrapper').length === 0 &&
                                    {{ auth()->id() === $video->user_id ? 'true' : 'false' }} &&
                                    commentBox.hasClass('parentComment')
                                ) {
                                    manageOption.prepend(`
                            <li class="pin-btn-wrapper">
                                <button class="pin-comment-btn comment-manage-btn" data-id="${commentId}">
                                    <i class="fa-solid fa-thumbtack"></i>
                                </button>
                            </li>
                        `);
                                }

                                if (
                                    manageOption.find('.edit-btn-wrapper').length === 0 &&
                                    {{ auth()->id() === @$comment->user_id ? 'true' : 'false' }}
                                ) {
                                    let hideWrapper = manageOption.find('.hide-btn-wrapper');
                                    let editBtnHtml = `
                            <li class="edit-btn-wrapper">
                                <button class="edit-comment-btn comment-manage-btn" data-id="${commentId}">
                                    <i class="fa-solid fa-pen-to-square"></i>
                                </button>
                            </li>
                        `;
                                    if (hideWrapper.length) {
                                        $(editBtnHtml).insertAfter(hideWrapper);
                                    } else {
                                        manageOption.append(editBtnHtml);
                                    }
                                }
                            }
                        } else {
                            alert(response.message || 'Something went wrong');
                        }
                    },
                    error: function(xhr) {
                        let msg = 'Something went wrong';
                        if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON
                            .message;
                        alert(msg);
                    }
                });
            });


            $(document).on('click', '.delete-comment-btn', function(e) {
                e.preventDefault();

                let button = $(this);
                let commentId = button.data('id');
                let actionUrl = '{{ route('user.comment.delete', ':id') }}'.replace(':id', commentId);

                const modal = $('#confirmationModal');
                const form = modal.find('form');

                modal.find('.question').text('Are you sure you want to delete this comment?');
                form.attr('action', actionUrl);
                modal.modal('show');

                form.off('submit').on('submit', function(e) {
                    e.preventDefault();

                    $.ajax({
                        url: actionUrl,
                        type: 'POST',
                        data: {
                            _token: '{{ csrf_token() }}',
                            _method: 'DELETE'
                        },
                        success: function(response) {
                            if (response.status === 'success') {
                                let parentWrapper = $('#parent-comment-' + commentId);
                                if (parentWrapper.length) {
                                    parentWrapper.fadeOut(function() {
                                        $(this).remove();
                                        $('.comment-pinned-title').css(
                                            'display', 'none');
                                    });
                                } else {
                                    $('#comment-' + commentId).fadeOut(function() {
                                        $(this).remove();
                                        $('.comment-pinned-title').css(
                                            'display', 'none');

                                    });
                                }

                                let countEl = $('.commentCount').first();
                                let currentCount = parseInt(countEl.text()) || 0;
                                countEl.text(Math.max(0, currentCount - 1));
                            } else {
                                alert(response.message || 'Something went wrong');
                            }
                            modal.modal('hide');
                        },
                        error: function(xhr) {
                            let msg = 'Something went wrong';
                            if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr
                                .responseJSON.message;
                            alert(msg);
                            modal.modal('hide');
                        }
                    });
                });
            });




            $(document).on('click', '.edit-comment-btn', function(e) {
                e.preventDefault();

                const commentBox = $(this).closest('.comment-box-item__content');
                const commentTextEl = commentBox.find('.comment-box-item__text').first();
                const oldText = commentTextEl.text().trim();

                if (commentBox.find('.edit-form').length > 0) return;

                commentTextEl.hide();

                const editForm = $(`
        <form class="edit-form mb-3">
            <input name="reply_to" type="hidden" value="{{ @$comment->id }}" />
            <textarea class="form--control edit-form__textarea commentBox edited-text" name="comment" placeholder="Add a comment">${oldText}</textarea>
            <div class="edit-form__input-btn">
                <button class="edit-form__btn" type="submit">
                    <i class="las la-paper-plane"></i>
                </button>
                <button type="button" class="cancel-edit-btn">
                    <i class="fa-solid fa-xmark"></i>
                </button>
            </div>
        </form>
    `);

                commentTextEl.after(editForm);
            });


            $(document).on('click', '.cancel-edit-btn', function() {
                const form = $(this).closest('.edit-form');
                const commentBox = form.closest('.comment-box-item__content');
                commentBox.find('.comment-box-item__text').show();
                form.remove();
            });

            $(document).on('keydown', '.edit-form__textarea', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    $(this).closest('.edit-form').submit();
                }
            });

            $(document).on('submit', '.edit-form', function(e) {
                e.preventDefault();

                const form = $(this);
                const commentBox = form.closest('.comment-box-item__content');
                const commentId = form.closest('.comment-box-item').attr('id').replace('comment-', '');
                const newText = form.find('.edited-text').val().trim();

                if (!newText) {
                    alert("Comment cannot be empty!");
                    return;
                }

                $.ajax({
                    type: 'POST',
                    url: '{{ route('user.comment.edit', ':id') }}'.replace(':id', commentId),
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    data: {
                        comment: newText
                    },
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            commentBox.find('.comment-box-item__text').text(newText).show();
                            form.remove();
                        } else {
                            alert(response.message || 'Something went wrong');
                        }
                    },
                    error: function(xhr) {
                        alert(xhr.responseJSON?.message || 'Something went wrong');
                    }
                });
            });
        });
    </script>
@endpush
