@extends('layouts.app')

@section('title', $thread->title)

@section('content')
<div class="forum-container">
    <div class="forum-breadcrumbs">
        <a href="{{ route('forum.index') }}">Forums</a>
        <span class="separator">/</span>
        <a href="{{ route('forum.board', $board->slug) }}">{{ $board->name }}</a>
        <span class="separator">/</span>
        <span class="current">{{ \Illuminate\Support\Str::limit($thread->title, 30) }}</span>
    </div>
    
    <div class="forum-thread-header">
        <h1>{{ $thread->title }}</h1>
        <div class="meta">
            Started by  - <a href="{{ route('users.show', $thread->user->slug) }}">{{ $thread->user->name }}</a>
            <span class="dot"></span>
            {{ $thread->created_at->format('M d, Y') }}
            <span class="dot"></span>
            {{ $thread->view_count }} views
            
            @if($thread->is_locked)
                <span class="dot"></span>
                <span class="locked">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                        <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                    </svg>
                    Locked
                </span>
            @endif
            
            @if($thread->is_pinned)
                <span class="dot"></span>
                <span class="pinned">
                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M12 2L12 22"></path>
                        <path d="M18 8L12 2 6 8"></path>
                    </svg>
                    Pinned
                </span>
            @endif
        </div>
        
        @auth
            @if(Auth::user()->can('moderate forums') || Auth::id() === $thread->user_id)
                <div class="thread-moderation">
                    @if(Auth::user()->can('moderate forums'))
                        <div class="dropdown">
                            <button class="btn moderation-btn">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <circle cx="12" cy="12" r="1"></circle>
                                    <circle cx="19" cy="12" r="1"></circle>
                                    <circle cx="5" cy="12" r="1"></circle>
                                </svg>
                                Moderate
                            </button>
                            <div class="dropdown-content">
                                <a href="{{ route('forum.edit-thread', [$board->slug, $thread->slug]) }}" class="edit-link">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                    </svg>
                                    Edit Thread
                                </a>
                                
                                <form action="{{ route('forum.toggle-lock-thread', [$board->slug, $thread->slug]) }}" method="POST" class="inline-form">
                                    @csrf
                                    <button type="submit" class="lock-link">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
                                            <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                                        </svg>
                                        {{ $thread->is_locked ? 'Unlock Thread' : 'Lock Thread' }}
                                    </button>
                                </form>
                                
                                <form action="{{ route('forum.toggle-pin-thread', [$board->slug, $thread->slug]) }}" method="POST" class="inline-form">
                                    @csrf
                                    <button type="submit" class="pin-link">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M12 2L12 22"></path>
                                            <path d="M18 8L12 2 6 8"></path>
                                        </svg>
                                        {{ $thread->is_pinned ? 'Unpin Thread' : 'Pin Thread' }}
                                    </button>
                                </form>
                                
                                <form action="{{ route('forum.delete-thread', [$board->slug, $thread->slug]) }}" method="POST" class="inline-form" onsubmit="return confirm('Are you sure you want to delete this thread? This action cannot be undone.');">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="delete-link">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <polyline points="3 6 5 6 21 6"></polyline>
                                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                            <line x1="10" y1="11" x2="10" y2="17"></line>
                                            <line x1="14" y1="11" x2="14" y2="17"></line>
                                        </svg>
                                        Delete Thread
                                    </button>
                                </form>
                            </div>
                        </div>
                    @elseif(Auth::id() === $thread->user_id)
                        <a href="{{ route('forum.edit-thread', [$board->slug, $thread->slug]) }}" class="btn edit-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                            </svg>
                            Edit
                        </a>
                    @endif
                </div>
            @endif
        @endauth
    </div>
    
    <!-- Original Post -->
    <div class="forum-thread-content">
        <div class="author">
            <div class="avatar">
                <img src="{{ $thread->user->avatar }}" alt="{{ $thread->user->name }}">
            </div>
            <div class="info">
                <div class="name"><a href="{{ route('users.show', $thread->user->slug) }}">{{ $thread->user->name }}</a></div>
                @if($thread->user->isAdmin ?? false)
                    <div class="role">Admin</div>
                @elseif($thread->user->isModerator ?? false)
                    <div class="role">Moderator</div>
                @endif
                <div class="joined">Joined {{ $thread->user->created_at->format('M Y') }}</div>
            </div>
        </div>
        
        <div class="content bbcode-content">
            @sanitize((new \Golonka\BBCode\BBCodeParser)->parse($thread->content))
        </div>
        
        <div class="reactions">
            @foreach(App\Models\ForumReaction::getTypes() as $type => $emoji)
                <div 
                    class="reaction {{ Auth::check() && $thread->reactions()->where('user_id', Auth::id())->where('type', $type)->exists() ? 'active' : '' }}"
                    data-thread-id="{{ $thread->id }}"
                    data-type="{{ $type }}"
                    onclick="toggleThreadReaction(this)"
                >
                    <span class="emoji">{{ $emoji }}</span>
                    <span class="count">{{ $thread->reactions()->where('type', $type)->count() }}</span>
                </div>
            @endforeach
        </div>
    </div>
    
    <!-- Replies -->
    <div class="forum-thread-replies">
        <h2>Replies</h2>
        
        @forelse($posts as $post)
            <div class="post" id="post-{{ $post->id }}">
                <div class="author">
                    <div class="avatar">
                        <img src="{{ $post->user->avatar }}" alt="{{ $post->user->name }}">
                    </div>
                    <div class="info">
                        <div class="name-time">
                            <div class="name"><a href="{{ route('users.show', $post->user->slug) }}">{{ $post->user->name }}</a></div>
                            <div class="time">
                                {{ $post->created_at->format('M d, Y g:i A') }}
                                @if($post->is_edited)
                                    <span class="edited-tag">(edited {{ $post->edited_at->format('M d, Y') }})</span>
                                @endif
                            </div>
                        </div>
                        @if($post->user->isAdmin ?? false)
                            <div class="role">Admin</div>
                        @elseif($post->user->isModerator ?? false)
                            <div class="role">Moderator</div>
                        @endif
                        
                        @auth
                            @if(Auth::user()->can('moderate forums') || Auth::id() === $post->user_id)
                                <div class="post-actions">
                                    <a href="{{ route('forum.edit-post', [$board->slug, $thread->slug, $post->id]) }}" class="post-action edit">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                        </svg>
                                        Edit
                                    </a>
                                    
                                    @if(Auth::user()->can('moderate forums'))
                                        <form action="{{ route('forum.delete-post', [$board->slug, $thread->slug, $post->id]) }}" method="POST" class="inline-form" onsubmit="return confirm('Are you sure you want to delete this post? This action cannot be undone.');">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="post-action delete">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <polyline points="3 6 5 6 21 6"></polyline>
                                                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
                                                    <line x1="10" y1="11" x2="10" y2="17"></line>
                                                    <line x1="14" y1="11" x2="14" y2="17"></line>
                                                </svg>
                                                Delete
                                            </button>
                                        </form>
                                    @endif
                                </div>
                            @endif
                        @endauth
                    </div>
                </div>
                
                <div class="content bbcode-content">
                    @sanitize((new \Golonka\BBCode\BBCodeParser)->parse($post->content))
                </div>
                
                <div class="reactions">
                    @foreach(App\Models\ForumReaction::getTypes() as $type => $emoji)
                        <div 
                            class="reaction {{ Auth::check() && $post->hasReactionFromUser(Auth::id(), $type) ? 'active' : '' }}" 
                            data-post-id="{{ $post->id }}"
                            data-type="{{ $type }}"
                            onclick="toggleReaction(this)"
                        >
                            <span class="emoji">{{ $emoji }}</span>
                            <span class="count">{{ $post->getReactionCount($type) }}</span>
                        </div>
                    @endforeach
                </div>
            </div>
        @empty
            <div class="no-replies">No replies yet. Be the first to reply!</div>
        @endforelse
        
        <div class="mt-4">
            {{ $posts->links() }}
        </div>
    </div>
    
    <!-- Reply Form -->
    @if(!$thread->is_locked)
        @auth
            <div class="forum-thread-reply-form">
                <h3>Post a Reply</h3>
                
                <form action="{{ route('forum.store-post', [$board->slug, $thread->slug]) }}" method="POST">
                    @csrf
                    
                    <div class="form-group">
                        <x-bbcode-editor 
                            name="content"
                            placeholder="Write your reply here..."
                            :content="old('content')"
                            height="200px"
                        />
                        @error('content')
                            <div class="error-message">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit">Post Reply</button>
                    </div>
                </form>
            </div>
        @else
            <div class="forum-login-prompt">
                <p>You need to <a href="{{ route('login.steam') }}">log in</a> to reply to this thread.</p>
            </div>
        @endauth
    @else
        <div class="forum-thread-locked-message">
            <p>This thread is locked. No new replies can be posted.</p>
        </div>
    @endif
