<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin | @yield('title')</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="{{ asset('quil.css') }}">
    <link rel="stylesheet"
        href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&icon_names=dashboard" />
    <link rel="stylesheet" href="{{ asset('toaster/toaster.min.css') }}">
    <link rel="stylesheet" href="{{ asset('dashboards.css') }}">
    <meta name="asset-url" content="{{ asset('') }}">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    @vite('resources/css/app.css')
    @vite('resources/js/app.js')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

      <style>
        .logout{
    position: absolute;
    
    width: 100%;
     }
    </style>

</head>

<body class="bg-gray-100 h-screen overflow-hidden">
    <div class="flex h-full">

        <div id="overlay" onclick="toggleSidebar()" class="fixed inset-0 bg-black/40 z-40 hidden lg:hidden">
        </div>

        @include('admin.layouts.sidebar')

        <div
            class="flex-1 min-h-0 lg:border bg-[#FFFFFF]
             lg:mt-8 lg:p-0 lg:rounded-[20px]
             border-[#dbd7d7] overflow-y-auto">

            @php
                $headerText = 'Admin Dashboard';
                if (Route::is('user-management')) {
                    $headerText = 'User Management';
                } elseif (Route::is('sessions')) {
                    $headerText = 'Sessions';
                } elseif (Route::is('bookingRequest')) {
                    $headerText = 'Bookings';
                } elseif (Route::is('earningsAndPayout')) {
                    $headerText = 'Earnings & Payouts';
                } elseif (Route::is('supportAndDispute')) {
                    $headerText = 'Support & Dispute';
                } elseif (Route::is('bookingDetail')) {
                    $headerText = 'Booking Details';
                }
            @endphp

            @include('admin.layouts.header', ['headerText' => $headerText])

            <main class="p-4 sm:px-8 w-full">
                @yield('content')
            </main>

        </div>
    </div>
</body>
<script src="{{ asset('jquery/jquery.min.js') }}"></script>
<script src="{{ asset('quil.js') }}"></script>
<script src="{{ asset('toaster/toaster.min.js') }}"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://js.pusher.com/8.4.0/pusher.min.js"></script>

@if (session()->has('success'))
    <script>
        toastr.success('{{ session('success') }}')
    </script>
@endif

@if (session()->has('error'))
    <script>
        toastr.error('{{ session('error') }}')
    </script>
@endif

<script>
    const WS_KEY     = '{{ env("PUSHER_APP_KEY") }}';
  const WS_HOST    = '{{ env("PUSHER_HOST") }}';
  const WS_PORT    = {{ env("PUSHER_PORT") }};
  const WS_SCHEME  = '{{ env("PUSHER_SCHEME") }}';
  const WS_CLUSTER = '{{ env("PUSHER_CLUSTER") }}';
  const FORCE_TLS  = WS_SCHEME === 'wss';

  let pusher;
  let channel;

  function connectWebSocket() {
    if (pusher) pusher.disconnect();

    pusher = new Pusher(WS_KEY, {
        wsHost:            WS_HOST,
        wsPort:            FORCE_TLS ? undefined : WS_PORT,
        wssPort:           FORCE_TLS ? WS_PORT : undefined,
        forceTLS:          FORCE_TLS,
        enabledTransports: FORCE_TLS ? ['wss'] : ['ws'],
        disableStats:      true,
        cluster:           WS_CLUSTER,
    });

    pusher.connection.bind('connected', () => {
        console.log('%c[Pusher] Connected ✅ Socket ID:', 'color: green; font-weight: bold;', pusher.connection.socket_id);
    });

    pusher.connection.bind('disconnected', () => {
        console.warn('%c[Pusher] Disconnected ⚠️', 'color: orange;');
    });

    pusher.connection.bind('error', (err) => {
        console.error('%c[Pusher] Connection error ❌', 'color: red;', err);
    });

    pusher.connection.bind('state_change', (states) => {
        console.log(`%c[Pusher] State: ${states.previous} → ${states.current}`, 'color: #888;');
    });

    channel = pusher.subscribe('my-channel');
    
    // channel = pusher.subscribe('private-user.{{ auth()->id() }}');

    channel.bind('pusher:subscription_succeeded', () => {
        console.log('%c[Pusher] Subscribed to my-channel ✅', 'color: green;');

        // ✅ Bind INSIDE subscription_succeeded so channel is guaranteed ready
        // bind_global first — tells you the EXACT event name Laravel is sending
        channel.bind_global(function(eventName, data) {
            if (eventName.startsWith('pusher:')) return; // ignore internal events
            console.log('%c[Pusher] RAW event received:', 'color: purple; font-weight: bold;', eventName, data);
        });

        // Try both possible event name formats Laravel might use
        const possibleNames = [
            'my-event',
            'App\\Notifications\\my-event',
            'AlertNotification',
            'App\\Notifications\\AlertNotification',
        ];

        possibleNames.forEach(name => {
            channel.bind(name, function(data) {
                console.log(`%c[Pusher] Matched on event name: "${name}"`, 'color: orange; font-weight: bold;', data);
                handleNotification(data);
            });
        });

        console.log('%c[Pusher] All event bindings registered ✅', 'color: green;');
    });

    channel.bind('pusher:subscription_error', (status) => {
        console.error('%c[Pusher] Subscription error ❌', 'color: red;', status);
    });
  }

  function handleNotification(data) {
    console.log('[Pusher] handleNotification called with:', data);

    const payload = data.notification ?? data;
    console.log('[Pusher] Resolved payload:', payload);

    if (!payload || !payload.user_id) {
        console.warn('[Pusher] Missing or invalid payload:', data);
        return;
    }

    const userId = '{{ auth()->id() }}';
    console.log(`[Pusher] user_id check: event=${payload.user_id} auth=${userId}`);

    if (payload.user_id != userId) {
        console.log('[Pusher] user_id mismatch — ignoring.');
        return;
    }

    console.log('[Pusher] User match ✅ — updating UI');

    const counter = document.getElementById('notificationDropdownCount');
    if (counter) {
        counter.textContent = parseInt(counter.textContent || 0) + 1;
    } else {
        console.warn('[Pusher] notificationDropdownCount not found in DOM.');
    }

    const list = document.getElementById('notificationDropdownSection');
    if (!list) {
        console.warn('[Pusher] notificationDropdownSection not found in DOM.');
        return;
    }

    const emptyText = list.querySelector('.text-gray-400');
    if (emptyText) emptyText.remove();

    fetch(`{{url('/render-notification')}}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        body: JSON.stringify(payload)
    })
    .then(res => {
        if (!res.ok) {
            console.error('[Pusher] /render-notification HTTP error:', res.status);
            throw new Error('Bad response');
        }
        return res.text();
    })
    .then(html => {
        if (!html || html.trim() === '') {
            console.warn('[Pusher] /render-notification returned empty HTML.');
            return;
        }
        list.insertAdjacentHTML("afterbegin", html);
        toastr.success('New notification received');
        console.log('[Pusher] Notification inserted into DOM ✅');
    })
    .catch(err => {
        console.error('[Pusher] fetch failed ❌', err);
    });
  }

  connectWebSocket();

    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('overlay');
        sidebar.classList.toggle('-translate-x-full');
        overlay.classList.toggle('hidden');
    }
</script>
<script>
    function toggleAccordion() {
        const body = document.getElementById('accordionBody');
        const icon = document.getElementById('accordionIcon');

        body.classList.toggle('hidden');
        icon.textContent = body.classList.contains('hidden') ? '+' : 'âˆ’';
    }
</script>

<script>
    const quillEditors = [];
    const quill = [];


    document.querySelectorAll('.editor').forEach((editor, index) => {
        const quill = new Quill(editor, {
            theme: 'snow'
        });

        quillEditors.push(quill);

    });
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
</script>
<script>
    document.addEventListener('click', function(e) {

        const btn = e.target.closest('button[command="close"]');
        if (!btn) return;

        const modalId = btn.getAttribute('commandfor');
        const modal = modalId ? document.getElementById(modalId) : btn.closest('dialog');

        if (modal?.open) modal.close();

    });

    // document.addEventListener("DOMContentLoaded", function() {
    //     window.Echo.channel('my-channel')
    //         .listen('.my-event', (data) => {

    //             let userId = '{{ auth()->id() }}';

    //             if (data.user_id == userId) {

    //                 let counter = document.getElementById('notificationDropdownCount');
    //                 if (counter) {
    //                     counter.textContent = parseInt(counter.textContent || 0) + 1;
    //                 }

    //                 let list = document.getElementById('notificationDropdownSection');

    //                 if (list) {

    //                     let emptyText = list.querySelector('.text-gray-400');
    //                     if (emptyText) emptyText.remove();

    //                     // ðŸ”¥ call backend to render Blade
    //                     fetch('/render-notification', {
    //                             method: 'POST',
    //                             headers: {
    //                                 'Content-Type': 'application/json',
    //                                 'X-CSRF-TOKEN': '{{ csrf_token() }}'
    //                             },
    //                             body: JSON.stringify(data)
    //                         })
    //                         .then(res => res.text())
    //                         .then(html => {
    //                             list.insertAdjacentHTML("afterbegin", html);
    //                             toastr.success('New notification received');
    //                         });
    //                 }
    //             }
    //         });
    // });
    
      document.getElementById('refreshNotification').addEventListener('click', function () {

    let btn = this;
    btn.classList.add('animate-spin');

    fetch('{{ url('/get-notification') }}')
        .then(response => response.json())
        .then(data => {

            let list = document.getElementById('notificationDropdownSection');
            

              let counter = document.querySelector('.notificationDropdownCount');
            

            if (list) {
                list.innerHTML = data.html;
                
        counter.innerText = data.count;
    
            }


        })
        .finally(() => {
            setTimeout(() => {
                btn.classList.remove('animate-spin');
            }, 500);
        });

});
    
    $(document).ready(function() {
        $('.select2').select2();

    });
</script>
@stack('script')

</html>
