@extends('layouts.franchise', ['heading' => 'Notifications'])

@section('content')
    <div class="mb-4 flex items-center justify-between">
        <div class="text-sm text-[var(--user-muted)]">Panel alerts for stock, commission, pickup and requests.</div>
        <button
            type="button"
            data-mark-read
            class="rounded-lg bg-[var(--user-primary)] px-3 py-2 text-xs font-semibold text-white"
        >
            Mark all read
        </button>
    </div>

    <div class="grid grid-cols-1 gap-3">
        @forelse($notifications as $notification)
            <div class="user-card p-4 {{ $notification->read_at ? 'opacity-70' : '' }}">
                <div class="flex items-start justify-between gap-2">
                    <div>
                        <div class="text-sm font-semibold">{{ $notification->title }}</div>
                        <div class="mt-1 text-xs text-[var(--user-muted)]">{{ $notification->message }}</div>
                    </div>
                    @if(! $notification->read_at)
                        <span class="user-badge warning">New</span>
                    @endif
                </div>
                <div class="mt-2 flex items-center justify-between text-xs text-[var(--user-muted)]">
                    <span>{{ optional($notification->created_at)->format('d M Y h:i A') }}</span>
                    @if($notification->link)
                        <a href="{{ $notification->link }}" class="text-[var(--user-primary)]">Open</a>
                    @endif
                </div>
            </div>
        @empty
            <div class="user-card p-8 text-center text-sm text-[var(--user-muted)]">No notifications yet.</div>
        @endforelse
    </div>

    <div class="mt-4">{{ $notifications->links() }}</div>

    <script>
        (() => {
            const button = document.querySelector('[data-mark-read]');
            if (!button) return;

            button.addEventListener('click', async () => {
                const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
                if (!token) return;

                await fetch('{{ route('franchise.notifications.read') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': token,
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                    body: JSON.stringify({}),
                });

                window.location.reload();
            });
        })();
    </script>
@endsection

