<?php $attributes ??= new \Illuminate\View\ComponentAttributeBag;

$__newAttributes = [];
$__propNames = \Illuminate\View\ComponentAttributeBag::extractPropNames((['post']));

foreach ($attributes->all() as $__key => $__value) {
    if (in_array($__key, $__propNames)) {
        $$__key = $$__key ?? $__value;
    } else {
        $__newAttributes[$__key] = $__value;
    }
}

$attributes = new \Illuminate\View\ComponentAttributeBag($__newAttributes);

unset($__propNames);
unset($__newAttributes);

foreach (array_filter((['post']), 'is_string', ARRAY_FILTER_USE_KEY) as $__key => $__value) {
    $$__key = $$__key ?? $__value;
}

$__defined_vars = get_defined_vars();

foreach ($attributes->all() as $__key => $__value) {
    if (array_key_exists($__key, $__defined_vars)) unset($$__key);
}

unset($__defined_vars); ?>

<div class="max-w-3xl mx-auto space-y-8">

    <h3 class="text-2xl font-bold text-gray-800 mb-6">Leave a Comment</h3>

    <!-- Success Message -->
    <div id="success-message" class="hidden p-4 rounded-lg bg-green-50 border border-green-200 transition-all duration-300"></div>

    <!-- Comment Form -->
    <form id="comment-form" action="<?php echo e(route('comments.store', $post->id)); ?>" method="POST" 
          class="p-6 rounded-lg shadow-sm border border-gray-100 transition-all duration-300 hover:shadow-md">
        <?php echo csrf_field(); ?>
        <div class="space-y-4">
            <input type="text" name="name" placeholder="Name" required class="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-blue-400">
            <input type="email" name="email" placeholder="Email" required class="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-blue-400">
            <input type="url" name="website" placeholder="Website (optional)" class="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-blue-400">
            <textarea name="content" placeholder="Write your comment..." required rows="4" class="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-blue-400"></textarea>
            <button type="submit" class="bg-blue-500 text-white px-6 py-2.5 rounded-lg hover:bg-blue-600">
                Post Comment
            </button>
        </div>
    </form>

    <!-- Comments Container -->
    <h1 class="text-2xl font-bold text-gray-800 flex items-center space-x-2">
        <span>Comments</span>
        <span class="bg-blue-500 text-white text-sm font-semibold px-3 py-1 rounded-full">
            <?php echo e($post->comments->count() + $post->comments->sum(fn($comment) => $comment->replies->count())); ?>

        </span>
    </h1>
    <div id="comments-container" class="space-y-6">

        <?php $__currentLoopData = $post->comments->whereNull('parent_id')->sortByDesc('created_at'); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $comment): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <?php echo $__env->make('comments.partials.comment', ['comment' => $comment], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </div>

</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const commentForm = document.getElementById('comment-form');

    // Handle main comment submission
    commentForm.addEventListener('submit', function (event) {
        event.preventDefault();
        submitComment(this);
    });

    // Event delegation for reply buttons
    document.getElementById('comments-container').addEventListener('click', function (e) {
        if (e.target.classList.contains('reply-btn')) {
            e.preventDefault();
            showReplyForm(e.target.dataset.commentId);
        }
    });
});

