<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'DFOOD') }}</title>

    @vite(['resources/css/app.css', 'resources/js/app.js'])

    <script type="text/javascript" src="{{ config('services.midtrans.snap_url') }}"
        data-client-key="{{ config('services.midtrans.client_key') }}"></script>

    @livewireStyles
</head>

<body class="font-sans antialiased">

    {{ $slot }}

    {{-- Alpine.js harus dimuat sebelum Livewire --}}
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>

    {{-- Livewire Scripts harus dimuat setelah Alpine.js --}}
    @livewireScripts

    {{-- Script kustom Anda harus dimuat setelah @livewireScripts --}}
    <script>
        document.addEventListener('livewire:initialized', function() {
            // Livewire Event Listener untuk notifikasi umum
            Livewire.on('notify', (data) => {
                console.log('Notification:', data.message);
            });

            // Livewire Event Listener untuk menampilkan Midtrans Snap Pop-up
            Livewire.on('midtransSnapToken', (event) => {
                const snapToken = event.token;
                console.log('Received Midtrans Snap Token:', snapToken);

                if (typeof Snap !== 'undefined' && snapToken) {
                    try {
                        Snap.pay(snapToken, {
                            onSuccess: function(result) {
                                console.log('Payment success:', result);
                                Livewire.dispatch(
                                    'paymentSuccess'); // Inform Livewire component
                            },
                            onPending: function(result) {
                                console.log('Payment pending:', result);
                                Livewire.dispatch('notify', {
                                    message: 'Pembayaran menunggu konfirmasi Anda.'
                                });
                            },
                            onError: function(result) {
                                console.log('Payment error:', result);
                                let errorMessage = 'Terjadi kesalahan pembayaran.';
                                if (result.status_code === '400') {
                                    errorMessage = 'Permintaan tidak valid. Mohon coba lagi.';
                                } else if (result.status_code === '401') {
                                    errorMessage =
                                        'Autentikasi Midtrans gagal. Hubungi administrator.';
                                }
                                Livewire.dispatch('notify', {
                                    message: errorMessage
                                });
                            },
                            onClose: function() {
                                console.log('Payment closed by user');
                                Livewire.dispatch('notify', {
                                    message: 'Pembayaran dibatalkan oleh pengguna.'
                                });
                            }
                        });
                    } catch (e) {
                        console.error("Error calling Snap.pay:", e);
                        Livewire.dispatch('notify', {
                            message: 'Terjadi kesalahan saat memulai pembayaran.'
                        });
                    }
                } else {
                    console.error(
                        'Midtrans Snap.js not loaded or Snap object is undefined, or snapToken is empty.'
                    );
                    Livewire.dispatch('notify', {
                        message: 'Sistem pembayaran tidak siap. Mohon refresh halaman.'
                    });
                }
            });

            // Livewire Event Listener untuk update URL di browser history
            Livewire.on('updateUrl', (data) => {
                const newUrl = data.url;
                if (window.history.pushState) {
                    window.history.pushState({
                        path: newUrl
                    }, '', newUrl);
                }
            });

            // Livewire hook untuk logging proses (hapus di production jika tidak perlu)
            Livewire.hook('message.processed', (message, component) => {
                if (component.fingerprint.name === 'food-order') {
                    console.log('FoodOrder component updated. Current cart:', component.serverMemo.data
                        .cart);
                }
            });

            // Livewire Event Listener untuk menyembunyikan progress bar navigasi
            Livewire.on('start-navigation', () => {
                const progressBar = document.querySelector('.livewire-progress-bar');
                if (progressBar) {
                    progressBar.style.display = 'none';
                }
            });

            setInterval(() => {
                fetch('/refresh-csrf', {
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        const csrfMeta = document.querySelector('meta[name="csrf-token"]');
                        if (csrfMeta) {
                            csrfMeta.setAttribute('content', data.csrf_token);
                        }

                        // Tidak perlu akses internal Livewire jika ingin aman dari perubahan API internal
                        console.log('CSRF token refreshed:', data.csrf_token);
                    })
                    .catch(error => {
                        console.error('Error refreshing CSRF token:', error);
                    });
            }, 1800000); // 30 menit
        });
    </script>
</body>

</html>
