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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tutor | @yield('title')</title>
    <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="csrf-token" content="{{ csrf_token() }}">
    
    <meta name="asset-url" content="{{ asset('') }}">


    <link rel="stylesheet" href="{{ asset('tutor/Fonts/Inter/Inter-VariableFont_opsz,wght.ttf') }}">
    @vite('resources/css/app.css')
    @vite('resources/js/app.js')

</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('tutor.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 = 'Tutor Dashboard';
                if (Route::is('tutor.my-calender')) {
                    $headerText = 'Schedule';
                } elseif (Route::is('tutor.sessions')) {
                    $headerText = 'Sessions';
                } elseif (Route::is('tutor.bookingRequest')) {
                    $headerText = 'Bookings';
                } elseif (Route::is('tutor.earningsAndPayout')) {
                    $headerText = 'Earnings & Payouts';
                } elseif (Route::is('tutor.supportAndDispute')) {
                    $headerText = 'Support & Dispute';
                } elseif (Route::is('tutor.bookingDetail')) {
                    $headerText = 'Booking Details';
                }
            @endphp

            @include('tutor.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://js.pusher.com/8.4.0/pusher.min.js"></script>
<script src="{{ asset('notification.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(btn) {
    //     const body = btn.closest('.accordionBody');

    //     // const body = document.getElementById('accordionBody');
    //     const icon = btn.closest('.accordionIcon');

    //     // const icon = document.getElementById('accordionIcon');

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

    function toggleAccordion(btn) {
        const wrapper = btn.parentElement;
        const body = wrapper.querySelector('.accordionBody');
        const icon = btn.querySelector('i');

        if (!body) return;

        body.classList.toggle('hidden');

        if (body.classList.contains('hidden')) {
            icon.classList.remove('fa-minus');
            icon.classList.add('fa-plus');
        } else {
            icon.classList.remove('fa-plus');
            icon.classList.add('fa-minus');
        }
    }
</script>

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

    });
</script>
<script>
    //     document.addEventListener("DOMContentLoaded", function () {
    //         console.log(window.Echo)
    //     if (window.Echo) {

    //         window.Echo.channel('my-channel')
    //         .listen('.my-event', (data) => {

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

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

    //                 var counter = document.getElementById('notificationDropdownCount');

    //                 if (counter) {
    //                     counter.textContent = parseInt(counter.textContent || 0) + 1;
    //                 }

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

    //                 if (list) {

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

    //                     if (emptyText && emptyText.textContent.trim() === "No notifications") {
    //                         emptyText.remove();
    //                     }

    //                     list.insertAdjacentHTML("afterbegin", data.html);

    //                     toastr.success('New notification received');
    //                 }
    //             }

    //         });

    //     }

    // });

    // 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');
    //                         });
    //                 }
    //             }
    //         });
    // });

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

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

    //             if (list) {

    //                 let emptyText = list.querySelector('.text-gray-400');
    //                 list.innerHTML = data.html;

    //             }
    //             // Update your UI here
    //             // example:
    //             // document.getElementById('data').innerHTML = ...
    //         });
    // }, 3000); // 3000ms = 3 seconds
    
    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);
        });

});
    function openConfirmModal(id) {

        const modal = document.getElementById(id);
        if (modal) {
            modal.showModal();
            modal.classList.remove('hidden');
        }
    }
</script>
@stack('scripts')

</html>
