<x-app-layout>
    <x-slot name="header">
        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center space-y-4 sm:space-y-0">
            <div>
                <h2 class="font-bold text-2xl text-slate-800 leading-tight flex items-center gap-3">
                    <span class="text-indigo-600 bg-indigo-50 p-2 rounded-lg">
                        <i class="ph-duotone ph-briefcase"></i>
                    </span>
                    <span>Case #{{ $case->case_number }}</span>
                </h2>
                <p class="text-sm text-slate-500 mt-1 ml-11 flex items-center gap-2">
                    Managed by <span class="font-bold text-slate-700">{{ $case->lawyer->name }}</span>
                    <span class="text-slate-300">|</span>
                    <span class="text-xs font-mono bg-slate-100 px-2 py-0.5 rounded text-slate-600">ID:
                        {{ $case->id }}</span>
                </p>
            </div>

            <div class="flex items-center gap-3">
                <span
                    class="px-3 py-1.5 text-xs font-bold rounded-full border border-blue-100 bg-blue-50 text-blue-700 flex items-center gap-1 uppercase tracking-wide">
                    <i class="ph-fill ph-flag-checkered"></i> {{ $case->case_stage ?? 'Pre-Trial' }}
                </span>

                <span
                    class="px-3 py-1.5 text-xs font-bold rounded-full border shadow-sm flex items-center gap-2 uppercase tracking-wide
                    {{ $case->status === 'open' ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-slate-100 text-slate-600 border-slate-200' }}">
                    <span class="relative flex h-2 w-2">
                        <span
                            class="animate-ping absolute inline-flex h-full w-full rounded-full opacity-75 {{ $case->status === 'open' ? 'bg-emerald-400' : 'hidden' }}"></span>
                        <span
                            class="relative inline-flex rounded-full h-2 w-2 {{ $case->status === 'open' ? 'bg-emerald-500' : 'bg-slate-500' }}"></span>
                    </span>
                    {{ ucfirst($case->status) }}
                </span>

                <a href="{{ route('admin.cases.edit', $case->id) }}"
                    class="bg-white border border-slate-300 text-slate-700 hover:bg-slate-50 hover:text-indigo-600 px-4 py-2 rounded-lg text-sm font-semibold shadow-sm transition flex items-center">
                    <i class="ph-bold ph-pencil-simple mr-2"></i> Edit
                </a>
            </div>
        </div>
    </x-slot>

    <div class="py-8 bg-slate-50 min-h-screen">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-8">

            <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl overflow-hidden">
                <div class="grid grid-cols-1 md:grid-cols-3 divide-y md:divide-y-0 md:divide-x divide-slate-100">

                    <div class="p-6 flex items-start space-x-4 hover:bg-slate-50 transition group">
                        <div
                            class="flex-shrink-0 p-3 bg-blue-50 text-blue-600 rounded-xl group-hover:bg-blue-100 transition">
                            <i class="ph-duotone ph-user text-2xl"></i>
                        </div>
                        <div>
                            <p class="text-xs font-bold text-slate-400 uppercase tracking-wider">Client</p>
                            <a href="#"
                                class="text-base font-bold text-slate-900 mt-0.5 hover:text-indigo-600 transition">{{ $case->client->name }}</a>
                            <p class="text-sm text-slate-500">{{ $case->client->email }}</p>
                        </div>
                    </div>

                    <div class="p-6 flex items-start space-x-4 hover:bg-slate-50 transition group">
                        <div
                            class="flex-shrink-0 p-3 bg-red-50 text-red-600 rounded-xl group-hover:bg-red-100 transition">
                            <i class="ph-duotone ph-gavel text-2xl"></i>
                        </div>
                        <div>
                            <p class="text-xs font-bold text-slate-400 uppercase tracking-wider">Court Session</p>
                            @if ($case->court_date)
                                <p class="text-base font-bold text-red-600 mt-0.5">
                                    {{ $case->court_date->format('M d, Y') }} <span
                                        class="text-xs text-slate-400 font-normal">at
                                        {{ $case->court_date->format('H:i') }}</span></p>
                                <p class="text-xs text-slate-600 mt-1 font-medium truncate max-w-[150px]"
                                    title="{{ $case->court_name }}">
                                    {{ $case->court_name ?? 'Court Not Assigned' }}
                                </p>
                            @else
                                <p class="text-sm font-semibold text-slate-400 mt-1 italic">Not Scheduled</p>
                            @endif
                        </div>
                    </div>

                    <div class="p-6 flex items-start space-x-4 hover:bg-slate-50 transition group">
                        <div
                            class="flex-shrink-0 p-3 bg-purple-50 text-purple-600 rounded-xl group-hover:bg-purple-100 transition">
                            <i class="ph-duotone ph-info text-2xl"></i>
                        </div>
                        <div class="overflow-hidden">
                            <p class="text-xs font-bold text-slate-400 uppercase tracking-wider">Matter</p>
                            <p class="text-sm font-semibold text-slate-800 mt-0.5 truncate">{{ $case->title }}</p>
                            <p class="text-xs text-slate-500 mt-1 truncate">
                                {{ $case->description ?? 'No details provided.' }}</p>
                                 <button onclick="openDescriptionModal('{{ addslashes($case->title) }}', `{{ addslashes($case->description) }}`)"
                                                class="text-slate-400 hover:text-indigo-600 transition-colors" title="Read Facts">
                                                <i class="ph-bold ph-notebook text-lg"></i>
                                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

                <div class="lg:col-span-2 space-y-8">

                    <div
                        class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl overflow-hidden border-t-4 border-indigo-500">
                        <div
                            class="px-6 py-5 border-b border-slate-100 flex justify-between items-center bg-indigo-50/50">
                            <div>
                                <h3 class="text-lg font-bold text-slate-900 flex items-center gap-2">
                                    <i class="ph-duotone ph-sparkle text-indigo-600"></i> AI Co-Counsel
                                </h3>
                                <p class="text-xs text-slate-500 mt-1">Automated legal strategy based on facts.</p>
                            </div>
                            <form action="{{ route('admin.cases.analyze', $case->id) }}" method="POST">
                                @csrf
                                <button type="submit"
                                    class="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-lg font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 transition shadow-lg shadow-indigo-200">
                                    <i class="ph-bold ph-lightning mr-2"></i>
                                    {{ $case->ai_analysis ? 'Regenerate' : 'Generate' }}
                                </button>
                            </form>
                        </div>
                        <div class="p-6 bg-white">
                            @if ($case->ai_analysis)
                                <div class="prose max-w-none text-slate-700 leading-relaxed text-sm">
                                    {!! Str::markdown($case->ai_analysis) !!}
                                </div>
                                <div
                                    class="mt-4 pt-4 border-t border-slate-100 flex items-center gap-2 text-xs text-slate-400 italic">
                                    <i class="ph-bold ph-info"></i> Generated by Google Gemini AI. Verify with counsel.
                                </div>
                            @else
                                <div class="text-center py-6">
                                    <p class="text-slate-500 text-sm">Click generate to analyze case facts & witnesses.
                                    </p>
                                </div>
                            @endif
                        </div>
                    </div>

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl p-5" x-data="audioRecorder()">
                        <div class="flex justify-between items-center border-b border-slate-100 pb-3 mb-4">
                            <h4 class="text-base font-bold text-slate-800 flex items-center gap-2">
                                <i class="ph-duotone ph-microphone text-red-500"></i> Voice Evidence & Notes
                            </h4>

                            <div x-show="isRecording" class="flex items-center gap-2 animate-pulse"
                                style="display: none;">
                                <div class="w-2 h-2 bg-red-500 rounded-full"></div>
                                <span class="text-xs font-bold text-red-500">RECORDING... <span
                                        x-text="timerDisplay"></span></span>
                            </div>
                        </div>

                        <div
                            class="bg-slate-50 rounded-xl p-6 border border-slate-200 text-center mb-6 relative overflow-hidden">
                            <div class="absolute inset-0 opacity-5"
                                style="background-image: radial-gradient(#64748b 1px, transparent 1px); background-size: 16px 16px;">
                            </div>

                            <button x-show="!isRecording && !hasAudio" @click="startRecording()"
                                class="relative inline-flex flex-col items-center gap-2 group z-10">
                                <div
                                    class="h-14 w-14 rounded-full bg-gradient-to-br from-red-500 to-red-600 text-white flex items-center justify-center shadow-lg shadow-red-500/30 group-hover:scale-110 transition-transform duration-300">
                                    <i class="ph-fill ph-microphone text-2xl"></i>
                                </div>
                                <span
                                    class="text-xs font-bold text-slate-500 group-hover:text-red-600 transition-colors">Tap
                                    to Record</span>
                            </button>

                            <button x-show="isRecording" @click="stopRecording()" style="display: none;"
                                class="relative inline-flex flex-col items-center gap-2 group z-10">
                                <div
                                    class="h-14 w-14 rounded-full bg-slate-800 text-white flex items-center justify-center shadow-lg group-hover:bg-slate-700 transition">
                                    <i class="ph-fill ph-stop text-2xl"></i>
                                </div>
                                <span class="text-xs font-bold text-slate-800">Stop Recording</span>
                            </button>

                            <div x-show="hasAudio" style="display: none;" class="w-full relative z-10">
                                <div class="bg-white p-2 rounded-lg shadow-sm border border-slate-200 mb-3">
                                    <audio x-ref="audioPlayer" controls class="w-full h-8"></audio>
                                </div>

                                <div class="flex gap-3 justify-center">
                                    <button @click="resetRecorder()"
                                        class="px-4 py-2 text-xs font-bold text-slate-500 hover:text-red-600 transition">
                                        Discard
                                    </button>
                                    <button @click="uploadAudio()"
                                        class="px-5 py-2 bg-indigo-600 text-white text-xs font-bold rounded-lg shadow-md hover:bg-indigo-700 disabled:opacity-50 flex items-center gap-2"
                                        :disabled="isUploading">
                                        <i x-show="!isUploading" class="ph-bold ph-floppy-disk"></i>
                                        <i x-show="isUploading" class="ph-bold ph-spinner animate-spin"></i>
                                        <span x-text="isUploading ? 'Uploading...' : 'Save Recording'"></span>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="space-y-3">
                            @foreach ($case->recordings as $rec)
                                <div
                                    class="flex items-center justify-between p-3 rounded-lg bg-white border border-slate-100 shadow-sm hover:border-indigo-100 hover:shadow-md transition group">
                                    <div class="flex items-center gap-3 overflow-hidden">
                                        <div
                                            class="h-9 w-9 rounded-full bg-indigo-50 text-indigo-600 flex items-center justify-center flex-shrink-0">
                                            <i class="ph-fill ph-play-circle text-xl"></i>
                                        </div>
                                        <div class="min-w-0">
                                            <p class="text-sm font-bold text-slate-700 truncate">{{ $rec->title }}
                                            </p>
                                            <p class="text-[10px] text-slate-400 uppercase tracking-wide">
                                                {{ $rec->created_at->diffForHumans() }} • {{ $rec->user->name }}</p>
                                        </div>
                                    </div>

                                    <div class="flex items-center gap-3">
                                        <audio src="{{ asset('storage/' . $rec->file_path) }}" controls
                                            class="h-7 w-28 opacity-70 hover:opacity-100 transition"></audio>

                                        <form action="{{ route('admin.recordings.destroy', $rec->id) }}"
                                            method="POST" onsubmit="return confirm('Delete recording?');">
                                            @csrf @method('DELETE')
                                            <button type="submit"
                                                class="text-slate-300 hover:text-red-500 transition p-1"
                                                title="Delete">
                                                <i class="ph-bold ph-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            @endforeach

                            @if ($case->recordings->count() === 0)
                                <p class="text-center text-xs text-slate-400 italic py-2">No voice notes recorded yet.
                                </p>
                            @endif
                        </div>
                    </div>
                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl flex flex-col mb-8"
                        x-data="{ showEvidenceForm: false }">
                        <div class="p-5 border-b border-slate-100 flex justify-between items-center bg-slate-50">
                            <h4 class="text-base font-bold text-slate-800 flex items-center gap-2">
                                <i class="ph-duotone ph-fingerprint text-amber-600"></i> Evidence Locker
                            </h4>
                            <button @click="showEvidenceForm = !showEvidenceForm"
                                class="text-amber-600 hover:text-amber-800 text-xs font-bold uppercase tracking-wider flex items-center gap-1 transition">
                                <span x-text="showEvidenceForm ? 'Cancel' : '+ LOG EVIDENCE'"></span>
                            </button>
                        </div>

                        <div x-show="showEvidenceForm" x-transition class="bg-amber-50 p-5 border-b border-amber-100">
                            <form action="{{ route('admin.evidence.store', $case->id) }}" method="POST"
                                enctype="multipart/form-data">
                                @csrf
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                    <div>
                                        <label class="block text-[10px] font-bold text-amber-900 uppercase mb-1">Item
                                            Title</label>
                                        <input type="text" name="title"
                                            class="block w-full rounded border-amber-200 text-xs focus:ring-amber-500 focus:border-amber-500"
                                            placeholder="e.g. CCTV Footage" required>
                                    </div>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-amber-900 uppercase mb-1">Exhibit
                                            Ref #</label>
                                        <input type="text" name="reference_number"
                                            class="block w-full rounded border-amber-200 text-xs focus:ring-amber-500 focus:border-amber-500"
                                            placeholder="e.g. EX-001">
                                    </div>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-amber-900 uppercase mb-1">Type</label>
                                        <select name="type"
                                            class="block w-full rounded border-amber-200 text-xs focus:ring-amber-500 focus:border-amber-500">
                                            <option value="Physical">Physical Object</option>
                                            <option value="Digital">Digital File / Video</option>
                                            <option value="Document">Original Document</option>
                                            <option value="Forensic">Forensic Report</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-amber-900 uppercase mb-1">Storage
                                            Location</label>
                                        <input type="text" name="storage_location"
                                            class="block w-full rounded border-amber-200 text-xs focus:ring-amber-500 focus:border-amber-500"
                                            placeholder="e.g. Safe Box A">
                                    </div>
                                    <div class="md:col-span-2">
                                        <label class="block text-[10px] font-bold text-amber-900 uppercase mb-1">Photo
                                            / File Attachment</label>
                                        <input type="file" name="file"
                                            class="block w-full text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-semibold file:bg-amber-200 file:text-amber-800 hover:file:bg-amber-300">
                                    </div>
                                    <div class="md:col-span-2">
                                        <label
                                            class="block text-[10px] font-bold text-amber-900 uppercase mb-1">Description
                                            / Chain of Custody</label>
                                        <textarea name="description" rows="2"
                                            class="block w-full rounded border-amber-200 text-xs focus:ring-amber-500 focus:border-amber-500"></textarea>
                                    </div>
                                </div>
                                <button type="submit"
                                    class="w-full bg-amber-600 text-white py-2 rounded text-xs font-bold hover:bg-amber-700 shadow-sm">Log
                                    Evidence</button>
                            </form>
                        </div>

                        <div class="p-5">
                            @if ($case->evidence && $case->evidence->count() > 0)
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                    @foreach ($case->evidence as $item)
                                        <div
                                            class="relative group border border-slate-200 rounded-xl p-3 hover:border-amber-200 hover:shadow-md transition bg-white flex items-start gap-3">
                                            <div
                                                class="h-16 w-16 flex-shrink-0 rounded-lg bg-slate-100 overflow-hidden flex items-center justify-center border border-slate-100">
                                                @if ($item->file_path && in_array(pathinfo($item->file_path, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'webp']))
                                                    <img src="{{ asset('storage/' . $item->file_path) }}"
                                                        class="h-full w-full object-cover" alt="Evidence">
                                                @else
                                                    <i
                                                        class="ph-duotone
                                    {{ $item->type == 'Physical'
                                        ? 'ph-cube'
                                        : ($item->type == 'Digital'
                                            ? 'ph-file-video'
                                            : ($item->type == 'Document'
                                                ? 'ph-file-text'
                                                : 'ph-fingerprint')) }}
                                    text-2xl text-slate-400"></i>
                                                @endif
                                            </div>

                                            <div class="min-w-0 flex-1">
                                                <div class="flex justify-between items-start">
                                                    <div>
                                                        <h5 class="text-sm font-bold text-slate-800 truncate"
                                                            title="{{ $item->title }}">{{ $item->title }}</h5>
                                                        <span
                                                            class="inline-flex items-center rounded-md bg-amber-50 px-1.5 py-0.5 text-[10px] font-bold text-amber-700 ring-1 ring-inset ring-amber-600/20">
                                                            {{ $item->reference_number ?? 'No Ref' }}
                                                        </span>
                                                    </div>
                                                    <form action="{{ route('admin.evidence.destroy', $item->id) }}"
                                                        method="POST"
                                                        onsubmit="return confirm('Destroy this evidence record?');">
                                                        @csrf @method('DELETE')
                                                        <button type="submit"
                                                            class="text-slate-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition"><i
                                                                class="ph-bold ph-trash"></i></button>
                                                    </form>
                                                </div>

                                                <p class="text-xs text-slate-500 mt-1 line-clamp-1">
                                                    {{ $item->description }}</p>

                                                <div
                                                    class="mt-2 flex items-center gap-2 text-[10px] text-slate-400 font-medium uppercase tracking-wide">
                                                    <span class="flex items-center gap-1"><i
                                                            class="ph-bold ph-map-pin"></i>
                                                        {{ $item->storage_location ?? 'Unspecified' }}</span>
                                                    @if ($item->file_path)
                                                        <span class="text-slate-300">|</span>
                                                        <a href="{{ asset('storage/' . $item->file_path) }}"
                                                            target="_blank"
                                                            class="text-indigo-600 hover:underline">View File</a>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            @else
                                <div class="text-center py-6">
                                    <div
                                        class="inline-flex items-center justify-center w-10 h-10 rounded-full bg-slate-50 mb-2">
                                        <i class="ph-duotone ph-fingerprint text-slate-300 text-xl"></i>
                                    </div>
                                    <p class="text-xs text-slate-400">Evidence locker is empty.</p>
                                </div>
                            @endif
                        </div>
                    </div>

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl p-6">
                        <div class="flex items-center justify-between mb-6">
                            <h4 class="text-lg font-bold text-slate-800 flex items-center gap-2">
                                <i class="ph-duotone ph-clock-counter-clockwise text-indigo-500"></i> Case Activity
                            </h4>
                        </div>

                        <div class="bg-slate-50 rounded-xl p-4 border border-slate-200 mb-8">
                            <form action="{{ route('admin.cases.notes.store', $case->id) }}" method="POST">
                                @csrf
                                <div class="relative">
                                    <textarea id="noteContent" name="content" rows="3"
                                        class="block w-full rounded-lg border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm resize-none pr-12 transition-colors bg-white"
                                        placeholder="Log a call summary, hearing notes, or internal memo..." required></textarea>

                                    <button type="button" id="startDictation"
                                        class="absolute top-2 right-2 p-2 rounded-full text-slate-400 hover:text-indigo-600 hover:bg-indigo-50 transition"
                                        title="Dictate Note">
                                        <i class="ph-bold ph-microphone text-xl"></i>
                                    </button>

                                    <div id="recordingIndicator"
                                        class="hidden absolute top-3 right-12 flex items-center gap-2">
                                        <span class="flex h-2 w-2 relative">
                                            <span
                                                class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                                            <span class="relative inline-flex rounded-full h-2 w-2 bg-red-500"></span>
                                        </span>
                                        <span
                                            class="text-[10px] font-bold text-red-500 animate-pulse uppercase">Listening</span>
                                    </div>

                                    <div class="mt-2 flex justify-between items-center">
                                        <div class="flex space-x-2">
                                            <select name="type"
                                                class="pl-2 pr-8 py-1 bg-white border border-slate-200 text-xs font-bold text-slate-600 rounded-lg hover:border-indigo-300 cursor-pointer focus:ring-0 shadow-sm">
                                                <option value="note">📝 General Note</option>
                                                <option value="call">📞 Phone Call</option>
                                                <option value="email">📧 Email Sent</option>
                                                <option value="hearing">⚖️ Court Hearing</option>
                                            </select>
                                            <label
                                                class="flex items-center space-x-1.5 px-2 py-1 rounded cursor-pointer hover:bg-slate-100 select-none border border-transparent hover:border-slate-200 transition">
                                                <input type="checkbox" name="is_visible_to_client"
                                                    class="rounded text-indigo-600 focus:ring-indigo-500 h-3.5 w-3.5 border-slate-300">
                                                <span class="text-xs text-slate-500 font-bold">Client Visible</span>
                                            </label>
                                        </div>
                                        <button type="submit"
                                            class="bg-slate-900 text-white px-4 py-1.5 rounded-lg text-xs font-bold hover:bg-slate-800 transition shadow-lg">Post
                                            Entry</button>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <div class="flow-root pl-2">
                            <ul role="list" class="-mb-8">
                                @forelse($case->timeline as $note)
                                    <li>
                                        <div class="relative pb-8">
                                            @if (!$loop->last)
                                                <span class="absolute top-5 left-5 -ml-px h-full w-0.5 bg-slate-200"
                                                    aria-hidden="true"></span>
                                            @endif
                                            <div class="relative flex items-start space-x-3">
                                                @php
                                                    $iconConfig = match ($note->type) {
                                                        'call' => [
                                                            'bg' => 'bg-emerald-100',
                                                            'text' => 'text-emerald-600',
                                                            'icon' => 'ph-phone',
                                                        ],
                                                        'hearing' => [
                                                            'bg' => 'bg-red-100',
                                                            'text' => 'text-red-600',
                                                            'icon' => 'ph-gavel',
                                                        ],
                                                        'email' => [
                                                            'bg' => 'bg-blue-100',
                                                            'text' => 'text-blue-600',
                                                            'icon' => 'ph-envelope',
                                                        ],
                                                        default => [
                                                            'bg' => 'bg-slate-100',
                                                            'text' => 'text-slate-600',
                                                            'icon' => 'ph-notepad',
                                                        ],
                                                    };
                                                @endphp
                                                <div class="relative">
                                                    <div
                                                        class="h-10 w-10 rounded-full {{ $iconConfig['bg'] }} flex items-center justify-center ring-4 ring-white shadow-sm z-10 relative">
                                                        <i
                                                            class="ph-fill {{ $iconConfig['icon'] }} {{ $iconConfig['text'] }} text-lg"></i>
                                                    </div>
                                                </div>
                                                <div class="min-w-0 flex-1 py-0">
                                                    <div class="flex justify-between items-center mb-1">
                                                        <span
                                                            class="font-bold text-slate-800 text-sm">{{ $note->user->name }}</span>
                                                        <span
                                                            class="text-xs text-slate-400">{{ $note->activity_date->diffForHumans() }}</span>
                                                    </div>
                                                    <div
                                                        class="bg-slate-50 p-3 rounded-lg border border-slate-100 text-sm text-slate-700 shadow-sm relative group hover:border-indigo-100 transition">
                                                        {{ $note->content }}
                                                    </div>
                                                    @if ($note->is_visible_to_client)
                                                        <div class="mt-1 flex items-center gap-1">
                                                            <i class="ph-bold ph-eye text-emerald-500 text-xs"></i>
                                                            <span
                                                                class="text-[10px] text-emerald-600 font-bold uppercase tracking-wider">Visible
                                                                to Client</span>
                                                        </div>
                                                    @endif
                                                </div>
                                            </div>
                                        </div>
                                    </li>
                                @empty
                                    <li class="text-center py-8">
                                        <p class="text-sm text-slate-400 italic">No activity logged yet.</p>
                                    </li>
                                @endforelse
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="lg:col-span-1 space-y-8">

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl overflow-hidden">
                        <div class="px-5 py-4 border-b border-slate-100 bg-slate-50 flex items-center gap-2">
                            <i class="ph-duotone ph-list-dashes text-indigo-500"></i>
                            <h4 class="text-sm font-bold text-slate-700 uppercase tracking-wider">Case Particulars</h4>
                        </div>
                        <div class="p-5 space-y-4">
                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Presiding Judge
                                </p>
                                <p class="text-sm font-bold text-slate-800 flex items-center gap-1">
                                    <i class="ph-fill ph-user-circle text-slate-300"></i>
                                    {{ $case->judge_name ?? 'Not Assigned' }}
                                </p>
                            </div>

                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Opposing
                                    Counsel</p>
                                <p class="text-sm font-medium text-slate-700">{{ $case->opposing_counsel ?? 'N/A' }}
                                </p>
                            </div>

                            <div class="border-t border-slate-100 my-2"></div>

                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wide">Police Station
                                </p>
                                <p class="text-sm font-medium text-slate-700">{{ $case->police_station ?? 'N/A' }}</p>
                            </div>
                            <div>
                                <p class="text-[10px] font-bold text-slate-400 uppercase tracking-wide">OB Number</p>
                                <p class="text-sm font-mono text-slate-600 bg-slate-100 inline-block px-2 rounded">
                                    {{ $case->police_ob_number ?? 'N/A' }}</p>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl flex flex-col"
                        x-data="{ showWitnessForm: false }">
                        <div class="p-5 border-b border-slate-100 flex justify-between items-center bg-slate-50">
                            <h4
                                class="text-sm font-bold text-slate-700 uppercase tracking-wider flex items-center gap-2">
                                <i class="ph-duotone ph-users-three text-indigo-500"></i> Witnesses
                            </h4>
                            <button @click="showWitnessForm = !showWitnessForm"
                                class="text-indigo-600 hover:text-indigo-800 text-xs font-bold uppercase tracking-wider flex items-center gap-1 transition">
                                <span x-text="showWitnessForm ? 'Cancel' : '+ ADD'"></span>
                            </button>
                        </div>

                        <div x-show="showWitnessForm" x-transition
                            class="bg-indigo-50 p-5 border-b border-indigo-100">
                            <form action="{{ route('admin.witnesses.store', $case->id) }}" method="POST">
                                @csrf
                                <div class="space-y-3">
                                    <div class="grid grid-cols-2 gap-3">
                                        <div>
                                            <label
                                                class="block text-[10px] font-bold text-indigo-900 uppercase mb-1">Full
                                                Name</label>
                                            <input type="text" name="name"
                                                class="block w-full rounded border-indigo-200 text-xs focus:ring-indigo-500 focus:border-indigo-500"
                                                required>
                                        </div>
                                        <div>
                                            <label
                                                class="block text-[10px] font-bold text-indigo-900 uppercase mb-1">Role</label>
                                            <select name="type"
                                                class="block w-full rounded border-indigo-200 text-xs focus:ring-indigo-500 focus:border-indigo-500">
                                                <option value="eyewitness">Eyewitness</option>
                                                <option value="expert">Expert</option>
                                                <option value="defense">Defense</option>
                                                <option value="plaintiff">Plaintiff</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-indigo-900 uppercase mb-1">Statement</label>
                                        <textarea name="statement" rows="2"
                                            class="block w-full rounded border-indigo-200 text-xs focus:ring-indigo-500 focus:border-indigo-500"
                                            placeholder="Summary..."></textarea>
                                    </div>
                                    <button type="submit"
                                        class="w-full bg-indigo-600 text-white py-2 rounded text-xs font-bold hover:bg-indigo-700 shadow-sm">Save
                                        Witness</button>
                                </div>
                            </form>
                        </div>

                        <div class="flex-1 overflow-y-auto max-h-[300px]">
                            @if ($case->witnesses && $case->witnesses->count() > 0)
                                <ul class="divide-y divide-slate-100">
                                    @foreach ($case->witnesses as $witness)
                                        <li class="p-4 hover:bg-slate-50 transition group">
                                            <div class="flex items-start justify-between">
                                                <div class="flex items-start gap-3">
                                                    <div
                                                        class="mt-1 h-8 w-8 rounded-full bg-slate-100 flex items-center justify-center text-slate-500 flex-shrink-0">
                                                        <i class="ph-fill ph-user"></i>
                                                    </div>
                                                    <div>
                                                        <p class="text-sm font-bold text-slate-800">
                                                            {{ $witness->name }}</p>
                                                        <span
                                                            class="inline-flex items-center rounded-md bg-slate-100 px-2 py-0.5 text-[10px] font-bold text-slate-600 uppercase tracking-wide mb-1">
                                                            {{ $witness->type }}
                                                        </span>
                                                        @if ($witness->statement)
                                                            <p
                                                                class="text-xs text-slate-500 mt-1 italic leading-tight">
                                                                "{{ Str::limit($witness->statement, 50) }}"</p>
                                                        @endif
                                                    </div>
                                                </div>
                                                <form action="{{ route('admin.witnesses.destroy', $witness->id) }}"
                                                    method="POST" onsubmit="return confirm('Remove this witness?');">
                                                    @csrf @method('DELETE')
                                                    <button type="submit"
                                                        class="text-slate-300 hover:text-red-500 opacity-0 group-hover:opacity-100 transition p-1"><i
                                                            class="ph-bold ph-trash"></i></button>
                                                </form>
                                            </div>
                                        </li>
                                    @endforeach
                                </ul>
                            @else
                                <div class="text-center py-6">
                                    <p class="text-xs text-slate-400">No witnesses added.</p>
                                </div>
                            @endif
                        </div>
                    </div>

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl flex flex-col"
                        x-data="{ showUpload: false }">
                        <div class="p-5 border-b border-slate-100 flex justify-between items-center bg-slate-50">
                            <h4
                                class="text-sm font-bold text-slate-700 uppercase tracking-wider flex items-center gap-2">
                                <i class="ph-duotone ph-files text-indigo-500"></i> Documents
                            </h4>
                            <button @click="showUpload = !showUpload"
                                class="text-indigo-600 hover:text-indigo-800 text-xs font-bold uppercase tracking-wider flex items-center gap-1 transition">
                                <span x-text="showUpload ? 'Cancel' : '+ ADD'"></span>
                            </button>
                        </div>

                        <div x-show="showUpload" x-transition class="bg-indigo-50 p-5 border-b border-indigo-100">
                            <form action="{{ route('admin.documents.store', $case->id) }}" method="POST"
                                enctype="multipart/form-data">
                                @csrf
                                <div class="space-y-4">
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-indigo-900 uppercase mb-1">Title</label>
                                        <input type="text" name="title"
                                            class="block w-full rounded border-indigo-200 text-xs focus:ring-indigo-500 focus:border-indigo-500"
                                            required>
                                    </div>
                                    <div>
                                        <label
                                            class="block text-[10px] font-bold text-indigo-900 uppercase mb-1">File</label>
                                        <input type="file" name="document"
                                            class="block w-full text-xs text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-xs file:font-semibold file:bg-indigo-100 file:text-indigo-700 hover:file:bg-indigo-200"
                                            required>
                                    </div>
                                    <button type="submit"
                                        class="w-full bg-indigo-600 text-white py-2 rounded text-xs font-bold hover:bg-indigo-700 shadow-sm">Upload
                                        File</button>
                                </div>
                            </form>
                        </div>

                        <div class="flex-1 overflow-y-auto max-h-[500px]">
                            @if ($case->documents->count() > 0)
                                <ul class="divide-y divide-slate-100">
                                    @foreach ($case->documents as $doc)
                                        <li class="p-4 hover:bg-slate-50 transition group">
                                            <div class="flex items-start space-x-3">
                                                <div
                                                    class="flex-shrink-0 h-10 w-10 rounded-lg flex items-center justify-center border border-slate-100 {{ in_array($doc->file_type, ['pdf']) ? 'bg-red-50 text-red-500' : 'bg-blue-50 text-blue-500' }}">
                                                    <i
                                                        class="ph-fill {{ in_array($doc->file_type, ['pdf']) ? 'ph-file-pdf' : 'ph-file-text' }} text-xl"></i>
                                                </div>
                                                <div class="min-w-0 flex-1">
                                                    <p class="text-sm font-semibold text-slate-800 truncate">
                                                        {{ $doc->title }}</p>
                                                    <p
                                                        class="text-[10px] text-slate-400 mt-0.5 uppercase tracking-wide">
                                                        {{ $doc->file_type }} • {{ $doc->created_at->format('M d') }}
                                                    </p>
                                                </div>
                                            </div>
                                            <div
                                                class="mt-3 flex items-center justify-end gap-3 opacity-60 group-hover:opacity-100 transition">
                                                @if (in_array(strtolower($doc->file_type), ['pdf', 'jpg', 'jpeg', 'png']))
                                                    <a href="{{ route('admin.documents.preview', $doc->id) }}"
                                                        target="_blank"
                                                        class="text-xs font-bold text-slate-600 hover:text-indigo-600 flex items-center gap-1 transition"><i
                                                            class="ph-bold ph-eye"></i> View</a>
                                                @endif
                                                <a href="{{ route('admin.documents.download', $doc->id) }}"
                                                    class="text-xs font-bold text-slate-600 hover:text-green-600 flex items-center gap-1 transition"><i
                                                        class="ph-bold ph-download-simple"></i> Save</a>
                                            </div>
                                        </li>
                                    @endforeach
                                </ul>
                            @else
                                <div class="text-center py-10">
                                    <p class="text-xs text-slate-400">No documents uploaded.</p>
                                </div>
                            @endif
                        </div>
                    </div>

                    <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl p-5">
                        <div class="flex items-center justify-between text-xs mb-2">
                            <span class="text-slate-500 font-medium">Created</span>
                            <span
                                class="text-slate-700 font-mono bg-slate-100 px-2 py-1 rounded">{{ $case->created_at->format('Y-m-d') }}</span>
                        </div>
                        <div class="flex items-center justify-between text-xs">
                            <span class="text-slate-500 font-medium">Updated</span>
                            <span
                                class="text-slate-700 font-mono bg-slate-100 px-2 py-1 rounded">{{ $case->updated_at->diffForHumans() }}</span>
                        </div>
                    </div>
                </div>

            </div>

           <div class="bg-white shadow-sm ring-1 ring-slate-900/5 sm:rounded-xl overflow-hidden mt-8">
    <div class="p-6 border-b border-slate-100 flex justify-between items-center bg-white">
        <h4 class="text-lg font-bold text-slate-800 flex items-center gap-2">
            <i class="ph-duotone ph-receipt text-indigo-500"></i> Invoices & Billing
        </h4>
        <a href="{{ route('admin.invoices.create', $case->id) }}"
            class="bg-indigo-50 text-indigo-700 border border-indigo-100 px-4 py-2 rounded-lg text-xs font-bold hover:bg-indigo-100 transition shadow-sm">
            + Create Invoice
        </a>
    </div>

    @if ($case->invoices && $case->invoices->count() > 0)
        <div class="overflow-x-auto">
            <table class="min-w-full text-left text-sm whitespace-nowrap">
                <thead class="bg-slate-50 text-slate-500 font-semibold border-b border-slate-200">
                    <tr>
                        <th class="px-6 py-3">Invoice #</th>
                        <th class="px-6 py-3">Date</th>
                        <th class="px-6 py-3">Amount</th>
                        <th class="px-6 py-3">Status</th>
                        <th class="px-6 py-3 text-right">Action</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    @foreach ($case->invoices as $inv)
                        <tr class="hover:bg-slate-50 transition group">
                            <td class="px-6 py-4 font-bold text-slate-700">
                                {{ $inv->invoice_number }}
                                @if($inv->user_id === auth()->id())
                                    <span class="ml-1 text-[10px] text-slate-400 font-normal">(You)</span>
                                @endif
                            </td>

                            <td class="px-6 py-4 text-slate-500">{{ $inv->created_at->format('M d, Y') }}</td>

                            <td class="px-6 py-4 font-mono text-slate-700">KES {{ number_format($inv->total_amount) }}</td>

                            <td class="px-6 py-4">
                                @if ($inv->status === 'paid')
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold border bg-emerald-50 text-emerald-700 border-emerald-100">
                                        <span class="h-1.5 w-1.5 rounded-full bg-emerald-500"></span> Paid
                                    </span>
                                @elseif ($inv->status === 'pending_approval')
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold border bg-amber-50 text-amber-700 border-amber-100">
                                        <i class="ph-fill ph-hourglass text-amber-500"></i> Pending Approval
                                    </span>
                                @elseif ($inv->status === 'draft')
                                    <div class="flex flex-col items-start gap-1">
                                        <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold border bg-red-50 text-red-700 border-red-100">
                                            <i class="ph-fill ph-warning-circle text-red-500"></i> Rejected
                                        </span>
                                        @if($inv->rejection_reason)
                                            <span class="text-[10px] text-red-500 max-w-[150px] truncate" title="{{ $inv->rejection_reason }}">
                                                "{{ $inv->rejection_reason }}"
                                            </span>
                                        @endif
                                    </div>
                                @else
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold border bg-slate-100 text-slate-600 border-slate-200">
                                        <span class="h-1.5 w-1.5 rounded-full bg-slate-400"></span> {{ ucfirst($inv->status) }}
                                    </span>
                                @endif
                            </td>

                            <td class="px-6 py-4 text-right">
                                <div class="flex items-center justify-end gap-2">

                                    @if ($inv->status === 'pending_approval' && auth()->user()->isHeadOfLegal())
                                        <div class="flex items-center bg-white border border-slate-200 rounded-lg shadow-sm mr-2" x-data="{ showRejectModal: false }">

                                            <form action="{{ route('admin.invoices.approve', $inv->id) }}" method="POST">
                                                @csrf
                                                <button type="submit" class="px-3 py-1.5 text-emerald-600 hover:bg-emerald-50 border-r border-slate-200 rounded-l-lg transition" title="Approve">
                                                    <i class="ph-bold ph-check text-lg"></i>
                                                </button>
                                            </form>

                                            <button @click="showRejectModal = true" class="px-3 py-1.5 text-red-500 hover:bg-red-50 rounded-r-lg transition" title="Reject">
                                                <i class="ph-bold ph-x text-lg"></i>
                                            </button>

                                            <div x-show="showRejectModal" class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 backdrop-blur-sm text-left" style="display: none;">
                                                <div class="bg-white rounded-xl shadow-2xl p-6 w-80 ring-1 ring-slate-900/5" @click.away="showRejectModal = false">
                                                    <h3 class="text-sm font-bold text-slate-800 mb-2">Reject Invoice #{{ $inv->invoice_number }}</h3>
                                                    <form action="{{ route('admin.invoices.reject', $inv->id) }}" method="POST">
                                                        @csrf
                                                        <textarea name="reason" rows="3" class="w-full rounded-md border-slate-300 text-xs focus:ring-red-500 focus:border-red-500 mb-3" placeholder="Reason for rejection..." required></textarea>
                                                        <div class="flex justify-end gap-2">
                                                            <button type="button" @click="showRejectModal = false" class="text-slate-500 text-xs font-bold px-3 py-2 hover:bg-slate-50 rounded">Cancel</button>
                                                            <button type="submit" class="bg-red-600 text-white px-3 py-2 rounded text-xs font-bold hover:bg-red-700">Reject</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    @endif

                                    @if ($inv->status === 'unpaid' || $inv->status === 'paid')
                                        <form action="{{ route('admin.invoices.send', $inv->id) }}" method="POST">
                                            @csrf
                                            <button type="submit" class="text-slate-400 hover:text-amber-600 transition p-1" title="Email Invoice">
                                                <i class="ph-bold ph-paper-plane-tilt text-lg"></i>
                                            </button>
                                        </form>
                                    @endif

                                    <a href="{{ route('admin.invoices.edit', $inv->id) }}" class="text-slate-400 hover:text-indigo-600 transition p-1" title="Edit">
                                        <i class="ph-bold ph-pencil-simple text-lg"></i>
                                    </a>

                                    <a href="{{ route('admin.invoices.download', $inv->id) }}" class="text-slate-400 hover:text-green-600 transition p-1" title="Download PDF">
                                        <i class="ph-bold ph-download-simple text-lg"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    @else
        <div class="p-12 text-center">
            <div class="bg-slate-50 rounded-full h-12 w-12 flex items-center justify-center mx-auto mb-3">
                <i class="ph-duotone ph-receipt text-2xl text-slate-300"></i>
            </div>
            <p class="text-sm text-slate-500">No invoices generated for this case yet.</p>
        </div>
    @endif
</div>
        </div>
    </div>

    <div id="descModal" class="fixed inset-0 z-50 hidden transition-opacity duration-300" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity" onclick="closeDescriptionModal()"></div>

        <div class="fixed inset-0 z-10 overflow-y-auto">
            <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">

                <div class="relative transform overflow-hidden rounded-2xl bg-white text-left shadow-2xl transition-all sm:my-8 sm:w-full sm:max-w-lg border border-slate-100">

                    <div class="bg-slate-50 px-4 py-3 sm:px-6 flex justify-between items-center border-b border-slate-100">
                        <h3 class="text-base font-bold leading-6 text-slate-900 flex items-center gap-2" id="modalTitle">
                            Case Facts
                        </h3>
                        <button type="button" onclick="closeDescriptionModal()" class="rounded-md bg-white text-slate-400 hover:text-red-500 focus:outline-none">
                            <i class="ph-bold ph-x text-lg"></i>
                        </button>
                    </div>

                    <div class="px-4 py-5 sm:p-6 max-h-[60vh] overflow-y-auto">
                        <div class="prose prose-sm prose-slate text-slate-600">
                            <p id="modalContent">No description available.</p>
                        </div>
                    </div>

                    <div class="bg-slate-50 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6 border-t border-slate-100">
                        <button type="button" onclick="closeDescriptionModal()" class="mt-3 inline-flex w-full justify-center rounded-lg bg-white px-3 py-2 text-sm font-semibold text-slate-900 shadow-sm ring-1 ring-inset ring-slate-300 hover:bg-slate-50 sm:mt-0 sm:w-auto">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const micBtn = document.getElementById('startDictation');
        const textArea = document.getElementById('noteContent');
        const indicator = document.getElementById('recordingIndicator');
        const icon = micBtn ? micBtn.querySelector('i') : null;

        if (!micBtn) return;

        // Compatibility check
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        if (!SpeechRecognition) {
            micBtn.style.display = 'none';
            console.warn("Speech Recognition not supported in this browser.");
            return;
        }

        const recognition = new SpeechRecognition();

        // CHANGE: Setting continuous to true keeps the mic open
        // until you manually hit STOP.
        recognition.continuous = true;
        recognition.interimResults = true; // Shows text as you speak
        recognition.lang = 'en-US';

        let isRecording = false;

        micBtn.addEventListener('click', (e) => {
            e.preventDefault(); // Prevent form submission if inside a form
            if (isRecording) {
                recognition.stop();
            } else {
                try {
                    recognition.start();
                } catch (err) {
                    console.error("Recognition start error:", err);
                }
            }
        });

        recognition.onstart = () => {
            isRecording = true;
            indicator.classList.remove('hidden');
            icon.classList.replace('ph-microphone', 'ph-stop');
            icon.classList.add('text-red-600', 'animate-pulse');
            micBtn.classList.add('bg-red-50', 'border-red-200');
        };

        recognition.onend = () => {
            isRecording = false;
            indicator.classList.add('hidden');
            icon.classList.replace('ph-stop', 'ph-microphone');
            icon.classList.remove('text-red-600', 'animate-pulse');
            micBtn.classList.remove('bg-red-50', 'border-red-200');
        };

        recognition.onerror = (event) => {
            console.error("Speech Recognition Error:", event.error);
            if (event.error === 'not-allowed') {
                alert("Permission to use microphone was denied.");
            }
            isRecording = false;
        };

        recognition.onresult = (event) => {
            let interimTranscript = '';
            let finalTranscript = '';

            for (let i = event.resultIndex; i < event.results.length; ++i) {
                if (event.results[i].isFinal) {
                    finalTranscript += event.results[i][0].transcript;
                }
            }

            if (finalTranscript) {
                const currentText = textArea.value;
                const space = (currentText.length > 0 && !currentText.endsWith(' ')) ? ' ' : '';
                textArea.value += space + finalTranscript + '. ';
                // Auto-scroll to bottom of textarea
                textArea.scrollTop = textArea.scrollHeight;
            }
        };
    });
