@extends('layouts.app')

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

@section('content')
<!-- 페이지 헤더 -->
<div class="flex justify-between items-center mb-6">
    <div>
        <p class="text-sm text-gray-500">{{ $board->name }}</p>
        <h1 class="text-2xl font-bold text-gray-800 mt-1">
            @if($post->is_notice)
                <span class="inline-flex items-center px-2 py-0.5 rounded text-sm font-medium bg-blue-100 text-blue-800 mr-2">
                    공지
                </span>
            @endif
            @if($post->is_secret)
                <svg class="w-5 h-5 inline-block text-gray-400 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                </svg>
            @endif
            {{ $post->title }}
        </h1>
    </div>
    <a href="{{ route('boards.posts.index', ['boardCode' => $board->board_code, 't' => $board->tenant_id]) }}" class="text-gray-600 hover:text-gray-900">
        &larr; 목록으로
    </a>
</div>

<!-- 게시글 정보 -->
<div class="bg-white rounded-lg shadow-sm overflow-hidden">
    <!-- 메타 정보 -->
    <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
        <div class="flex items-center justify-between text-sm text-gray-500">
            <div class="flex items-center gap-6">
                <span>
                    <span class="font-medium text-gray-700">작성자:</span>
                    {{ $post->author?->name ?? '알 수 없음' }}
                </span>
                <span>
                    <span class="font-medium text-gray-700">작성일:</span>
                    {{ $post->created_at->format('Y-m-d H:i') }}
                </span>
                <span>
                    <span class="font-medium text-gray-700">조회:</span>
                    {{ number_format($post->views) }}
                </span>
            </div>
            @if($post->user_id === auth()->id() || auth()->user()->hasRole(['admin', 'super-admin']))
                <div class="flex items-center gap-2">
                    <a href="{{ route('boards.posts.edit', ['boardCode' => $board->board_code, 'post' => $post, 't' => $board->tenant_id]) }}"
                       class="px-3 py-1 text-sm text-blue-600 hover:text-blue-800 border border-blue-300 rounded hover:bg-blue-50 transition">
                        수정
                    </a>
                    <form id="deletePostForm" action="{{ route('boards.posts.destroy', ['boardCode' => $board->board_code, 'post' => $post, 't' => $board->tenant_id]) }}" method="POST">
                        @csrf
                        @method('DELETE')
                        <button type="button" onclick="confirmDeletePost()"
                                class="px-3 py-1 text-sm text-red-600 hover:text-red-800 border border-red-300 rounded hover:bg-red-50 transition">
                            삭제
                        </button>
                    </form>
                    <script>
                        function confirmDeletePost() {
                            showDeleteConfirm('이 게시글', () => {
                                document.getElementById('deletePostForm').submit();
                            });
                        }
                    </script>
                </div>
            @endif
        </div>
    </div>

    <!-- 커스텀 필드 값 -->
    @if(!empty($customFieldValues))
        <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
            <div class="grid grid-cols-3 gap-4 text-sm">
                @foreach($board->fields as $field)
                    @if(isset($customFieldValues[$field->field_key]))
                        <div>
                            <span class="font-medium text-gray-700">{{ $field->name }}:</span>
                            <span class="text-gray-600 ml-1">{{ $customFieldValues[$field->field_key] }}</span>
                        </div>
                    @endif
                @endforeach
            </div>
        </div>
    @endif

    <!-- 첨부 이미지 (본문 상단 - 풀 너비) -->
    @php
        $imageFiles = $post->files->filter(fn($file) => $file->isImage());
        $otherFiles = $post->files->filter(fn($file) => !$file->isImage());
    @endphp
    @if($imageFiles->isNotEmpty())
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="space-y-4">
                @foreach($imageFiles as $file)
                    <a href="{{ route('boards.posts.files.preview', ['boardCode' => $board->board_code, 'post' => $post, 'fileId' => $file->id, 't' => $board->tenant_id]) }}"
                       target="_blank"
                       class="block overflow-hidden rounded-lg border border-gray-200 hover:border-blue-400 transition">
                        <img src="{{ route('boards.posts.files.preview', ['boardCode' => $board->board_code, 'post' => $post, 'fileId' => $file->id, 't' => $board->tenant_id]) }}"
                             alt="{{ $file->display_name ?? $file->original_name }}"
                             class="w-full h-auto">
                    </a>
                @endforeach
            </div>
        </div>
    @endif

    <!-- 본문 -->
    <div class="px-6 py-8">
        <div class="prose max-w-none">
            @if($board->editor_type === 'wysiwyg')
                {{-- WYSIWYG: HTML 허용 (안전한 태그만) --}}
                {!! $post->getSafeHtmlContent() !!}
            @elseif($board->editor_type === 'markdown')
                {{-- Markdown: 파싱 후 출력 --}}
                {!! Str::markdown($post->content) !!}
            @else
                {{-- Text: 일반 텍스트 --}}
                {!! nl2br(e($post->content)) !!}
            @endif
        </div>
    </div>

    <!-- 첨부파일 (이미지 제외) -->
    @if($otherFiles->isNotEmpty())
        <div class="px-6 py-4 border-t border-gray-200 bg-gray-50">
            <h3 class="text-sm font-medium text-gray-700 mb-3">
                첨부파일 ({{ $otherFiles->count() }}개)
            </h3>
            <div class="space-y-2">
                @foreach($otherFiles as $file)
                    <div class="flex items-center justify-between px-4 py-3 bg-white rounded-lg border border-gray-200">
                        <div class="flex items-center gap-3">
                            <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                            </svg>
                            <div>
                                <span class="text-sm text-gray-900">{{ $file->display_name ?? $file->original_name }}</span>
                                <span class="text-xs text-gray-400 ml-2">({{ $file->getFormattedSize() }})</span>
                            </div>
                        </div>
                        <a href="{{ route('boards.posts.files.download', ['boardCode' => $board->board_code, 'post' => $post, 'fileId' => $file->id, 't' => $board->tenant_id]) }}"
                           class="px-3 py-1 text-sm text-blue-600 hover:text-blue-800 border border-blue-300 rounded hover:bg-blue-50 transition">
                            다운로드
                        </a>
                    </div>
                @endforeach
            </div>
        </div>
    @endif
