@extends('layouts.app2')

@section('title', 'Discussion Details')

@section('content')
<div class="container mx-auto p-6">
    <h1 class="text-3xl font-bold text-gray-800 dark:text-gray-100 mb-8">Discussion Details</h1>

  <!-- Question Section -->
<div class="bg-white dark:bg-gray-800 shadow-lg rounded-lg mb-6 p-6 hover:shadow-xl transition-shadow">
    <div class="flex justify-between items-start">
        <div class="flex items-start space-x-4">
            @if ($post->user->profile_picture)
                <!-- Show Profile Picture -->
                <img src="{{ $post->user->profile_picture }}" alt="User Avatar" class="w-12 h-12 rounded-full border-2 border-gray-300 dark:border-gray-700">
            @else
                <!-- Show Custom Avatar with Initials -->
                @php
                    $colors = ['bg-blue-500', 'bg-green-500', 'bg-red-500', 'bg-yellow-500', 'bg-purple-500', 'bg-pink-500', 'bg-indigo-500'];
                    $colorIndex = crc32($post->user->name) % count($colors);
                    $selectedColor = $colors[$colorIndex];
                    $nameParts = explode(' ', $post->user->name);
                    $initials = count($nameParts) > 1 
                        ? strtoupper(substr($nameParts[0], 0, 1)) . strtoupper(substr(end($nameParts), 0, 1))
                        : strtoupper(substr($nameParts[0], 0, 1));
                @endphp
                <div class="flex-none w-12 h-12 {{ $selectedColor }} text-white flex justify-center items-center rounded-full border-2 border-gray-300 dark:border-gray-700">
                    {{ $initials }}
                </div>
            @endif

            <!-- Post Header -->
            <div>
                <!-- Name, Username, and Green Dot -->
                <div class="flex items-center space-x-2">
                    <a href="#" class="text-base font-medium text-white hover:underline">{{ $post->user->name }}</a>
                    <div class="w-2 h-2 bg-green-500 rounded-full"></div> <!-- Green Dot -->
                    <button class="text-sm text-blue-400 hover:underline">Follow</button>
                </div>
                <!-- Username -->
                <div class="text-sm text-gray-400">
                    @<span>{{ $post->user->username }}</span>
                </div>
            </div>
        </div>

        <!-- More Button Dropdown -->
        <div class="relative">
            <button
                class="text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-300 transition"
                onclick="toggleDropdown(this)"
            >
                <i class="fas fa-ellipsis-v"></i>
            </button>
            <!-- Dropdown Menu -->
            <div
                class="absolute right-0 mt-2 w-40 bg-white dark:bg-gray-800 shadow-md rounded-lg overflow-hidden hidden"
                style="z-index: 10;"
            >
                <button class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                    <i class="far fa-bookmark mr-2"></i>Bookmark
                </button>
                <button class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                    <i class="fas fa-flag mr-2"></i>Report
                </button>
                <button class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                    <i class="fas fa-share mr-2"></i>Share
                </button>
                <button class="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700">
                    <i class="fas fa-copy mr-2"></i>Copy Link
                </button>
            </div>
        </div>
    </div>

    <!-- Post Content -->
    <div class="mt-4">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-100 mb-2">{{ $post->title }}</h2>
        <p class="text-gray-600 dark:text-gray-400 mb-4">{!! $post->body !!}</p>
    </div>

    <!-- Footer Section -->
    <div class="flex justify-between items-center mt-4 border-t pt-4 text-sm text-gray-500 dark:text-gray-400">
        <!-- Metadata -->
        <div>
            <span>{{ $post->created_at->diffForHumans() }}</span>
        </div>

        <!-- Voting and Comments -->
        <div class="flex items-center space-x-6">
            <!-- Upvotes -->
            <button id="questionUpvote" class="flex items-center space-x-1 text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-300 transition">
                <i class="far fa-thumbs-up text-lg"></i>
                <span id="questionUpvoteCount">{{ $post->upvotes_count }}</span>
            </button>
            
            <!-- Downvotes -->
            <button id="questionDownvote" class="flex items-center space-x-1 text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-300 transition">
                <i class="far fa-thumbs-down text-lg"></i>
                <span id="questionDownvoteCount">{{ $post->downvotes_count }}</span>
            </button>

            <!-- Comments -->
            <span class="flex items-center space-x-1">
                <i class="fas fa-comments text-lg"></i>
                <span>{{ $post->comments_count }} Comments</span>
            </span>
        </div>
    </div>
