<?php

use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Computed;
use App\Models\Ticket;
use App\Models\TicketMessages;
use App\Notifications\TicketReplied;
use App\Traits\WithTableHelpers;
use Livewire\WithFileUploads;
use Livewire\WithPagination;

new #[Layout('layouts::base', ['title' => 'Manage Ticket'])] class extends Component {
    use WithPagination, WithTableHelpers, WithFileUploads;

    public $perPage = 15;
    public $selectedTicketId = null;
    public $selectedTicket = null;
    public $adminReply = '';
    public $attachments = [];

    protected function searchableFields(): array
    {
        return ['id', 'user.name', 'user.email', 'subject', 'status'];
    }

    public function selectTicket($ticketId)
    {
        $this->selectedTicketId = $ticketId;
        $this->loadSelectedTicket();
    }

    public function loadSelectedTicket()
    {
        $this->selectedTicket = Ticket::with(['messages.user.profile', 'messages.admin'])->find($this->selectedTicketId);
        $this->adminReply = '';
        $this->attachments = [];
    }

    public function markResolved($ticketId)
    {
        $ticket = Ticket::findOrFail($ticketId);
        $ticket->update(['status' => Ticket::STATUS_RESOLVED]);
        $this->loadSelectedTicket();
    }

    protected $rules = [
        'adminReply' => 'required|string',
        'attachments' => 'nullable|array|max:5',
        'attachments.*' => 'file|max:5120|mimes:jpg,jpeg,png,webp,pdf,doc,docx,xls,xlsx',
    ];

    protected function messages()
    {
        return [
            'adminReply.required' => 'Please write a reply before submitting.',
            'attachments.*.image' => 'Each file must be an image.',
            'attachments.max' => 'You can upload a maximum of 5 attachments.',
            'attachments.*.max' => 'Each attachment must not exceed 5MB.',
            'attachments.*.mimes' => 'Allowed file types: jpg, jpeg, png, webp, pdf, doc, docx, xls, xlsx.',
        ];
    }

    public function updated($propertyName)
    {
        $this->validateOnly($propertyName);
    }

    public function updatedAttachments()
    {
        if (count($this->attachments) > 5) {
            $this->attachments = array_slice($this->attachments, 0, 5);
            $this->addError('attachments', 'You can upload a maximum of 5 attachments.');
        }
    }

    public function removeAttachment($index)
    {
        unset($this->attachments[$index]);
        $this->attachments = array_values($this->attachments); // reindex
    }

    public function delete($id)
    {
        Ticket::findOrFail($id)->delete();
        $this->dispatch('showToast', message: 'Ticket successfully deleted', type: 'success');
    }

    public function updatedPerPage()
    {
        $this->resetPage();
        $this->dispatch('perPageUpdated', $this->perPage);
    }

    public function sendReply()
    {
        $this->validate();

        $paths = [];
        foreach ($this->attachments as $file) {
            $paths[] = $file->store('tickets', 'public');
        }
        $admin = \Illuminate\Support\Facades\Auth::guard('admin')->user();

        TicketMessages::create([
            'ticket_id' => $this->selectedTicketId,
            'admin_id' => $admin->id,
            'user_id' => null,
            'message' => $this->adminReply,
            'attachments' => $paths, // Save as array
            'is_admin' => true,
        ]);

        // Update ticket status
        $ticket = Ticket::find($this->selectedTicketId);
        $ticket->update(['status' => Ticket::STATUS_IN_PROGRESS]);

        // Notify user
        if ($ticket->user) {
            $ticket->user->notify(new TicketReplied($ticket));
        }

        $this->loadSelectedTicket();
        $this->dispatch('showToast', message: 'Message sent successfully!', type: 'success');
    }

    #[Computed]
    public function tickets()
    {
        /** @var \App\Models\Admin|null $admin */
        $admin = auth('admin')->user();

        $query = Ticket::query()->with(['messages', 'user']);

        // Apply visibility filter only if an admin is logged in
        if ($admin) {
            $query->visibleToAdmin($admin);
        } else {
            // No admin logged in, deny access
            $query->whereRaw('1 = 0');
        }

        $this->applySearch($query, $this->searchableFields());

        return $query->orderBy($this->sortField, $this->sortDirection)->paginate($this->perPage)->withQueryString();
    }
};
?>