</div>

@push('scripts')
<script>
    function toggleReaction(element) {
        if (!{{ Auth::check() ? 'true' : 'false' }}) {
            window.location.href = "{{ route('login.steam') }}";
            return;
        }
        
        const postId = element.getAttribute('data-post-id');
        const type = element.getAttribute('data-type');
        
        fetch('{{ route('forum.toggle-reaction') }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                post_id: postId,
                type: type
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const countElement = element.querySelector('.count');
                countElement.textContent = data.count;
                
                if (data.action === 'added') {
                    element.classList.add('active');
                } else {
                    element.classList.remove('active');
                }
            }
        })
        .catch(error => {
            console.error('Error toggling reaction:', error);
        });
    }
    
    function toggleThreadReaction(element) {
        if (!{{ Auth::check() ? 'true' : 'false' }}) {
            window.location.href = "{{ route('login.steam') }}";
            return;
        }
        
        const threadId = element.getAttribute('data-thread-id');
        const type = element.getAttribute('data-type');
        
        fetch('{{ route('forum.toggle-thread-reaction') }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                thread_id: threadId,
                type: type
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const countElement = element.querySelector('.count');
                countElement.textContent = data.count;
                
                if (data.action === 'added') {
                    element.classList.add('active');
                } else {
                    element.classList.remove('active');
                }
            }
        })
        .catch(error => {
            console.error('Error toggling thread reaction:', error);
        });
    }
</script>
@endpush
@endsection