<x-app-layout>
    <a href="{{ route('expenses.index') }}" class="inline-flex items-center gap-1.5 text-slate-600 hover:text-slate-900 text-sm font-medium mb-3 transition duration-150">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M15 19l-7-7 7-7"/></svg>
        Back to Expenses
    </a>
    <!-- Page Header -->
    <div class="flex flex-col md:flex-row md:items-center justify-between mb-8">
        <div class="flex items-center space-x-4">
            <div>
                <h2 class="text-xl md:text-2xl font-bold text-slate-800">Expense Details</h2>
                <p class="text-slate-500 text-sm mt-1">Logged by {{ $expense->creator ? $expense->creator->first_name . ' ' . $expense->creator->last_name : 'System' }} on {{ $expense->created_at->format('d M Y H:i') }}</p>
            </div>
        </div>
        
        @if(!auth()->user()->isAccountant())
        <div class="mt-4 md:mt-0 flex flex-nowrap md:flex-wrap gap-2 md:gap-3 justify-center md:justify-end">
            @if(!auth()->user()->isDataEntryManager())
            <a href="{{ route('expenses.download-pdf', $expense->id) }}" class="inline-flex items-center justify-center p-2.5 md:py-2.5 md:px-4 bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 hover:border-slate-300 rounded-xl text-sm font-semibold transition duration-150 flex-shrink-0">
                <svg class="w-5 h-5 md:w-4 md:h-4 md:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                </svg>
                <span class="hidden md:inline">Download PDF</span>
            </a>

            <div x-data="{ open: false, email: '', subject: 'Expense Receipt - {{ $businessName }}', message: '' }" @click.outside="open = false" class="relative flex-shrink-0">
                <button @click="open = !open" class="inline-flex items-center justify-center p-2.5 md:py-2.5 md:px-4 bg-brand-50 hover:bg-brand-600 text-brand-500 hover:text-white border border-brand-200 hover:border-brand-500 rounded-xl text-sm font-semibold transition duration-150">
                    <svg class="w-5 h-5 md:w-4 md:h-4 md:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                    </svg>
                    <span class="hidden md:inline">Email</span>
                </button>
                <div x-show="open" class="fixed md:absolute inset-x-4 md:inset-x-auto top-1/2 md:top-auto md:right-0 md:mt-2 w-auto md:w-96 -translate-y-1/2 md:translate-y-0 bg-white border border-slate-200 rounded-2xl p-4 md:p-5 shadow-xl z-50" x-cloak>
                    <div class="flex items-center justify-between mb-3">
                        <h3 class="text-sm font-bold text-slate-700">Send Email</h3>
                        <button @click="open = false" class="text-slate-500 hover:text-slate-800 p-1">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                    </div>
                    <form method="POST" action="{{ route('expenses.send-email', $expense->id) }}">
                        @csrf
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs text-slate-600 font-semibold uppercase mb-1">To</label>
                                <input type="email" name="email" required placeholder="recipient@example.com" x-model="email" class="w-full py-2 px-3 bg-white border border-slate-300 rounded-xl text-slate-800 text-sm focus:outline-none focus:border-brand-500">
                            </div>
                            <div>
                                <label class="block text-xs text-slate-600 font-semibold uppercase mb-1">Subject</label>
                                <input type="text" name="subject" x-model="subject" class="w-full py-2 px-3 bg-white border border-slate-300 rounded-xl text-slate-800 text-sm focus:outline-none focus:border-brand-500">
                            </div>
                            <div>
                                <label class="block text-xs text-slate-600 font-semibold uppercase mb-1">Message</label>
                                <textarea name="message" x-model="message" rows="3" placeholder="Write a brief message..." class="w-full py-2 px-3 bg-white border border-slate-300 rounded-xl text-slate-800 text-sm focus:outline-none focus:border-brand-500 resize-none"></textarea>
                            </div>
                            <button type="submit" class="w-full py-2.5 bg-brand-500 hover:bg-brand-600 text-white text-sm font-bold rounded-xl transition duration-150 flex items-center justify-center gap-2">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>
                                Send Email
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <button x-data="{ sharing: false }" @click="
                sharing = true;
                $nextTick(async () => {
                    try {
                        let res = await fetch('{{ route('expenses.share-whatsapp', $expense->id) }}');
                        let data = await res.json();
                        let pdfRes = await fetch(data.pdf_url);
                        let pdfBlob = await pdfRes.blob();
                        let file = new File([pdfBlob], data.filename, { type: 'application/pdf' });
                        if (navigator.canShare && navigator.canShare({ files: [file] })) {
                            await navigator.share({ files: [file], title: data.filename, text: data.text });
                        } else {
                            let a = document.createElement('a');
                            a.href = data.pdf_url;
                            a.download = data.filename;
                            a.click();
                        }
                    } catch(e) {
                        if (e.name !== 'AbortError') {
                            let a = document.createElement('a');
                            let res = await fetch('{{ route('expenses.share-whatsapp', $expense->id) }}');
                            let data = await res.json();
                            a.href = data.pdf_url;
                            a.download = data.filename;
                            a.click();
                        }
                    } finally { sharing = false; }
                });
            " class="inline-flex items-center justify-center p-2.5 md:py-2.5 md:px-4 bg-brand-50 hover:bg-brand-600 text-brand-700 hover:text-white border border-brand-200 hover:border-brand-500 rounded-xl text-sm font-semibold transition duration-150 flex-shrink-0">
                <svg class="w-5 h-5 md:w-4 md:h-4 md:mr-2" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/>
                </svg>
                <span class="hidden md:inline" x-text="sharing ? 'Preparing...' : 'WhatsApp'"></span>
            </button>
            @endif

            <a href="{{ route('expenses.edit', $expense->id) }}" class="inline-flex items-center justify-center p-2.5 md:py-2.5 md:px-4 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-xl transition duration-150 flex-shrink-0">
                <svg class="w-5 h-5 md:w-4 md:h-4 md:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                <span class="hidden md:inline">Edit</span>
            </a>
            @if(auth()->user()->isAdmin())
                <form action="{{ route('expenses.destroy', $expense->id) }}" method="POST" onsubmit="return confirm('Delete this expense permanently?')">
                    @csrf @method('DELETE')
                    <button type="submit" class="inline-flex items-center justify-center p-2.5 md:py-2.5 md:px-4 bg-rose-50 hover:bg-rose-100 text-rose-600 hover:text-rose-700 border border-rose-200 hover:border-rose-300 rounded-xl text-xs font-semibold transition flex-shrink-0">
                        <svg class="w-5 h-5 md:w-4 md:h-4 md:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                        <span class="hidden md:inline">Delete</span>
                    </button>
                </form>
            @endif
        </div>
        @endif
    </div>

    <!-- Details Grid -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-8">
        <!-- Text details -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Core Details Card -->
            <div class="bg-white border border-slate-200 rounded-xl shadow-sm p-5">
                <div class="flex justify-between items-start mb-6 border-b border-slate-200 pb-4">
                    <div>
                        <span class="px-2.5 py-1 bg-rose-50 border border-rose-200 text-rose-600 text-xs font-bold uppercase rounded-full tracking-wider block w-max mb-2">Expense</span>
                        @if($expense->category)
                            <h3 class="text-xl font-bold text-slate-800">
                                @if($expense->category->parent)
                                    {{ $expense->category->parent->name }} &rsaquo; 
                                @endif
                                {{ $expense->category->name }}
                            </h3>
                        @else
                            <h3 class="text-xl font-bold text-slate-800">Uncategorized</h3>
                        @endif
                    </div>
                    <div class="text-right">
                        <span class="text-xs text-slate-400 uppercase font-semibold block mb-1">Amount Paid</span>
                        @if($expense->original_currency)
                            <span class="text-xs text-slate-500 block font-mono">{{ number_format($expense->original_amount, 2) }} {{ $expense->original_currency }}</span>
                            <span class="text-xs text-slate-400 block font-mono">(Rate: 1 {{ $expense->original_currency }} = {{ number_format($expense->exchange_rate, 6) }} {{ $baseCurrencyCode }})</span>
                        @endif
                        <span class="text-2xl md:text-3xl font-extrabold text-rose-600 font-mono">{{ $currencySymbol }}{{ number_format($expense->amount, 2) }}</span>
                    </div>
                </div>

                <table class="w-full text-sm">
                    <tr class="h-auto min-h-[2.5rem] md:h-10 border-b border-slate-200">
                        <td class="text-slate-400 w-1/3 align-top md:align-middle">Expense Date:</td>
                        <td class="text-slate-700 font-medium">{{ $expense->date->format('d-m-Y') }}</td>
                    </tr>
                    <tr class="h-auto min-h-[2.5rem] md:h-10 border-b border-slate-200">
                        <td class="text-slate-400">Paid Out From:</td>
                        <td class="text-slate-700 font-medium">
                            @if($expense->bankAccount)
                                {{ $expense->bankAccount->name }} ({{ $expense->bankAccount->bank_name }})
                            @else
                                N/A
                            @endif
                        </td>
                    </tr>
                    <tr class="h-auto min-h-[2.5rem] md:h-10 border-b border-slate-200">
                        <td class="text-slate-400">Transaction ID / Reference:</td>
                        <td class="text-slate-700 font-mono font-medium">{{ $expense->transaction_id ?? 'N/A' }}</td>
                    </tr>
                    <tr class="h-auto min-h-[2.5rem] md:h-10">
                        <td class="text-slate-400">Log Creator:</td>
                        <td class="text-slate-700 font-medium">
                            {{ $expense->creator ? $expense->creator->first_name . ' ' . $expense->creator->last_name : 'System / Auto-Logged' }}
                        </td>
                    </tr>
                </table>
            </div>

            <!-- Payee Details Card -->
            <div class="bg-white border border-slate-200 rounded-xl shadow-sm p-5">
                <h3 class="text-xs font-bold text-slate-800 uppercase tracking-wider mb-4 border-b border-slate-200 pb-2">📋 Recipient / Payee Details</h3>
                <table class="w-full text-sm">
                    <tr class="h-auto min-h-[2.5rem] md:h-10 border-b border-slate-200">
                        <td class="text-slate-400 w-1/3 align-top md:align-middle">Payee Bank Name:</td>
                        <td class="text-slate-700 font-medium">{{ $expense->payee_bank_name ?: 'N/A' }}</td>
                    </tr>
                    <tr class="h-auto min-h-[2.5rem] md:h-10">
                        <td class="text-slate-400">Payee Account No / Sort Code:</td>
                        <td class="text-slate-700 font-mono font-medium">{{ $expense->payee_account_no ?: 'N/A' }}</td>
                    </tr>
                </table>
            </div>

            <!-- Notes Card -->
            <div class="bg-white border border-slate-200 rounded-xl shadow-sm p-5">
                <h3 class="text-xs font-bold text-slate-800 uppercase tracking-wider mb-3 border-b border-slate-200 pb-2">📝 Notes & Details</h3>
                <p class="text-slate-600 text-sm whitespace-pre-wrap leading-relaxed">{{ $expense->notes ?: 'No notes attached to this record.' }}</p>
            </div>
        </div>

        <!-- Receipt preview -->
        <div class="space-y-6">
            @if(!auth()->user()->isAccountant())
            <div class="bg-white border border-slate-200 rounded-xl shadow-sm p-5">
                <h3 class="text-xs font-bold text-slate-800 uppercase tracking-wider mb-4 border-b border-slate-200 pb-2">📎 Attached Receipt</h3>
                
                @if($expense->receipt_path)
                    <div class="space-y-4">
                        @php
                            $ext = strtolower(pathinfo($expense->receipt_path, PATHINFO_EXTENSION));
                        @endphp
                        
                        @if(in_array($ext, ['png', 'jpg', 'jpeg', 'gif', 'webp']))
                            <div class="rounded-xl overflow-hidden border border-slate-850 max-h-96">
                                <img src="{{ url('serve-storage/' . $expense->receipt_path) }}" alt="Receipt" class="w-full h-auto object-contain">
                            </div>
                        @elseif($ext === 'pdf')
                            <div class="rounded-xl overflow-hidden border border-slate-850 h-80">
                                <iframe src="{{ url('serve-storage/' . $expense->receipt_path) }}" class="w-full h-full border-0"></iframe>
                            </div>
                        @else
                            <div class="bg-slate-950/30 p-4 rounded-xl border border-slate-850 flex items-center justify-between text-xs text-slate-450">
                                <span>Unsupported file format ({{ $ext }})</span>
                            </div>
                        @endif

                        <div class="flex flex-col sm:flex-row sm:space-x-2 space-y-2 sm:space-y-0 pt-2">
                            <a href="{{ url('serve-storage/' . $expense->receipt_path) }}" target="_blank"
                               class="flex-1 py-2 px-3 bg-black hover:bg-slate-800 text-white text-center font-medium rounded-xl text-sm border border-slate-200 transition duration-150">
                                👁 View Fullscreen
                            </a>
                            <a href="{{ url('serve-storage/' . $expense->receipt_path) }}" download
                               class="py-2 px-3 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-xl text-sm transition duration-150">
                                ⬇ Download
                            </a>
                        </div>
                    </div>
                @else
                    <div class="py-12 flex flex-col items-center justify-center text-slate-400 text-center text-sm">
                        <span class="text-3xl mb-2">📁</span>
                        <span>No receipt or invoice was attached to this expense.</span>
                    </div>
                @endif
            </div>
            @endif
        </div>
    </div>

    @if(auth()->user()->isAdmin() || auth()->user()->isManager())
    <div class="mt-6 bg-slate-50 border border-slate-200 rounded-xl p-4 flex flex-col md:flex-row md:items-center justify-between gap-4 text-xs text-slate-500 col-span-1 lg:col-span-3">
        <div class="flex items-center gap-2">
            <svg class="w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
            <div>
                <span class="font-bold text-slate-700 uppercase block tracking-wider mb-0.5">System Audit Trail Log</span>
                <span>Created by <strong class="text-slate-600 font-semibold">{{ $expense->creator?->name ?? 'System / Anonymous' }}</strong> on {{ $expense->created_at->format('d M Y \a\t H:i') }}</span>
            </div>
        </div>
        @if($expense->updated_by && $expense->updater)
        <div class="md:text-right border-t md:border-t-0 border-slate-200 pt-2 md:pt-0">
            <span class="block font-medium text-slate-600">Last Modified</span>
            <span>By <strong class="text-slate-600 font-semibold">{{ $expense->updater->name }}</strong> on {{ $expense->updated_at->format('d M Y \a\t H:i') }}</span>
        </div>
        @endif
    </div>
    @endif
</x-app-layout>