<div class="min-h-screen bg-gray-50 dark:bg-gray-950 p-6 space-y-8">

    
    <div class="flex flex-col md:flex-row justify-between items-center gap-4 md:gap-0 mb-6">
        <div class="w-full md:w-1/3">
            <input type="text" wire:model.live="search" placeholder="Search tickets..."
                class="w-full px-4 py-3 text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-sky-500 transition" />
        </div>

        <div class="flex items-center space-x-2">
            <label class="text-sm text-gray-600 dark:text-gray-400 font-medium">Show:</label>
            <select wire:model="perPage"
                class="text-sm px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-sky-500 transition">
                <option value="10">10</option>
                <option value="15">15</option>
                <option value="25">25</option>
                <option value="50">50</option>
            </select>
        </div>
    </div>

    <div class="flex flex-col lg:flex-row h-[85vh] bg-gray-100 dark:bg-gray-900">

        <!-- Ticket List -->
        <div class="lg:w-1/3 border-r border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 overflow-auto">

            <!-- Header -->
            <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                <h2 class="text-xl font-bold text-gray-800 dark:text-gray-100">Support Tickets</h2>
            </div>

            <!-- Ticket Items -->
            <ul class="divide-y divide-gray-200 dark:divide-gray-700">
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__empty_1 = true; $__currentLoopData = $this->tickets; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ticket): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                    <li wire:click="selectTicket(<?php echo e($ticket->id); ?>)" tabindex="0" role="button"
                        <?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processElementKey('ticket-{{ $ticket->id }}', get_defined_vars()); ?>wire:key="ticket-<?php echo e($ticket->id); ?>"
                        class="cursor-pointer p-4 hover:bg-gray-50 dark:hover:bg-gray-700 transition 
                   <?php echo e($selectedTicketId === $ticket->id ? 'bg-sky-100 dark:bg-sky-800 border-l-4 border-sky-600' : ''); ?>">

                        <div class="flex justify-between items-center">
                            <!-- Subject -->
                            <h3 class="font-semibold truncate max-w-[60%] text-gray-800 dark:text-gray-100"
                                title="<?php echo e($ticket->subject); ?>">
                                <?php echo e($ticket->subject); ?>

                            </h3>

                            <!-- Status & Priority -->
                            <div class="flex items-center gap-2">
                                <!-- Status Badge -->
                                <span
                                    class="text-xs font-semibold px-2 py-1 rounded-full
                        <?php echo e($ticket->status === 'resolved'
                            ? 'bg-green-200 text-green-800 dark:bg-green-700 dark:text-green-100'
                            : ($ticket->status === 'in_progress'
                                ? 'bg-yellow-200 text-yellow-800 dark:bg-yellow-600 dark:text-yellow-100'
                                : 'bg-red-200 text-red-800 dark:bg-red-700 dark:text-red-100')); ?>">
                                    <?php echo e(ucfirst(str_replace('_', ' ', $ticket->status))); ?>

                                </span>

                                <!-- Priority Badge -->
                                <span
                                    class="text-xs font-semibold px-2 py-1 rounded-full
                        <?php echo e($ticket->priority === 'High'
                            ? 'bg-red-100 text-red-700 dark:bg-red-700 dark:text-red-100'
                            : ($ticket->priority === 'Medium'
                                ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-600 dark:text-yellow-100'
                                : 'bg-green-100 text-green-700 dark:bg-green-700 dark:text-green-100')); ?>">
                                    <?php echo e($ticket->priority); ?>

                                </span>
                            </div>
                        </div>

                        <!-- Created At -->
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            <?php echo e($ticket->created_at->format('Y-m-d H:i')); ?>

                        </p>
                    </li>
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                    <li class="text-gray-500 italic p-4">No tickets found.</li>
                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
            </ul>

            <!-- Pagination -->
            <div class="p-4">
                <?php echo e($this->tickets->links()); ?>

            </div>
        </div>


        <!-- Chat & Reply -->
        <div class="lg:w-2/3 flex flex-col bg-white dark:bg-gray-900">
            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($selectedTicket): ?>
                <!-- Header -->
                <div
                    class="p-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center sticky top-0 bg-white dark:bg-gray-900 z-10">
                    <h3 class="text-xl font-bold truncate"><?php echo e($selectedTicket->subject); ?></h3>
                    <div class="flex items-center gap-1">
                        <span
                            class="inline-block px-3 py-1 rounded-full font-semibold select-none
                <?php echo e($selectedTicket->status === 'resolved'
                    ? 'bg-green-300 text-green-900'
                    : ($selectedTicket->status === 'in_progress'
                        ? 'bg-yellow-300 text-yellow-900'
                        : 'bg-red-300 text-red-900')); ?>">
                            <?php echo e(ucfirst(str_replace('_', ' ', $selectedTicket->status))); ?>

                        </span>

                        <!-- Priority Badge -->
                        <span
                            class="text-xs font-semibold px-2 py-1 rounded-full
                        <?php echo e($selectedTicket->priority === 'High'
                            ? 'bg-red-100 text-red-700 dark:bg-red-700 dark:text-red-100'
                            : ($selectedTicket->priority === 'Medium'
                                ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-600 dark:text-yellow-100'
                                : 'bg-green-100 text-green-700 dark:bg-green-700 dark:text-green-100')); ?>">
                            <?php echo e($selectedTicket->priority); ?>

                        </span>
                    </div>
                </div>

                <!-- Messages -->
                <div id="chatWindow" class="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $selectedTicket->messages; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $msg): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                        <div class="flex items-end <?php echo e($msg->is_admin ? 'justify-start' : 'justify-end'); ?> gap-2">

                            
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->is_admin): ?>
                                
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->admin?->avatar): ?>
                                    <img src="<?php echo e(asset('storage/' . $msg->admin->avatar)); ?>"
                                        class="w-8 h-8 rounded-full object-cover">
                                <?php else: ?>
                                    <img src="<?php echo e(asset('images/admin-avatar.png')); ?>"
                                        class="w-8 h-8 rounded-full object-cover">
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            <?php else: ?>
                                
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->user?->profile?->profile_photo): ?>
                                    <img src="<?php echo e(asset('storage/' . $msg->user->profile->profile_photo)); ?>"
                                        class="w-8 h-8 rounded-full object-cover">
                                <?php else: ?>
                                    <div
                                        class="w-8 h-8 rounded-full bg-gray-400 text-white flex items-center justify-center text-xs font-bold">
                                        <?php echo e(strtoupper(substr($msg->user?->name ?? 'U', 0, 1))); ?>

                                    </div>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                            
                            <div
                                class="max-w-[70%] px-4 py-2 rounded-xl shadow
        <?php echo e($msg->is_admin
            ? 'bg-sky-50 dark:bg-sky-900 dark:text-sky-200 rounded-tl-none'
            : 'bg-green-50 dark:bg-green-800 dark:text-green-100 rounded-tr-none'); ?>">

                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->message): ?>
                                    <p class="whitespace-pre-line"><?php echo e($msg->message); ?></p>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($msg->attachments && count($msg->attachments)): ?>
                                    <div class="mt-2 grid gap-2">
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $msg->attachments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $att): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(str_contains($att, '.jpg') || str_contains($att, '.png') || str_contains($att, '.webp')): ?>
                                                <a href="<?php echo e(asset('storage/' . $att)); ?>" target="_blank">
                                                    <img src="<?php echo e(asset('storage/' . $att)); ?>"
                                                        class="w-28 h-28 object-cover rounded-lg shadow-md hover:scale-105 transition-transform cursor-pointer" />
                                                </a>
                                            <?php else: ?>
                                                <a href="<?php echo e(asset('storage/' . $att)); ?>" target="_blank"
                                                    class="text-sky-600 dark:text-sky-300 underline truncate max-w-xs block">
                                                    <?php echo e(basename($att)); ?>

                                                </a>
                                            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                                    </div>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                                <p class="mt-1 text-xs text-gray-500 text-right select-none">
                                    <?php echo e($msg->created_at->format('H:i')); ?>

                                </p>
                            </div>
                        </div>
                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>


                </div>


                <!-- WhatsApp-style Reply Box with Preview -->
                <form wire:submit.prevent="sendReply"
                    class="sticky bottom-0 z-10 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700 px-4 py-3 space-y-2">

                    <!-- Attachments & Upload Preview -->
                    <div x-data="{ uploading: false, progress: 0 }" x-on:livewire-upload-start="uploading = true"
                        x-on:livewire-upload-finish="uploading = false" x-on:livewire-upload-cancel="uploading = false"
                        x-on:livewire-upload-error="uploading = false"
                        x-on:livewire-upload-progress="progress = $event.detail.progress" class="space-y-2">

                        <!-- File Input -->
                        <label class="flex items-center space-x-2 cursor-pointer text-gray-600 dark:text-gray-300">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                                stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828L18 10.828a4 4 0 10-5.656-5.656l-6.586 6.586a6 6 0 108.486 8.486L20 14.828" />
                            </svg>
                            <span class="text-sm">Attach files (max 5)</span>
                            <input type="file" multiple wire:model="attachments"
                                accept=".jpg,.jpeg,.png,.webp,.pdf,.doc,.docx,.xls,.xlsx" class="hidden">
                        </label>

                        <!-- Upload Progress -->
                        <div x-show="uploading">
                            <progress max="100" x-bind:value="progress"
                                class="w-full h-2 rounded bg-gray-200 dark:bg-gray-700"></progress>
                            <button type="button" wire:click="$cancelUpload('attachments')"
                                class="mt-1 px-3 py-1 bg-red-600 text-white rounded text-sm">Cancel Upload</button>
                        </div>

                        <!-- Previews -->
                        <div class="flex flex-wrap gap-3 mt-2">
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $attachments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $file): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                                <div <?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processElementKey('attachment_{{ $index }}', get_defined_vars()); ?>wire:key="attachment_<?php echo e($index); ?>"
                                    class="relative w-24 h-24 border rounded p-1 flex flex-col items-center justify-center">
                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if(str_contains($file->getMimeType(), 'image')): ?>
                                        <img src="<?php echo e($file->temporaryUrl()); ?>"
                                            class="w-full h-full object-cover rounded">
                                    <?php else: ?>
                                        <div class="text-xs text-center truncate w-full">
                                            <?php echo e($file->getClientOriginalName()); ?></div>
                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                    <button type="button" wire:click="removeAttachment(<?php echo e($index); ?>)"
                                        class="absolute top-1 right-1 bg-red-600 text-white w-5 h-5 flex items-center justify-center rounded-full">&times;</button>
                                </div>
                            <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
                        </div>

                        <!-- Validation errors -->
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['attachments'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="text-red-600 text-sm"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['attachments.*'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <p class="text-red-600 text-sm"><?php echo e($message); ?></p>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                    </div>
                    <!-- Message Input (Full width) -->
                    <?php if (isset($component)) { $__componentOriginal4727f9fd7c3055c2cf9c658d89b16886 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.textarea','data' => ['wire:model.live.blur' => 'adminReply','placeholder' => 'Type a message...','rows' => '1','class' => 'flex-1 resize-none border border-gray-300 dark:border-gray-700 rounded-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500 dark:focus:ring-sky-400']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('textarea'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['wire:model.live.blur' => 'adminReply','placeholder' => 'Type a message...','rows' => '1','class' => 'flex-1 resize-none border border-gray-300 dark:border-gray-700 rounded-full px-4 py-2 focus:outline-none focus:ring-2 focus:ring-sky-500 dark:focus:ring-sky-400']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886)): ?>
<?php $attributes = $__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886; ?>
<?php unset($__attributesOriginal4727f9fd7c3055c2cf9c658d89b16886); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal4727f9fd7c3055c2cf9c658d89b16886)): ?>
<?php $component = $__componentOriginal4727f9fd7c3055c2cf9c658d89b16886; ?>
<?php unset($__componentOriginal4727f9fd7c3055c2cf9c658d89b16886); ?>
<?php endif; ?>
                    <!-- Message Input & Buttons -->
                    <div class="flex items-center space-x-2">


                        <!-- Send Button -->
                        <button type="submit" wire:click="sendReply"
                            class="flex-none bg-sky-600 text-white p-3 rounded-full hover:bg-sky-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
                            <?php if($attachments === null && trim($adminReply) === ''): ?> disabled <?php endif; ?>>
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none"
                                viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M5 12h14M12 5l7 7-7 7" />
                            </svg>
                        </button>

                        <!-- Resolve Button -->
                        <button type="button" wire:click="markResolved(<?php echo e($selectedTicketId); ?>)"
                            class="flex-none bg-green-600 text-white px-3 py-2 rounded-full hover:bg-green-700 transition">
                            Resolve
                        </button>
                    </div>

                </form>
            <?php else: ?>
                <div class="flex-1 flex items-center justify-center text-gray-500 italic">
                    Select a ticket to view and reply.
                </div>
            <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
        </div>

    </div>

    <style>
        /* Custom scrollbar like WhatsApp web */
        .custom-scrollbar::-webkit-scrollbar {
            width: 6px;
        }

        .custom-scrollbar::-webkit-scrollbar-thumb {
            background-color: rgba(59, 130, 246, 0.5);
            border-radius: 3px;
        }
    </style>

    <script>
        // Auto scroll to bottom when new messages arrive
        const chatWindow = document.getElementById('chatWindow');
        if (chatWindow) chatWindow.scrollTop = chatWindow.scrollHeight;
        Livewire.hook('message.processed', () => {
            if (chatWindow) chatWindow.scrollTop = chatWindow.scrollHeight;
        });
    </script>

</div>
<?php /**PATH /Users/macuser/Herd/Novabank/resources/views/pages/admin/⚡tickets.blade.php ENDPATH**/ ?>