</div>


    <!-- Answers Section -->
    <div>
        <h3 class="text-2xl font-semibold text-gray-800 dark:text-gray-100 mb-4">Replies:</h3>
        @foreach ($post->comments as $comment)
        <!-- Answer Card -->
<div class="bg-gray-100 dark:bg-gray-800 shadow-md rounded-lg mb-4 p-6 hover:shadow-lg transition-shadow">
    <div class="flex justify-between items-start">
        <div class="flex items-start space-x-4">
            @if ($comment->user->profile_picture)
                <!-- Show Profile Picture -->
                <img src="{{ $comment->user->profile_picture }}" alt="User Avatar" class="w-12 h-12 rounded-full border-2 border-gray-300 dark:border-gray-700">
            @else
                <!-- Show Custom Avatar with Initials -->
                @php
                    $colors = ['bg-blue-500', 'bg-green-500', 'bg-red-500', 'bg-yellow-500', 'bg-purple-500', 'bg-pink-500', 'bg-indigo-500'];
                    $colorIndex = crc32($comment->user->name) % count($colors);
                    $selectedColor = $colors[$colorIndex];
                    $nameParts = explode(' ', $comment->user->name);
                    $initials = count($nameParts) > 1 
                        ? strtoupper(substr($nameParts[0], 0, 1)) . strtoupper(substr(end($nameParts), 0, 1))
                        : strtoupper(substr($nameParts[0], 0, 1));
                @endphp
                <div class="flex-none w-12 h-12 {{ $selectedColor }} text-white flex justify-center items-center rounded-full border-2 border-gray-300 dark:border-gray-700">
                    {{ $initials }}
                </div>
            @endif
            <div>
                <p class="text-gray-800 dark:text-gray-100 mb-4">{{ $comment->body }}</p>
                <div class="flex items-center space-x-4 text-gray-500 dark:text-gray-400 text-sm">
                    <span>Answered by <a href="#" class="text-blue-500 dark:text-blue-300 font-bold">{{ '@'.$comment->user->username }}</a></span>
                    <span>{{ $comment->created_at->diffForHumans() }}</span>
                </div>
            </div>
        </div>
        <div class="flex items-center space-x-2">
            <button class="answerUpvote flex items-center space-x-1 mr-2 text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-300 transition">
                <i class="fas fa-arrow-up"></i>
                <span class="answerUpvoteCount">{{ $comment->upvotes_count }}</span>
            </button>
            <button class="answerDownvote flex items-center space-x-1 text-gray-500 dark:text-gray-400 hover:text-blue-500 dark:hover:text-blue-300 transition">
                <i class="fas fa-arrow-down"></i>
                <span class="answerDownvoteCount">{{ $comment->downvotes_count }}</span>
            </button>
        </div>
    </div>

    <div class="mt-4 pl-6 border-l-2 border-gray-300 dark:border-gray-700">
    @if(count($comment->replies) > 0)
        <h4 class="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-4">Replies</h4>
    @endif
    @foreach ($comment->replies as $reply)
        <div class="bg-white dark:bg-gray-700 p-4 rounded-lg mb-4 hover:shadow-md transition-shadow">
            <div class="flex items-center space-x-4">
                <img src="{{ $reply->user->profile_picture ?? 'default-avatar.jpg' }}" alt="User Avatar" class="w-10 h-10 rounded-full border-2 border-gray-300 dark:border-gray-700">
                <div>
                    <p class="text-gray-800 dark:text-gray-100 font-medium">{{ $reply->body }}</p>
                    <div class="text-gray-500 dark:text-gray-400 text-sm">
                        <span>Replied by <a href="#" class="text-blue-500 dark:text-blue-300 font-bold">{{ '@'.$reply->user->username }}</a></span>
                        <span class="ml-2">{{ $reply->created_at->diffForHumans() }}</span>
                    </div>
                </div>
            </div>
        </div>
    @endforeach

    <!-- Reply Button -->