</script>

{{-- <script>
    document.addEventListener('DOMContentLoaded', function() {
        const micBtn = document.getElementById('startDictation');
        const textArea = document.getElementById('noteContent');
        const indicator = document.getElementById('recordingIndicator');
        const icon = micBtn.querySelector('i');

        if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
            micBtn.style.display = 'none';
            return;
        }

        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        const recognition = new SpeechRecognition();

        recognition.continuous = false;
        recognition.interimResults = false;
        recognition.lang = 'en-US';

        let isRecording = false;

        micBtn.addEventListener('click', () => {
            if (isRecording) {
                recognition.stop();
            } else {
                recognition.start();
            }
        });

        recognition.onstart = () => {
            isRecording = true;
            indicator.classList.remove('hidden');
            icon.classList.remove('ph-microphone');
            icon.classList.add('ph-stop', 'text-red-600');
            micBtn.classList.add('bg-red-50');
        };

        recognition.onend = () => {
            isRecording = false;
            indicator.classList.add('hidden');
            icon.classList.remove('ph-stop', 'text-red-600');
            icon.classList.add('ph-microphone');
            micBtn.classList.remove('bg-red-50');
        };

        recognition.onresult = (event) => {
            const transcript = event.results[0][0].transcript;
            const currentText = textArea.value;
            if (currentText.length > 0 && !currentText.endsWith(' ')) {
                textArea.value += ' ' + transcript + '.';
            } else {
                textArea.value += transcript + '.';
            }
        };
    });
</script> --}}