// Show Reply Form with Toggle Functionality
function showReplyForm(parentId) {
    const commentDiv = document.getElementById(`comment-${parentId}`);
    const formContainer = commentDiv.querySelector('.reply-form-container');

    // যদি ফর্ম আগে থেকে বিদ্যমান থাকে, তাহলে মুছে ফেলুন
    if (formContainer.innerHTML.trim() !== '') {
        formContainer.innerHTML = '';
        return;
    }

    // নতুন ফর্ম তৈরি করুন
    const formHtml = `
        <form class="reply-form mt-4 space-y-4" data-parent-id="${parentId}" 
              action="<?php echo e(route('comments.store', $post->id)); ?>" method="POST">
            <?php echo csrf_field(); ?>
            <input type="hidden" name="parent_id" value="${parentId}">
            <input type="text" name="name" placeholder="Name" required 
                   class="w-full px-4 py-2 border rounded-lg">
            <input type="email" name="email" placeholder="Email" required 
                   class="w-full px-4 py-2 border rounded-lg">
            <input type="url" name="website" placeholder="Website (optional)" class="w-full px-4 py-3 border rounded-lg focus:ring-2 focus:ring-blue-400">
            <textarea name="content" rows="2" required 
                      class="w-full px-4 py-2 border rounded-lg" 
                      placeholder="Write a reply..."></textarea>
            <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded-lg">
                Post Reply
            </button>
            <button type="button" class="cancel-reply ml-2 text-gray-600">
                Cancel
            </button>
        </form>
    `;

    // সব আগের রিপ্লাই ফর্ম মুছে ফেলুন
    document.querySelectorAll('.reply-form-container').forEach(container => {
        container.innerHTML = '';
    });

    formContainer.innerHTML = formHtml;

    // Cancel বাটন ইভেন্ট হ্যান্ডলার
    formContainer.querySelector('.cancel-reply').addEventListener('click', () => {
        formContainer.innerHTML = '';
    });

    // Reply form সাবমিশন হ্যান্ডলার
    formContainer.querySelector('.reply-form').addEventListener('submit', function(e) {
        e.preventDefault();
        submitComment(this);
    });
}

// Submit Comment (Main & Replies)
function submitComment(form) {
    fetch(form.action, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        },
        body: new FormData(form)
    })
    .then(response => response.json())
    .then(data => {
        if (data.comment) {
            const commentHtml = createCommentHtml(data.comment);
            if (data.comment.parent_id) {
                const parent = document.getElementById(`comment-${data.comment.parent_id}`);
                const repliesContainer = parent.querySelector('.replies') || createRepliesContainer(parent);
                repliesContainer.insertAdjacentHTML('beforeend', commentHtml);
            } else {
                document.getElementById('comments-container').insertAdjacentHTML('afterbegin', commentHtml);
            }
            form.reset();
            if (form.closest('.reply-form-container')) {
                form.closest('.reply-form-container').innerHTML = '';
            }
            showSuccessMessage("Comment added successfully!");
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert("Something went wrong. Please try again.");
    });
}

// Create Comment HTML
function createCommentHtml(comment) {
    return `
        <div id="comment-${comment.id}" class="p-4 rounded-lg border border-blue-400 hover:border-blue-700">
            <div class="flex items-center space-x-3">
                <div class="bg-gray-100 w-10 h-10 flex items-center justify-center rounded-full text-gray-600 font-bold">
                    ${comment.name.charAt(0).toUpperCase()}
                </div>
                <div>
                    <strong class="text-gray-800">${comment.name}</strong>
                    <div class="flex items-center text-gray-500 text-sm mt-1">
                        <i class="fas fa-clock mr-1"></i> Just now
                    </div>
                </div>
            </div>
            <p class="mt-3 text-gray-700 leading-relaxed">${comment.content}</p>
            <button class="reply-btn mt-2 text-blue-500 text-sm" data-comment-id="${comment.id}">Reply</button>
            <div class="reply-form-container"></div>
            <div class="replies pl-8 mt-4 space-y-4"></div>
        </div>
    `;
}

// Create Replies Container
function createRepliesContainer(parent) {
    const container = document.createElement('div');
    container.className = 'replies pl-8 mt-4 space-y-4';
    parent.appendChild(container);
    return container;
}

// Show success message
function showSuccessMessage(message) {
    const messageBox = document.getElementById('success-message');
    messageBox.textContent = message;
    messageBox.classList.remove('hidden');
    setTimeout(() => messageBox.classList.add('hidden'), 3000);
}
</script><?php /**PATH /home/laravel/portfoliio/resources/views/components/comment.blade.php ENDPATH**/ ?>