<button
    class="flex items-center space-x-2 text-sm px-4 py-2 rounded-md bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition"
    onclick="toggleReplyForm(this)"
>
    <i class="fas fa-reply"></i>
    <span>Reply</span>
</button>

<!-- Add Reply Form (Hidden by Default) -->
<div id="replyForm" class="replyForm hidden mt-4 bg-white dark:bg-gray-700 p-4 rounded-lg shadow-md">
    <textarea
        class="w-full p-3 rounded-lg border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white focus:outline-none focus:ring focus:ring-blue-400 transition"
        rows="3"
        placeholder="Write your reply here..."
    ></textarea>
    <div class="flex items-center justify-between mt-4">
        <button class="px-4 py-2 rounded-md bg-blue-500 text-white hover:bg-blue-600 transition">Post Reply</button>
        <button
            type="button"
            class="px-4 py-2 rounded-md bg-gray-500 text-white hover:bg-gray-600 transition"
            onclick="hideReplyForm(this)"
        >
            Cancel
        </button>
    </div>
</div>

</div>

</div>

        @endforeach
       <!-- Reply -->
<form id="replyForm" aria-label="Add Answer Form">
  <h3 class="text-2xl font-semibold text-gray-800 dark:text-gray-100 mb-4">Reply</h3>
  <textarea
    id="replyContent"
    name="reply"
    class="w-full p-3 border border-gray-300 rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white focus:outline-none focus:ring focus:ring-blue-300"
    rows="4"
    placeholder="Write your reply..."
    maxlength="500"
    required
  ></textarea>
  <div class="flex items-center space-x-2 mt-4">
    <button
      type="submit"
      class="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 dark:bg-blue-700 dark:hover:bg-blue-600"
    >
      Post Answer
    </button>
    <button
      type="reset"
      class="px-6 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600 dark:bg-gray-600 dark:hover:bg-gray-500"
    >
      Cancel
    </button>
  </div>
</form>

    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const questionUpvoteButton = document.getElementById('questionUpvote');
        const questionUpvoteCount = document.getElementById('questionUpvoteCount');

        questionUpvoteButton.addEventListener('click', () => {
            const isUpvoted = questionUpvoteButton.classList.toggle('text-blue-500');
            questionUpvoteButton.querySelector('i').classList.toggle('fas');
            questionUpvoteButton.querySelector('i').classList.toggle('far');
            questionUpvoteCount.textContent = parseInt(questionUpvoteCount.textContent) + (isUpvoted ? 1 : -1);
        });

        document.querySelectorAll('.answerUpvote').forEach(button => {
            button.addEventListener('click', () => {
                const countSpan = button.querySelector('.answerUpvoteCount');
                const isUpvoted = button.classList.toggle('text-blue-500');
                button.querySelector('i').classList.toggle('fas');
                button.querySelector('i').classList.toggle('far');
                countSpan.textContent = parseInt(countSpan.textContent) + (isUpvoted ? 1 : -1);
            });
        });
    });

    

</script>