<script>
    function openDescriptionModal(title, desc) {
        document.getElementById('modalTitle').innerText = title;
        // Check if desc is null, undefined, or string 'null'
        if (!desc || desc === 'null') {
            document.getElementById('modalContent').innerText = 'No description or facts recorded for this case.';
        } else {
            document.getElementById('modalContent').innerText = desc;
        }
        document.getElementById('descModal').classList.remove('hidden');
    }

    function closeDescriptionModal() {
        document.getElementById('descModal').classList.add('hidden');
    }
</script>


<script>
    function audioRecorder() {
        return {
            isRecording: false,
            hasAudio: false,
            isUploading: false,
            mediaRecorder: null,
            audioChunks: [],
            audioBlob: null,
            timerDisplay: '00:00',
            startTime: null,
            timerInterval: null,

            async startRecording() {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({
                        audio: true
                    });
                    this.mediaRecorder = new MediaRecorder(stream);
                    this.audioChunks = [];
                    this.mediaRecorder.ondataavailable = e => this.audioChunks.push(e.data);
                    this.mediaRecorder.onstop = () => {
                        this.audioBlob = new Blob(this.audioChunks, {
                            type: 'audio/webm'
                        });
                        this.$refs.audioPlayer.src = URL.createObjectURL(this.audioBlob);
                        this.hasAudio = true;
                    };
                    this.mediaRecorder.start();
                    this.isRecording = true;
                    this.startTimer();
                } catch (err) {
                    alert("Mic access denied.");
                }
            },

            stopRecording() {
                if (this.mediaRecorder) {
                    this.mediaRecorder.stop();
                    this.isRecording = false;
                    this.stopTimer();
                    this.mediaRecorder.stream.getTracks().forEach(track => track.stop());
                }
            },

            resetRecorder() {
                this.hasAudio = false;
                this.audioBlob = null;
                this.timerDisplay = '00:00';
            },

            async uploadAudio() {
                if (!this.audioBlob) return;
                this.isUploading = true;
                let formData = new FormData();
                formData.append('audio_blob', this.audioBlob, 'recording.webm');
                formData.append('_token', '{{ csrf_token() }}');

                try {
                    const res = await fetch("{{ route('admin.recordings.store', $case->id) }}", {
                        method: 'POST',
                        body: formData
                    });
                    if (res.ok) window.location.reload();
                    else alert("Upload failed.");
                } catch (err) {
                    console.error(err);
                    alert("Error saving.");
                } finally {
                    this.isUploading = false;
                }
            },

            startTimer() {
                this.startTime = Date.now();
                this.timerInterval = setInterval(() => {
                    const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
                    const mins = String(Math.floor(elapsed / 60)).padStart(2, '0');
                    const secs = String(elapsed % 60).padStart(2, '0');
                    this.timerDisplay = `${mins}:${secs}`;
                }, 1000);
            },

            stopTimer() {
                clearInterval(this.timerInterval);
            }
        }
    }
</script>
