@extends('theme::layouts.app', ['title' => $title ?? __('tickets.title|View Ticket')])

@section('content')
    <main class="flex-grow w-full max-w-[1440px] mx-auto px-6 lg:px-10 py-10">
        <div class="flex flex-col lg:flex-row gap-10">
            @include('theme::partials.account.nav')
            <section class="flex-grow max-w-4xl space-y-8">
                {{-- Ticket Header Card --}}
                <div class="bg-white dark:bg-surface-dark rounded-xl border border-gray-100 dark:border-gray-800 p-6 shadow-soft">
                    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                        <div class="space-y-1">
                            <div class="flex items-center gap-2">
                                <a class="text-xs font-semibold text-primary hover:underline flex items-center gap-1" href="{{ route('helpdesk.tickets.index') }}">
                                    <span class="material-symbols-outlined text-sm">arrow_back</span>
                                    @lang('tickets.Back to Tickets')
                                </a>
                            </div>
                            <h1 class="text-xl font-bold text-text-main dark:text-white">{{ $ticket->subject }}</h1>
                            <div class="flex flex-wrap items-center gap-3 text-sm">
                                <span class="text-text-muted">{{ __('tickets.ID:') }} #{{ $ticket->reference_id }}</span>
                                <span class="w-1 h-1 bg-gray-300 rounded-full hidden sm:block"></span>
                                <span class="text-text-muted">{{ $ticket->created_at->format('M d, Y') }}</span>
                                @if($ticket->order && $ticket->order->order_reference)
                                    <span class="w-1 h-1 bg-gray-300 rounded-full hidden sm:block"></span>
                                    <span class="text-text-muted flex items-center gap-1">
                                        <span class="material-symbols-outlined text-sm">shopping_cart</span>
                                        {{ $ticket->order->order_reference }}
                                    </span>
                                @endif
                                <span class="w-1 h-1 bg-gray-300 rounded-full hidden sm:block"></span>
                                <span class="text-text-muted flex items-center gap-1">
                                    <span class="material-symbols-outlined text-sm">folder</span>
                                    {{ $ticket->category->name }}
                                </span>
                            </div>
                        </div>
                        <div class="flex items-center gap-3">
                            @php
                                $statusClasses = [
                                    'Open' => 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 border-green-200 dark:border-green-800',
                                    'In Progress' => 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400 border-yellow-200 dark:border-yellow-800',
                                    'Resolved' => 'bg-gray-100 text-gray-600 dark:bg-gray-700/50 dark:text-gray-300 border-gray-200 dark:border-gray-600',
                                    'Closed' => 'bg-gray-100 text-gray-600 dark:bg-gray-700/50 dark:text-gray-300 border-gray-200 dark:border-gray-600',
                                ];
                                $statusClass = $statusClasses[$ticket->status] ?? 'bg-gray-100 text-gray-600 dark:bg-gray-700/50 dark:text-gray-300 border-gray-200 dark:border-gray-600';
                                $isResolved = in_array($ticket->status, ['Resolved', 'Closed']);
                            @endphp
                            <span class="px-2.5 py-1 {{ $statusClass }} text-xs font-bold rounded-full border">
                                {{ $ticket->status }}
                            </span>
                            {{-- Mark as Resolved / Reopen Button --}}
                            <form action="{{ route('helpdesk.tickets.update', $ticket->id) }}" method="POST" class="inline">
                                @csrf
                                @method('PUT')
                                <input type="hidden" name="status_only" value="1">
                                @if($isResolved)
                                    <input type="hidden" name="status" value="Open">
                                    <button type="submit" class="px-4 py-2 border border-gray-200 dark:border-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors text-text-main dark:text-gray-200 cursor-pointer">
                                        @lang('tickets.Reopen')
                                    </button>
                                @else
                                    <input type="hidden" name="status" value="Resolved">
                                    <button type="submit" class="px-4 py-2 border border-gray-200 dark:border-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors text-text-main dark:text-gray-200 cursor-pointer">
                                        @lang('tickets.Mark as Resolved')
                                    </button>
                                @endif
                            </form>
                        </div>
                    </div>
                </div>

                {{-- Messages Thread --}}
                <div class="space-y-6">
                    @foreach($messages as $message)
                        @php
                            $isAdmin = $message->user->roles[0]->display_name === 'Administrator';
                        @endphp

                        @if($isAdmin)
                            {{-- Admin/Support Message (Right aligned) --}}
                            <div class="flex items-start gap-4 flex-row-reverse">
                                <div class="size-10 rounded-full bg-primary/10 flex items-center justify-center flex-shrink-0">
                                    <span class="material-symbols-outlined text-primary">support_agent</span>
                                </div>
                                <div class="flex-grow max-w-[85%] text-right">
                                    <div class="bg-primary text-white p-4 rounded-2xl rounded-tr-none shadow-soft text-left">
                                        <div class="flex items-center justify-between mb-2">
                                            <span class="text-sm font-bold">
                                                {{ $message->user->first_name }} {{ $message->user->last_name }}
                                                <span class="text-xs opacity-80 font-normal ml-1">(Support)</span>
                                            </span>
                                            <span class="text-[11px] opacity-80">{{ $message->created_at->format('h:i A') }}</span>
                                        </div>
                                        <div class="text-sm leading-relaxed rich-content">
                                            {!! $message->message_content !!}
                                        </div>
                                        {{-- Attachments for Admin --}}
                                        @if($message->media->isNotEmpty())
                                            <div class="mt-4 flex flex-wrap gap-2">
                                                @foreach($message->media as $attachment)
                                                    <a href="{{ $attachment->TempUrl }}" target="_blank" class="flex items-center gap-2 px-3 py-2 bg-white/10 hover:bg-white/20 rounded-lg transition-colors">
                                                        <span class="material-symbols-outlined text-sm">attach_file</span>
                                                        <span class="text-xs font-medium">{{ $attachment->filename }}</span>
                                                    </a>
                                                @endforeach
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        @else
                            {{-- Customer Message (Left aligned) --}}
                            <div class="flex items-start gap-4">
                                <div class="size-10 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center flex-shrink-0 text-text-muted">
                                    <span class="material-symbols-outlined">person</span>
                                </div>
                                <div class="flex-grow max-w-[85%]">
                                    <div class="bg-white dark:bg-surface-dark p-4 rounded-2xl rounded-tl-none border border-gray-100 dark:border-gray-800 shadow-soft">
                                        <div class="flex items-center justify-between mb-2">
                                            <span class="text-sm font-bold text-text-main dark:text-white">
                                                {{ $message->user->first_name }} {{ $message->user->last_name }}
                                            </span>
                                            <span class="text-[11px] text-text-muted">{{ $message->created_at->format('h:i A') }}</span>
                                        </div>
                                        <div class="text-sm text-text-main dark:text-gray-300 leading-relaxed rich-content">
                                            {!! $message->message_content !!}
                                        </div>
                                        {{-- Attachments for Customer --}}
                                        @if($message->media->isNotEmpty())
                                            <div class="mt-4 flex flex-wrap gap-2">
                                                @foreach($message->media as $attachment)
                                                    <a href="{{ $attachment->TempUrl }}" target="_blank" class="flex items-center gap-2 px-3 py-2 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-primary dark:hover:border-primary transition-colors">
                                                        <span class="material-symbols-outlined text-sm text-text-muted">attach_file</span>
                                                        <span class="text-xs font-medium text-text-main dark:text-gray-200">{{ $attachment->filename }}</span>
                                                    </a>
                                                @endforeach
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        @endif
                    @endforeach
                </div>

                {{-- Reply Form (Hidden when ticket is resolved) --}}
                @if(!in_array($ticket->status, ['Resolved', 'Closed']))
                <form action="{{ route('helpdesk.tickets.update', $ticket->id) }}" method="POST" class="bg-white dark:bg-surface-dark rounded-xl border border-gray-100 dark:border-gray-800 shadow-soft overflow-hidden">
                    @csrf
                    @method('PUT')

                    <div class="p-6 space-y-4">
                        <h3 class="text-lg font-bold text-text-main dark:text-white">@lang('tickets.Reply to Ticket')</h3>

                        {{-- Message Textarea --}}
                        <div class="space-y-1.5">
                            <textarea
                                name="message"
                                id="message_content"
                                class="w-full px-4 py-3 bg-gray-50 dark:bg-gray-800/50 border border-gray-200 dark:border-gray-700 rounded-lg text-sm focus:ring-1 focus:ring-primary focus:border-primary focus:outline-none transition-all min-h-[160px] @error('message') border-red-500 @enderror"
                                placeholder="@lang('tickets.Write your message...')"
                            >{{ old('message') }}</textarea>
                            @error('message')
                                <p class="text-xs text-red-500 mt-1">{{ $message }}</p>
                            @enderror
                        </div>

                        {{-- File Attachments --}}
                        @if(setting('ticket_system.file_attachments', 1))
                            <div class="space-y-1.5">
                                <label class="text-sm font-semibold text-text-main dark:text-gray-200">@lang('tickets.Attachments') (@lang('tickets.Optional'))</label>
                                <div class="uploader">
                                    <button
                                        id="logo-uploader"
                                        data-media-config='{
                                            "key": "attachments",
                                            "container": ".attachments-container",
                                            "maxFiles": {{ setting('ticket_system.max_file_attachments', 1) }},
                                            "maxFilesize": {{ setting('ticket_system.file_size', 2) * 1048576 }},
                                            "previewsContainer": ".attachments-container-preview",
                                            "disk": "local"
                                        }'
                                        data-upload-url='{{ route('upload_attachments') }}'
                                        data-delete-url='{{ route('delete_attachments') }}'
                                        type="button"
                                        class="dropzone relative border-2 border-dashed border-gray-200 dark:border-gray-700 rounded-xl p-6 transition-colors hover:border-primary/50 group bg-gray-50/50 dark:bg-gray-800/30 w-full cursor-pointer text-left block">
                                        <div class="flex flex-col items-center justify-center text-center pointer-events-none">
                                            <div class="w-10 h-10 bg-white dark:bg-surface-dark rounded-full shadow-sm flex items-center justify-center mb-3 group-hover:scale-110 transition-transform">
                                                <span class="material-symbols-outlined text-primary text-[20px]">upload_file</span>
                                            </div>
                                            <p class="text-sm font-medium text-text-main dark:text-white">
                                                @lang('tickets.Click to upload or drag and drop')
                                            </p>
                                            <p class="text-xs text-text-muted mt-1">
                                                PNG, JPG or PDF up to {{ setting('ticket_system.file_size', 2) }}MB each (max {{ setting('ticket_system.max_file_attachments', 1) }} files)
                                            </p>
                                        </div>
                                    </button>
                                    <div class="attachments-container"></div>
                                    <div class="attachments-container-preview mt-3"></div>
                                </div>
                            </div>
                        @endif
                    </div>

                    {{-- Form Footer --}}
                    <div class="px-6 py-4 bg-gray-50/50 dark:bg-gray-800/20 flex items-center justify-end border-t border-gray-100 dark:border-gray-800">
                        {{-- Submit Button --}}
                        <button type="submit" class="flex items-center gap-2 px-6 py-2.5 bg-primary hover:bg-primary-dark text-white rounded-lg font-semibold transition-all shadow-sm text-sm">
                            <span>@lang('tickets.Send Reply')</span>
                            <span class="material-symbols-outlined text-sm">send</span>
                        </button>
                    </div>
                </form>
                @else
                {{-- Ticket Resolved Notice --}}
                <div class="bg-gray-50 dark:bg-gray-800/50 rounded-xl border border-gray-100 dark:border-gray-800 p-6 text-center">
                    <span class="material-symbols-outlined text-4xl text-gray-400 dark:text-gray-500 mb-3">check_circle</span>
                    <p class="text-text-muted dark:text-gray-400">@lang('tickets.This ticket has been resolved. Click "Reopen" above if you need further assistance.')</p>
                </div>
                @endif
            </section>
        </div>
    </main>
@endsection

@push('ch_header')
    @if(setting('ticket_system.rich_editor', 1))
        <link rel="stylesheet" href="{{ url('assets/themes/tailwind/css/jodit.min.css') }}">
        <script src="{{ url('assets/themes/tailwind/js/vendors/jodit.min.js') }}"></script>
    @endif
@endpush

@push('ch_footer')
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    @include('theme::pages.account.tickets.upload')
    <script src="{{ url('assets/backend/js/vendors/dropzone.min.js') }}"></script>
    <script src="{{ url('assets/backend/js/media.js') }}"></script>

    @if(setting('ticket_system.rich_editor', 1))
        <script>
            const textAreas = ['#message_content'];
            textAreas.forEach((el) => {
                const editor = Jodit.make(el, {
                    height: 250,
                    buttons: 'bold,italic,underline,strikethrough,eraser,|,ul,ol,|,paragraph,|,link,image,hr,|,align,|,source,|,undo,redo',
                });
                document.querySelector('form').addEventListener('submit', function () {
                    document.querySelector(el).value = editor.value;
                });
            });
        </script>
    @endif
@endpush