</div>

<!-- 이전/다음 글 네비게이션 -->
<div class="mt-6 bg-white rounded-lg shadow-sm overflow-hidden">
    <div class="divide-y divide-gray-200">
        @if($adjacent['prev'])
            <a href="{{ route('boards.posts.show', ['boardCode' => $board->board_code, 'post' => $adjacent['prev']->id, 't' => $board->tenant_id]) }}"
               class="block px-6 py-4 hover:bg-gray-50 transition">
                <div class="flex items-center">
                    <span class="text-sm text-gray-500 w-20">이전글</span>
                    <span class="text-gray-900">{{ $adjacent['prev']->title }}</span>
                </div>
            </a>
        @endif
        @if($adjacent['next'])
            <a href="{{ route('boards.posts.show', ['boardCode' => $board->board_code, 'post' => $adjacent['next']->id, 't' => $board->tenant_id]) }}"
               class="block px-6 py-4 hover:bg-gray-50 transition">
                <div class="flex items-center">
                    <span class="text-sm text-gray-500 w-20">다음글</span>
                    <span class="text-gray-900">{{ $adjacent['next']->title }}</span>
                </div>
            </a>
        @endif
    </div>
</div>

<!-- 댓글 섹션 -->
<div class="mt-6 bg-white rounded-lg shadow-sm overflow-hidden">
    <div class="px-6 py-4 border-b border-gray-200 bg-gray-50">
        <h3 class="text-lg font-medium text-gray-900">
            댓글 <span class="text-blue-600">{{ $comments->count() + $comments->sum(fn($c) => $c->replies->count()) }}</span>
        </h3>
    </div>

    <!-- 댓글 작성 폼 -->
    <div class="px-6 py-4 border-b border-gray-200">
        <form action="{{ route('boards.posts.comments.store', ['boardCode' => $board->board_code, 'post' => $post, 't' => $board->tenant_id]) }}" method="POST">
            @csrf
            <div class="flex gap-3">
                <div class="flex-shrink-0">
                    <div class="w-10 h-10 rounded-full bg-blue-500 flex items-center justify-center text-white font-medium">
                        {{ mb_substr(auth()->user()->name, 0, 1) }}
                    </div>
                </div>
                <div class="flex-1">
                    <textarea name="content" rows="3" required
                              placeholder="댓글을 입력하세요..."
                              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none">{{ old('content') }}</textarea>
                    @error('content')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                    <div class="mt-2 flex justify-end">
                        <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition">
                            댓글 작성
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- 댓글 목록 -->
    <div class="divide-y divide-gray-200">
        @forelse($comments as $comment)
            <div class="px-6 py-4" id="comment-{{ $comment->id }}">
                <div class="flex gap-3">
                    <div class="flex-shrink-0">
                        <div class="w-10 h-10 rounded-full bg-gray-400 flex items-center justify-center text-white font-medium">
                            {{ mb_substr($comment->user?->name ?? '?', 0, 1) }}
                        </div>
                    </div>
                    <div class="flex-1">
                        <div class="flex items-center gap-2">
                            <span class="font-medium text-gray-900">{{ $comment->user?->name ?? '알 수 없음' }}</span>
                            <span class="text-sm text-gray-500">{{ $comment->created_at->diffForHumans() }}</span>
                            @if($comment->created_at != $comment->updated_at)
                                <span class="text-xs text-gray-400">(수정됨)</span>
                            @endif
                        </div>

                        <!-- 댓글 내용 (수정 모드) -->
                        <div x-data="{ editing: false }">
                            <div x-show="!editing" class="mt-1">
                                <p class="text-gray-700 whitespace-pre-wrap">{{ $comment->content }}</p>
                                <div class="mt-2 flex items-center gap-3 text-sm">
                                    <button type="button" @click="$dispatch('reply-to', { commentId: {{ $comment->id }} })"
                                            class="text-gray-500 hover:text-blue-600 transition">
                                        답글
                                    </button>
                                    @if($comment->user_id === auth()->id() || auth()->user()->hasRole(['admin', 'super-admin']))
                                        <button type="button" @click="editing = true"
                                                class="text-gray-500 hover:text-blue-600 transition">
                                            수정
                                        </button>
                                        <form action="{{ route('boards.posts.comments.destroy', ['boardCode' => $board->board_code, 'post' => $post, 'comment' => $comment, 't' => $board->tenant_id]) }}"
                                              method="POST" class="inline"
                                              onsubmit="return confirm('댓글을 삭제하시겠습니까?')">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="text-gray-500 hover:text-red-600 transition">
                                                삭제
                                            </button>
                                        </form>
                                    @endif
                                </div>
                            </div>

                            <!-- 수정 폼 -->
                            <form x-show="editing" x-cloak
                                  action="{{ route('boards.posts.comments.update', ['boardCode' => $board->board_code, 'post' => $post, 'comment' => $comment, 't' => $board->tenant_id]) }}"
                                  method="POST" class="mt-2">
                                @csrf
                                @method('PUT')
                                <textarea name="content" rows="3" required
                                          class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none">{{ $comment->content }}</textarea>
                                <div class="mt-2 flex justify-end gap-2">
                                    <button type="button" @click="editing = false"
                                            class="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800 transition">
                                        취소
                                    </button>
                                    <button type="submit"
                                            class="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded transition">
                                        수정
                                    </button>
                                </div>
                            </form>
                        </div>

                        <!-- 답글 목록 -->
                        @if($comment->replies->isNotEmpty())
                            <div class="mt-4 space-y-4 pl-4 border-l-2 border-gray-200">
                                @foreach($comment->replies as $reply)
                                    <div class="flex gap-3" id="comment-{{ $reply->id }}">
                                        <div class="flex-shrink-0">
                                            <div class="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center text-white text-sm font-medium">
                                                {{ mb_substr($reply->user?->name ?? '?', 0, 1) }}
                                            </div>
                                        </div>
                                        <div class="flex-1">
                                            <div class="flex items-center gap-2">
                                                <span class="font-medium text-gray-900 text-sm">{{ $reply->user?->name ?? '알 수 없음' }}</span>
                                                <span class="text-xs text-gray-500">{{ $reply->created_at->diffForHumans() }}</span>
                                            </div>

                                            <div x-data="{ editing: false }">
                                                <div x-show="!editing" class="mt-1">
                                                    <p class="text-gray-700 text-sm whitespace-pre-wrap">{{ $reply->content }}</p>
                                                    @if($reply->user_id === auth()->id() || auth()->user()->hasRole(['admin', 'super-admin']))
                                                        <div class="mt-1 flex items-center gap-3 text-xs">
                                                            <button type="button" @click="editing = true"
                                                                    class="text-gray-500 hover:text-blue-600 transition">
                                                                수정
                                                            </button>
                                                            <form action="{{ route('boards.posts.comments.destroy', ['boardCode' => $board->board_code, 'post' => $post, 'comment' => $reply, 't' => $board->tenant_id]) }}"
                                                                  method="POST" class="inline"
                                                                  onsubmit="return confirm('답글을 삭제하시겠습니까?')">
                                                                @csrf
                                                                @method('DELETE')
                                                                <button type="submit" class="text-gray-500 hover:text-red-600 transition">
                                                                    삭제
                                                                </button>
                                                            </form>
                                                        </div>
                                                    @endif
                                                </div>

                                                <!-- 답글 수정 폼 -->
                                                <form x-show="editing" x-cloak
                                                      action="{{ route('boards.posts.comments.update', ['boardCode' => $board->board_code, 'post' => $post, 'comment' => $reply, 't' => $board->tenant_id]) }}"
                                                      method="POST" class="mt-2">
                                                    @csrf
                                                    @method('PUT')
                                                    <textarea name="content" rows="2" required
                                                              class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none">{{ $reply->content }}</textarea>
                                                    <div class="mt-2 flex justify-end gap-2">
                                                        <button type="button" @click="editing = false"
                                                                class="px-2 py-1 text-xs text-gray-600 hover:text-gray-800 transition">
                                                            취소
                                                        </button>
                                                        <button type="submit"
                                                                class="px-2 py-1 bg-blue-600 hover:bg-blue-700 text-white text-xs rounded transition">
                                                            수정
                                                        </button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                        @endif

                        <!-- 답글 작성 폼 -->
                        <div x-data="{ showReplyForm: false }"
                             x-on:reply-to.window="if ($event.detail.commentId === {{ $comment->id }}) showReplyForm = true">
                            <form x-show="showReplyForm" x-cloak
                                  action="{{ route('boards.posts.comments.store', ['boardCode' => $board->board_code, 'post' => $post, 't' => $board->tenant_id]) }}"
                                  method="POST" class="mt-4 pl-4 border-l-2 border-blue-200">
                                @csrf
                                <input type="hidden" name="parent_id" value="{{ $comment->id }}">
                                <textarea name="content" rows="2" required
                                          placeholder="답글을 입력하세요..."
                                          class="w-full px-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"></textarea>
                                <div class="mt-2 flex justify-end gap-2">
                                    <button type="button" @click="showReplyForm = false"
                                            class="px-3 py-1.5 text-sm text-gray-600 hover:text-gray-800 transition">
                                        취소
                                    </button>
                                    <button type="submit"
                                            class="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded transition">
                                        답글 작성
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        @empty
            <div class="px-6 py-12 text-center text-gray-500">
                <svg class="w-12 h-12 mx-auto text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/>
                </svg>
                <p>아직 댓글이 없습니다.</p>
                <p class="text-sm mt-1">첫 번째 댓글을 작성해보세요!</p>
            </div>
        @endforelse
    </div>
</div>

<!-- 목록 버튼 -->
<div class="mt-6 flex justify-center">
    <a href="{{ route('boards.posts.index', ['boardCode' => $board->board_code, 't' => $board->tenant_id]) }}"
       class="px-6 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">
        목록
    </a>
</div>

<!-- 알림 메시지 -->
@if(session('success'))
    <div class="fixed bottom-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg" id="toast">
        {{ session('success') }}
    </div>
    <script>setTimeout(() => document.getElementById('toast')?.remove(), 3000);</script>
@endif
@endsection