<script>
$(document).ready(function () {
  $('#replyForm').on('submit', function (e) {
    e.preventDefault(); // Prevent default form submission

    const replyContent = $('#replyContent').val().trim();
    //const discussionId = $('#discussionId').val(); // Assuming you have a hidden input for discussion ID

    if (!replyContent) {
      Swal.fire({
        icon: 'warning',
        title: 'Empty Reply',
        text: 'Please write something before submitting.',
      });
      return;
    }

    $.ajax({
      url: '/community/discussion/reply',
      method: 'POST',
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), // Laravel CSRF token
      },
      data: {
        body: replyContent,
        post_id: @json($post->id),
      },
      beforeSend: function () {
        console.log('Submitting reply...');
      },
      success: function (response) {
        Swal.fire({
          icon: 'success',
          title: 'Reply Posted!',
          text: 'Your reply has been successfully added.',
          confirmButtonColor: '#3085d6',
        //   background: document.documentElement.classList.contains('dark') ? '#1f2937' : '#fff',
        //   color: document.documentElement.classList.contains('dark') ? '#fff' : '#000'
        }).then(() => {
          // Optional: Reload the page or append the new reply dynamically
          location.reload();
        });
      },
      error: function (xhr, status, error) {
        console.error('Error:', xhr, status, error);
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: xhr.responseJSON?.message || 'An error occurred. Please try again.',
        //   background: document.documentElement.classList.contains('dark') ? '#1f2937' : '#fff',
        //   color: document.documentElement.classList.contains('dark') ? '#fff' : '#000'
        });
      },
    });
  });
});
</script>

@section('sidebar')
<div class="bg-white dark:bg-gray-800 shadow-md rounded-lg p-6">
    <h2 class="text-xl font-semibold mb-4">Contact Information</h2>
    <p>
        Email: <a href="mailto:info@yourapp.com" class="text-blue-500 dark:text-blue-300">info@yourapp.com</a>
    </p>
    <p>Phone: +1234567890</p>
</div>
@endsection


    <!-- Add Discussion -->
    <a href="{{ route('community.discussion.add') }}"
        class="fixed bottom-12 right-8 bg-blue-500 text-white p-3 rounded-full shadow hover:bg-blue-600 z-50">
        <i class="fas fa-comments"></i> <i class="fas fa-plus text-xs"></i>
    </a>
<style>

</style>
<script>
    function toggleDropdown(button) {
        const dropdownMenu = button.nextElementSibling;
        dropdownMenu.classList.toggle('hidden');
    }

    // Close dropdown when clicking outside
    document.addEventListener('click', (event) => {
        const dropdowns = document.querySelectorAll('.relative .absolute');
        dropdowns.forEach((dropdown) => {
            if (!dropdown.contains(event.target) && !dropdown.previousElementSibling.contains(event.target)) {
                dropdown.classList.add('hidden');
            }
        });
    });

//     function toggleReplyForm(button) {
//     const replyForm = button.nextElementSibling;
//     replyForm.classList.toggle('hidden');
//     if (!replyForm.classList.contains('hidden')) {
//         replyForm.classList.add('fade-in');
//         setTimeout(() => replyForm.classList.remove('fade-in'), 300); // Removes animation class after it plays
//     }
// }

// const replyForm = document.getElementById('replyForm');

//     // Hide dropdown if clicked outside
//     function hideReplyForm() {
//         replyForm.classList.toggle('hidden');
//     if (!replyForm.classList.contains('hidden')) {
//         replyForm.classList.add('fade-in');
//         setTimeout(() => replyForm.classList.remove('fade-in'), 300); // Removes animation class after it plays
//     }
//         };
</script>

<script>
function toggleReplyForm(button) {
    const replyForm = button.nextElementSibling;
    replyForm.classList.toggle('hidden');
    if (!replyForm.classList.contains('hidden')) {
        replyForm.classList.add('fade-in');
        setTimeout(() => replyForm.classList.remove('fade-in'), 300); // Removes animation class after it plays
    }
}

function hideReplyForm(button) {
    const replyForm = button.closest('.replyForm');
    replyForm.classList.add('hidden');
}
</script>
@endsection
