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

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Books Pair</title>
    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
        integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-4Q6Gf2aSP4eDXB8Miphtr37CMZZQ5oXLH2yaXMJ2w8e2ZtHTl7GptT4jmndRuHDT" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css"
        integrity="sha512-tS3S5qG0BlhnQROyJXvNjeEM4UpMXHrQfTGmbQ1gKmelCxlSEBUaxhRBj/EFTzpbP4RVSrpEikbmdJobCvhE3g=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css"
        integrity="sha512-OTcub78R3msOCtY3Tc6FzeDJ8N9qvQn1Ph49ou13xgA9VsH9+LRxoFU6EqLhW4+PKRfU+/HReXmSZXHEkpYoOA=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="icon" href="{{ asset('website/images/Group 427319199.svg') }}" type="image/svg+xml">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">

    <link rel="stylesheet" href="{{ asset('website/css/style.css') }}" />

</head>

<!-- Registration Modal -->
<div class="modal fade" id="registerModal" tabindex="-1" aria-labelledby="registerLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body">
                <div class="login_background py-3">
                    <!-- Toast container -->
                    <div id="toast-container" style="position: absolute; top: 20px; right: 20px; z-index: 9999"></div>

                    <div class="top-title">
                        <h2 class="mb-4">Create Account</h2>
                    </div>

                    <form id="registerForm" method="POST" action="{{ route('register.store') }}" novalidate>
                        @csrf
                        <div class="row d-flex justify-content-center align-items-center">
                            <!-- Email Field -->
                            <div class="mb-lg-4 mb-3 col-xl-11 col-lg-11 col-md-12 col-12">
                                <label for="email" class="label-text mb-1">Email</label>
                                <input type="text" name="email" id="email"
                                    class="form-control @error('email') is-invalid @enderror"
                                    placeholder="Enter your email" value="{{ old('email') }}">
                                @error('email')
                                    <small class="text-danger">{{ $message }}</small>
                                @enderror
                            </div>

                            <!-- Password Field -->
                            <div class="mb-lg-4 mb-1 col-xl-11 col-lg-11 col-md-12 col-12">
                                <div class="password-container position-relative">
                                    <label for="password" class="label-text mb-1">Password</label>
                                    <img src="{{ asset('website/images/lock.svg') }}" alt="" />
                                    <div class="divider">|</div>
                                    <input type="password" name="password" id="password"
                                        class="form-control ps-5 @error('password') is-invalid @enderror"
                                        placeholder="Password">
                                    <i class="fa-regular fa-eye-slash toggle-password" data-target="password"></i>
                                    @error('password')
                                        <small class="text-danger">{{ $message }}</small>
                                    @enderror
                                </div>
                            </div>

                            <!-- Confirm Password Field -->
                            <div class="mb-lg-2 mb-1 col-xl-11 col-lg-11 col-md-12 col-12">
                                <div class="password-container position-relative">
                                    <label for="confirmpassword" class="label-text mb-1">Confirm Password</label>
                                    <img src="{{ asset('website/images/lock.svg') }}" alt="" />
                                    <div class="divider">|</div>
                                    <input type="password" name="confirmpassword" id="confirmpassword"
                                        class="form-control ps-5 @error('confirmpassword') is-invalid @enderror"
                                        placeholder="Confirm Password">
                                    <i class="fa-regular fa-eye-slash toggle-password"
                                        data-target="confirmpassword"></i>
                                    @error('confirmpassword')
                                        <small class="text-danger">{{ $message }}</small>
                                    @enderror
                                </div>
                            </div>

                            <!-- Terms Checkbox -->
                            <div class="col-xl-11 col-lg-11 col-md-12 col-12 mx-auto pb-lg-1">
                                <div class="form-check d-flex gap-2 justify-content-start align-items-center">
                                    <input class="form-check-input @error('terms') is-invalid @enderror" type="checkbox"
                                        name="terms" id="termsCheckbox" {{ old('terms') ? 'checked' : '' }}>
                                    <label class="form-check-label" for="termsCheckbox">
                                        I agree to the <a href="{{ route('website.termandcondition') }}">Terms &
                                            Conditions</a>
                                    </label>
                                    @error('terms')
                                        <small class="text-danger d-block">{{ $message }}</small>
                                    @enderror
                                </div>
                            </div>

                            <!-- Submit Button -->
                            <div class="col-xl-11 col-lg-11 col-md-12 col-12 mx-auto my-4">
                                <div class="login_btn">
                                    <button type="submit" class="btn btn-primary w-100">Agree & Create
                                        Account</button>
                                </div>
                            </div>

                            <!-- Login Link -->
                            <div class="mb-lg-2 col-xl-10 col-lg-11 col-md-12 col-12 mx-auto">
                                <div class="login_up text-center">
                                    <span>Have an Account ? Login
                                        <a class="text-decoration-none" href="#" data-bs-toggle="modal"
                                            data-bs-target="#signUpModal">
                                            here!
                                        </a></span>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- LogIN Modal -->
<div class="modal fade" id="signUpModal" tabindex="-1" aria-labelledby="signUpLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body">
                <div class="login_background py-3">
                    <div class="top-title">
                        <h2 class="mb-4">Login to Books Pair</h2>
                    </div>

                    <!-- Toast container (add this at the top of your modal) -->
                    <div id="toast-container" style="position: absolute; top: 20px; right: 20px; z-index: 9999"></div>

                    <form id="loginForm" method="POST" action="{{ route('login.submit') }}">
                        @csrf
                        <div class="row d-flex justify-content-center align-items-center">
                            <!-- Email -->
                            <div class="mb-lg-4 mb-3 col-xl-11">
                                <label for="email" class="label-text mb-1">Email</label>
                                <input type="text" name="email" id="emails" class="form-control"
                                    placeholder="Enter your email" value="{{ old('email') }}">
                                @error('email')
                                    <small class="text-danger">{{ $message }}</small>
                                @enderror
                            </div>

                            <!-- Password -->
                            <div class="mb-lg-2 mb-1 col-xl-11">
                                <div class="password-container position-relative">
                                    <label for="password" class="label-text mb-1">Password</label>
                                    <img src="{{ asset('website/images/lock.svg') }}" alt="">
                                    <div class="divider">|</div>
                                    <input type="password" name="password" id="passwordd" class="form-control ps-5"
                                        placeholder="Password">
                                    <i class="fa-regular fa-eye-slash toggle-password" data-target="passwordd"></i>
                                    @error('password')
                                        <small class="text-danger">{{ $message }}</small>
                                    @enderror
                                </div>
                            </div>

                            <!-- Forgot password -->
                            <div class="col-xl-11 mx-auto pb-lg-1">
                                <div class="forget_btn text-start">
                                    <a style="cursor: pointer;" data-bs-toggle="modal"
                                        data-bs-target="#forgotPasswordModal" class="forget">Forgot Password ?</a>
                                </div>
                            </div>

                            <!-- Login Button -->
                            <div class="col-xl-11 mx-auto my-4">
                                <div class="login_btn">
                                    <button type="submit" class="btn btn-primary w-100">Login</button>
                                </div>
                            </div>

                            <!-- Register Link -->
                            <div class="mb-lg-2 col-xl-10 mx-auto">
                                <div class="login_up text-center">
                                    <span>Don't have any account? Create Account
                                        <a class="text-decoration-none" href="#" data-bs-toggle="modal"
                                            data-bs-target="#registerModal">here!</a>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!--Forget Email-->
<!-- Forgot Password Modal -->
<div class="modal fade" id="forgotPasswordModal" tabindex="-1" aria-labelledby="forgotLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body">
                <h5 class="mb-3">Forgot Your Password?</h5>

                <form method="POST" id="forgotPasswordForm" action="{{ route('password.email') }}">
                    @csrf
                    <div class="mb-3">
                        <label for="forgot_email">Email</label>
                        <input type="email" class="form-control" name="email" id="forgot_email" required>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Send Reset Link</button>
                </form>
                <div id="forgot-message" class="mt-2 text-success" style="display:none;"></div>
            </div>
        </div>
    </div>
</div>

<!-- Reset Password Modal -->
{{-- <div class="modal fade" id="resetPasswordModal" tabindex="-1" aria-labelledby="resetLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-body">
                <h5 class="mb-3">Reset Your Password</h5>

                <form method="POST" action="{{ route('password.update') }}">
                    @csrf
                    <input type="hidden" name="token" value="{{ request()->route('token') }}">
                    <input type="hidden" name="email" value="{{ request('email') }}">

                    <div class="mb-3">
                        <label>New Password</label>
                        <input type="password" class="form-control" name="password" required>
                    </div>
                    <div class="mb-3">
                        <label>Confirm Password</label>
                        <input type="password" class="form-control" name="password_confirmation" required>
                    </div>
                    <button type="submit" class="btn btn-success w-100">Reset Password</button>
                </form>

            </div>
        </div>
    </div>
</div> --}}



<body>
    @include('website.layouts.header')

    @yield('content')

    @include('website.layouts.footer')




    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
        integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"
        integrity="sha512-bPs7Ae6pVvhOSiIcyUClR7/q2OAsRiovw4vAkX+zJbw3ShAeeqezq50RIIcIURq7Oa20rW2n2q+fyXBNcU9lrw=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.6/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-j1CDi7MgGQ12Z7Qab0qlWQ/Qqz24Gc6BM0thvEMVjHnfYGF0rmFCozFSxQBxwHKO" crossorigin="anonymous">
    </script>
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>

    <script>
        $(document).ready(function() {
            if (window.location.hash === "#chats") {
                $('#v-pills-6-tab').click(); // activate tab

                // Remove the hash from the URL without reloading
                history.replaceState(null, null, window.location.pathname);
            }
        });
    </script>

    <script>
        $(document).on('submit', '#profilform', function(e) {
            e.preventDefault();
            let form = $(this);
            let formData = new FormData(this);
            let submitBtn = form.find('button[type="submit"]');

            // Disable submit button to prevent multiple submissions
            submitBtn.prop('disabled', true).text('Processing...');

            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        showToast(response.message, 'success');
                        // Optional: Reset form or redirect
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    }
                },
                error: function(xhr) {
                    submitBtn.prop('disabled', false).text('Submit');

                    if (xhr.status === 422) {
                        // Validation errors
                        let errors = xhr.responseJSON.errors;

                        // Show all error messages
                        Object.keys(errors).forEach(field => {
                            errors[field].forEach(message => {
                                showToast(message, 'error');
                            });
                        });

                        // Highlight problematic fields
                        Object.keys(errors).forEach(field => {
                            $(`[name="${field}"]`).addClass('is-invalid');
                            $(`[name="${field}"]`).next('.invalid-feedback').remove();
                            $(`[name="${field}"]`).after(
                                `<div class="invalid-feedback">${errors[field][0]}</div>`);
                        });
                    } else if (xhr.status === 401) {
                        showToast('You must be logged in.', 'error');
                    } else {
                        showToast('An error occurred. Please try again.', 'error');
                    }
                }
            });
        });

        function showToast(message, type = 'success') {
            Toastify({
                text: message,
                duration: 5000, // Longer duration for error messages
                gravity: "top",
                position: "right",
                backgroundColor: type === 'error' ? "#dc3545" : "#28a745",
                stopOnFocus: true
            }).showToast();
        }
    </script>


    {{-- <script>
    const isActive = @json($isActive);

    document.querySelectorAll('.conversation-item').forEach(item => {
        item.addEventListener('click', function () {
            const userId = this.getAttribute('data-user-id');

            if (!isActive) {
                fetch(`/preview-message/${userId}`, {
                    method: 'GET',
                    credentials: 'same-origin',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                .then(res => {
                    if (!res.ok) throw new Error('Network response was not ok');
                    return res.json();
                })
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                        return;
                    }

                    const modalBody = document.getElementById('modalMessageContent');
                    modalBody.innerHTML = `
                        <div class="row">
                            <div class="col-md-4">
                                <img src="${data.book_cover}" class="img-fluid rounded" alt="Book Cover">
                            </div>
                            <div class="col-md-8">
                                <p><strong>Real Name:</strong> ${data.real_name}</p>
                                <p><strong>Nickname:</strong> ${data.nickname}</p>
                                <p><strong>Book Name:</strong> ${data.book_name}</p>
                                <p><strong>Profile Likes:</strong> ${data.profile_likes}</p>
                                <p><strong>Book Likes:</strong> ${data.book_likes}</p>
                                <p><strong>Last Message:</strong> ${data.last_message}</p>
                            </div>
                        </div>
                    `;

                    new bootstrap.Modal(document.getElementById('messagePreviewModal')).show();
                })
                .catch(error => {
                    console.error('Preview fetch failed:', error);
                    alert('Could not load message preview.');
                });

            } else {
                // If user is active, show chat box
                document.getElementById('chat-container').style.display = 'block';
            }
        });
    });
</script> --}}

    <script></script>

    <script>
        $(document).ready(function() {
            // Handle all start trial forms by ID prefix
            $(document).on('submit', 'form[id^="start-trial-formd-"]', function(e) {
                e.preventDefault();

                const form = $(this);
                const button = form.find('button[type="submit"]');
                const coverId = form.attr('id').split('start-trial-formd-')[1]; // Extract ID
                const currentModalId = '#bookModal8' + coverId;
                const nextModalId = '#bookModal9' + coverId;
                const expiryTextContainer = $(nextModalId + ' .content_book');

                let trialStarted = false; // global variable
                $.ajax({
                    url: "{{ route('start.trial') }}",
                    type: "POST",
                    data: form.serialize(),
                    beforeSend: function() {
                        button.prop('disabled', true).text('Please wait...');
                    },
                    success: function(response) {
                        showToast(response.message, 'success');
                        //button.prop('disabled', false).text('Start Trial');
                        trialStarted = true;

                        const startFormatted = formatDate(response.start);
                        const expiryFormatted = formatDate(response.expiry);
                        expiryTextContainer.html(`
                            <p>Your trial started on: <strong>${startFormatted}</strong></p>
                            <p>Your trial expires on: <strong>${expiryFormatted}</strong></p>
                        `);

                        const currentModal = bootstrap.Modal.getInstance(document.querySelector(
                            currentModalId));
                        currentModal.hide();

                        const nextModal = new bootstrap.Modal(document.querySelector(
                            nextModalId));
                        nextModal.show();

                        // ✅ Enable chat inputs after subscription activated
                        $('.chat-input').each(function() {
                            const isSelf = $(this).attr('data-receiver') ==
                                "{{ auth()->id() }}";
                            if (!isSelf) {
                                $(this).prop('disabled', false).attr('placeholder',
                                    'Type your message...');
                            }
                        });

                        $('.send-bttn').each(function() {
                            const isSelf = $(this).attr('data-receiver') ==
                                "{{ auth()->id() }}";
                            if (!isSelf) {
                                $(this).prop('disabled', false);
                            }
                        });
                    },
                    error: function(xhr) {
                        const errorMsg = xhr.responseJSON?.message || 'An error occurred.';
                        showToast(errorMsg, 'error');
                        button.prop('disabled', false).text('Start Trial');
                    }
                });


            });

            // Toast function
            function showToast(message, type = 'success') {
                Toastify({
                    text: message,
                    duration: 3000,
                    close: true,
                    gravity: "top",
                    position: "right",
                    backgroundColor: type === 'error' ? "#dc3545" : "#28a745",
                    stopOnFocus: true
                }).showToast();
            }

            // Format Y-m-d to "Month Day, Year"
            function formatDate(dateStr) {
                const options = {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                };
                return new Date(dateStr).toLocaleDateString('en-US', options);
            }
        });
    </script>




    <script>
        function showToast(message, type = 'success') {
            Toastify({
                text: message,
                duration: 3000,
                close: true,
                gravity: "top",
                position: "right",
                backgroundColor: type === 'success' ? "#28a745" : "#dc3545",
                stopOnFocus: true
            }).showToast();
        }
    </script>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            @if (session('success'))
                showToast("{{ session('success') }}", 'success');
            @endif

            @if (session('error'))
                showToast("{{ session('error') }}", 'error');
            @endif
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const fields = [{
                    textareaId: 'short_description',
                    counterId: 'shortDescriptionCount'
                },
                {
                    textareaId: 'favorite_quotes',
                    counterId: 'favoriteQuotesCount'
                }
            ];

            fields.forEach(({
                textareaId,
                counterId
            }) => {
                const textarea = document.getElementById(textareaId);
                const counter = document.getElementById(counterId);

                function updateCount() {
                    counter.textContent = `${textarea.value.length} / 100`;
                }

                if (textarea && counter) {
                    textarea.addEventListener('input', updateCount);
                    updateCount(); // initial count
                }
            });
        });
    </script>


    <script>
        $(document).ready(function() {
            let currentChatUserId = null;
            let lastMessageTime = null;

            // Search conversations
            $('.search-box input').on('keyup', function() {
                const searchTerm = $(this).val().toLowerCase();
                $('.conversation-item').each(function() {
                    const text = $(this).text().toLowerCase();
                    $(this).toggle(text.includes(searchTerm));
                });
            });

            // Open conversation
            $('.conversation-item').click(function() {
                currentChatUserId = $(this).data('user-id');
                const userName = $(this).find('h6').text();

                // Update UI
                $('#chat-user-name').text('Chat with ' + userName);
                $('#chat-container').show();
                $('.conversation-item').removeClass('active');
                $(this).addClass('active');

                // Load messages
                loadMessages(currentChatUserId);
            });

            // Close chat
            $('#close-chat').click(function() {
                $('#chat-container').hide();
                $('.conversation-item').removeClass('active');
                currentChatUserId = null;
            });

            // Send message
            $('.send-btn').click(function() {
                if (!currentChatUserId) return;

                const message = $('.chat-input').val().trim();
                if (!message) return;

                $.post("/chat/send", {
                        _token: "{{ csrf_token() }}",
                        receiver_id: currentChatUserId,
                        message: message
                    })
                    .done(function() {
                        $('.chat-input').val('');
                        loadMessages(currentChatUserId);
                    })
                    .fail(function() {
                        showToast('Failed to send message');
                    });
            });

            // Load messages for a specific user
            function loadMessages(userId) {
                $.get(`/chat/messages/${userId}`)
                    .done(function(data) {
                        const chatBox = $('#chat-box');
                        chatBox.empty();

                        // Track the newest message time
                        let newestTime = null;

                        data.forEach(msg => {
                            const isMine = msg.sender_id == {{ auth()->id() }};
                            const senderName = isMine ? 'You' : (msg.sender.profile?.nickname || msg
                                .sender.name || 'User');

                            const alignClass = isMine ? 'text-end text-success' :
                                'text-start text-primary';
                            const messageTime = new Date(msg.created_at);

                            // Highlight new messages (received in last 5 minutes)
                            const isNew = !isMine && messageTime > new Date(Date.now() - 5 * 60 * 1000);
                            const highlightClass = isNew ? 'bg-light-yellow' : '';

                            chatBox.append(
                                `<div class="${alignClass} mb-2 ${highlightClass} p-2 rounded">
                        <strong>${senderName}:</strong> ${msg.message}
                        <br>
                        <small class="text-muted">${messageTime.toLocaleTimeString()}</small>
                    </div>`
                            );

                            // Track the newest message
                            if (!newestTime || messageTime > newestTime) {
                                newestTime = messageTime;
                            }
                        });

                        // Store the newest message time
                        lastMessageTime = newestTime;

                        chatBox.scrollTop(chatBox.prop("scrollHeight"));
                    })
                    .fail(function() {
                        showToast('Failed to load messages');
                    });
            }

            // Auto-refresh conversations every 10 seconds
            setInterval(function() {
                if (currentChatUserId) {
                    loadMessages(currentChatUserId);
                }

                // Refresh conversation list periodically
                refreshConversationList();
            }, 10000);

            // Refresh conversation list
            function refreshConversationList() {
                $.get("/chat/conversations")
                    .done(function(data) {
                        // You would need to implement this endpoint
                        // to return updated conversation list HTML
                    })
                    .fail(function() {
                        console.log('Failed to refresh conversations');
                    });
            }

            // Enter key to send message
            $('.chat-input').keypress(function(e) {
                if (e.which == 13) {
                    $('.send-btn').click();
                }
            });
        });
    </script>


    <script>
        // Toast function
        function showToast(message, type = 'success') {
            Toastify({
                text: message,
                duration: 3000,
                close: true,
                gravity: "top",
                position: "right",
                backgroundColor: type === 'success' ? "#28a745" : "#dc3545",
                stopOnFocus: true
            }).showToast();
        }

        // Handle form submission with AJAX
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const form = e.target;
            const formData = new FormData(form);

            fetch(form.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => Promise.reject(err));
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showToast(data.message, 'success');
                        // Redirect after a short delay
                        setTimeout(() => {
                            window.location.href = data.redirect || '/profile';
                        }, 1500);
                    }
                })
                .catch(error => {
                    if (error.message) {
                        showToast(error.message, 'error');
                    } else {
                        showToast('An error occurred. Please try again.', 'error');
                    }
                });
        });

        // Display server-side flash messages (for non-AJAX submissions)
        @if (session('toast'))
            document.addEventListener('DOMContentLoaded', function() {
                showToast("{{ session('toast.message') }}", "{{ session('toast.type') }}");
            });
        @endif

        //Registration

        // Toast notification function
        function showToast(message, type = 'success') {
            Toastify({
                text: message,
                duration: 5000,
                close: true,
                gravity: "top",
                position: "right",
                backgroundColor: type === 'success' ? "#28a745" : "#dc3545",
                stopOnFocus: true
            }).showToast();
        }

        // Handle form submission with AJAX
        document.getElementById('registerForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const form = e.target;
            const formData = new FormData(form);

            fetch(form.action, {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(err => Promise.reject(err));
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showToast(data.message, 'success');
                        // Close modal after 2 seconds
                        setTimeout(() => {
                            var modal = bootstrap.Modal.getInstance(document.getElementById(
                                'registerModal'));
                            modal.hide();
                            // Optionally redirect or show login modal
                            // document.getElementById('signUpModal').modal('show');
                        }, 2000);
                    }
                })
                .catch(error => {
                    if (error.errors) {
                        // Handle validation errors
                        Object.values(error.errors).forEach(messages => {
                            messages.forEach(message => {
                                showToast(message, 'error');
                            });
                        });
                    } else if (error.message) {
                        showToast(error.message, 'error');
                    } else {
                        showToast('An error occurred. Please try again.', 'error');
                    }
                });
        });

        // Display server-side flash messages (for non-AJAX submissions)
        @if (session('toast'))
            document.addEventListener('DOMContentLoaded', function() {
                showToast("{{ session('toast.message') }}", "{{ session('toast.type') }}");
            });
        @endif
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const contactForm = document.getElementById('contactForm');
            const submitBtn = document.getElementById('submitBtn');

            if (contactForm) {
                contactForm.addEventListener('submit', function(e) {
                    e.preventDefault();

                    const formData = new FormData(contactForm);

                    submitBtn.disabled = true;
                    submitBtn.innerHTML = 'Submitting...';

                    fetch(contactForm.action, {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'Accept': 'application/json',
                                'X-Requested-With': 'XMLHttpRequest'
                            }
                        })
                        .then(response => {
                            if (!response.ok) {
                                return response.json().then(err => Promise.reject(err));
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.success) {
                                showToast(data.message, 'success');
                                contactForm.reset();
                            }
                        })
                        .catch(error => {
                            if (error.errors) {
                                Object.values(error.errors).forEach(messages => {
                                    messages.forEach(message => {
                                        showToast(message, 'error');
                                    });
                                });
                            } else {
                                showToast('An error occurred. Please try again.', 'error');
                            }
                        })
                        .finally(() => {
                            submitBtn.disabled = false;
                            submitBtn.innerHTML = 'Submit';
                        });
                });
            }

            // Flash message toast
            @if (session('toast'))
                showToast("{{ session('toast.message') }}", "{{ session('toast.type') }}");
            @endif
        });
    </script>


    <script>
        // Toast notification function
        function showToast(message, type = 'error') {
            Toastify({
                text: message,
                duration: 3000,
                close: true,
                gravity: "top",
                position: "right",
                backgroundColor: type === 'error' ? "#dc3545" : "#28a745",
                stopOnFocus: true
            }).showToast();
        }

        // Authentication check
        function isAuthenticated() {
            return {!! auth()->check() ? 'true' : 'false' !!};
        }

        // Load messages function
        // Load messages function
        function loadMessages(receiverId) {
            if (!isAuthenticated()) return;

            $.get(`/chat/messages/${receiverId}`)

                .done(function(data) {
                    const chatBox = $(`#chat-box-${receiverId}`);
                    chatBox.empty();

                    data.forEach(msg => {
                        const isMine = msg.sender_id == {{ auth()->id() }};
                        const senderName = isMine ? 'You' : (msg.sender?.profile?.nickname || 'Unknown');

                        const alignClass = isMine ? 'text-end text-success' : 'text-start text-primary';

                        chatBox.append(
                            `<div class="${alignClass}"><strong>${senderName}:</strong> ${msg.message}</div>`
                        );
                    });

                    chatBox.scrollTop(chatBox.prop("scrollHeight"));
                })
                .fail(function() {
                    showToast('Failed to load messages. Please try again.');
                });
        }

        // Send message handler
        $(document).on('click', '.send-bttn', function() {
            const btn = $(this);
            const receiverId = btn.data('receiver');

            if (!isAuthenticated()) {
                showToast('Please login to send messages');
                return;
            }

            const input = $(`.chat-input[data-receiver="${receiverId}"]`);
            const message = input.val().trim();

            if (!message) {
                showToast('Message cannot be empty');
                return;
            }

            $.post("/chat/send", {
                    _token: "{{ csrf_token() }}",
                    receiver_id: receiverId,
                    message: message
                })
                .done(function(response) {
                    if (response.success) {
                        $('.chat-input').val('');
                        loadMessages(receiverId);
                    } else {
                        showToast('Failed to send message');
                    }
                })
                .fail(function() {
                    showToast('Failed to send message. Please try again.');
                });
        });

        // Auto-refresh if authenticated
        if (isAuthenticated()) {
            // Load initial messages
            $('.chat-box').each(function() {
                const receiverId = $(this).attr('id').split('-')[2];
                loadMessages(receiverId);
            });

            // Set up periodic refresh
            setInterval(function() {
                $('.chat-box').each(function() {
                    const receiverId = $(this).attr('id').split('-')[2];
                    loadMessages(receiverId);
                });
            }, 5000);
        }
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('updatePasswordForm');
            if (!form) return; // Exit if form is not found

            form.addEventListener('submit', function(e) {
                e.preventDefault();

                const formData = new FormData(form);
                const submitBtn = form.querySelector('button[type="submit"]');

                // Disable button during submission
                submitBtn.disabled = true;
                submitBtn.innerHTML = 'Updating...';

                fetch(form.action, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(err => Promise.reject(err));
                        }
                        return response.json();
                    })
                    .then(data => {
                        if (data.success) {
                            showToast(data.message, 'success');
                            form.reset();
                        }
                    })
                    .catch(error => {
                        if (error.errors) {
                            // Handle validation errors
                            Object.values(error.errors).forEach(messages => {
                                messages.forEach(message => {
                                    showToast(message, 'error');
                                });
                            });
                        } else if (error.message) {
                            showToast(error.message, 'error');
                        }
                    })
                    .finally(() => {
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = 'Update Password';
                    });
            });

            // Display server-side flash messages
            @if (session('toast'))
                showToast("{{ session('toast.message') }}", "{{ session('toast.type') }}");
            @endif
        });
    </script>



    {{-- <script>
        // Initialize variables from server-side
        const AUTH_ID = {{ auth()->check() ? auth()->id() : 'null' }};
        const CSRF_TOKEN = "{{ csrf_token() }}";

        // Load messages for a specific receiver
        function loadMessages(receiverId) {
            if (!AUTH_ID) return; // Don't load if not authenticated

            $.get(`/chat/messages/${receiverId}`, function(data) {
                const chatBox = $(`#chat-box-${receiverId}`);
                chatBox.empty();

                data.forEach(msg => {
                    const senderName = msg.sender_id == AUTH_ID ? 'You' : 'User';
                    chatBox.append(`<div><strong>${senderName}:</strong> ${msg.message}</div>`);
                });
                chatBox.scrollTop(chatBox.prop("scrollHeight"));
            }).fail(function() {
                console.error('Failed to load messages');
            });
        }

        // Send message handler
        $(document).on('click', '.send-btn', function() {
            const receiverId = $(this).data('receiver');
            const isAuthenticated = $(this).data('authenticated') === 'true';

            if (!isAuthenticated) {
                alert('Please login to send messages');
                return;
            }

            const input = $(`.chat-input[data-receiver="${receiverId}"]`);
            const message = input.val().trim();

            if (!message) return;

            $.post("/chat/send", {
                _token: CSRF_TOKEN,
                receiver_id: receiverId,
                message: message
            }, function() {
                input.val('');
                loadMessages(receiverId);
            }).fail(function() {
                alert('Failed to send message. Please try again.');
            });
        });

        // Auto-refresh messages if authenticated
        if (AUTH_ID) {
            // Load initial messages
            $('.chat-box').each(function() {
                const receiverId = $(this).attr('id').split('-')[2];
                loadMessages(receiverId);
            });

            // Set up periodic refresh
            setInterval(function() {
                $('.chat-box').each(function() {
                    const receiverId = $(this).attr('id').split('-')[2];
                    loadMessages(receiverId);
                });
            }, 5000);
        }
    </script> --}}

    <script>
        // Like button handler
        $(document).on('click', '.like-btn', function() {
            const profileId = $(this).data('id');
            const type = $(this).data('type');
            const button = $(this);

            $.ajax({
                url: "{{ route('like.profile') }}",
                method: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    profile_id: profileId,
                    type: type
                },
                success: function(response) {
                    let countSelector = `#like-count-${response.type}-${response.id}`;
                    let buttonSelector =
                        `.like-btn[data-id="${response.id}"][data-type="${response.type}"]`;

                    if (response.status === 'liked' || response.status === 'already_liked') {
                        $(countSelector).text(response.likes ?? ''); // Update count if available

                        // Hide the like button
                        if (response.hide) {
                            $(buttonSelector).hide();
                        }

                        // Show message
                        let toastType = response.status === 'liked' ? 'success' : 'info';
                        showToast(response.message, toastType);
                    }
                },

                error: function(xhr) {
                    if (xhr.status === 401) {
                        showToast('Please login to like', 'error');
                    } else {
                        showToast('An error occurred. Please try again.', 'error');
                    }
                }
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            // Main Page Filter
            $('#CountryMain').on('change', function() {
                var selectedCountry = $(this).val();

                $('#list-book .item').each(function() {
                    var country = $(this).data('country');
                    if (selectedCountry === '' || country === selectedCountry) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });

                $('#list-book').trigger('refresh.owl.carousel');
            });

            // Modal Filter
            $('#CountryModal').on('change', function() {
                var selectedCountry = $(this).val();

                $('#book-search .item').each(function() {
                    var country = $(this).data('country');
                    if (selectedCountry === '' || country === selectedCountry) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });

                $('#book-search').trigger('refresh.owl.carousel');
            });
        });
    </script>

    {{-- <script>
    document.getElementById('Country').addEventListener('change', function () {
        let selected = this.value;
        let items = document.querySelectorAll('#list-book .item');

        items.forEach(function (item) {
            if (selected === '' || item.getAttribute('data-country') === selected) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    });
</script> --}}

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            tooltipTriggerList.forEach(function(tooltipTriggerEl) {
                new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const logoutBtn = document.getElementById('confirmLogoutBtn');
            if (logoutBtn) {
                logoutBtn.addEventListener('click', function() {
                    window.location.href = "/logout";
                });
            }
        });
    </script>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const toggleIcons = document.querySelectorAll('.toggle-password');

            toggleIcons.forEach(icon => {
                icon.addEventListener('click', function() {
                    const targetId = this.getAttribute('data-target');
                    const input = document.getElementById(targetId);

                    if (input.type === 'password') {
                        input.type = 'text';
                        this.classList.remove('fa-eye-slash');
                        this.classList.add('fa-eye');
                    } else {
                        input.type = 'password';
                        this.classList.remove('fa-eye');
                        this.classList.add('fa-eye-slash');
                    }
                });
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            // console.log("jQuery is working!");
            const $profileInput = $('#profile_photo');
            const defaultImg = '{{ asset('website/images/big-dp.png') }}';
            const $previewImg = $('#profile_preview');

            // Open file dialog on click
            $('.trigger-upload').on('click', function() {
                $profileInput.click();
            });

            // Live preview on image select
            $profileInput.on('change', function() {
                const file = this.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $previewImg.attr('src', e.target.result);
                    };
                    reader.readAsDataURL(file);
                }
            });

            // Handle delete
            $('.delete-photo').on('click', function() {
                if (!confirm('Are you sure you want to delete your profile photo?')) return;

                $.ajax({
                    url: "{{ route('delete.profile.photo') }}", // define this route in web.php
                    type: "POST",
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.success) {
                            $profileInput.val('');
                            $previewImg.attr('src', defaultImg);
                        } else {
                            alert('Failed to delete image. Try again.');
                        }
                    },
                    error: function() {
                        alert('Server error occurred.');
                    }
                });
            });
        });
    </script>
    <script>
        $(document).ready(function() {
            const bookCoverInput = $('#book_cover_input');
            const bookCoverPreview = $('#book_cover_preview');

            // Trigger input when clicking on the area
            $('#dropArea').on('click', function() {
                bookCoverInput.click();
            });

            // Show preview when a file is selected
            bookCoverInput.on('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        bookCoverPreview.attr('src', e.target.result);
                    };
                    reader.readAsDataURL(file);
                }
            });
        });
    </script>

    <script>
        $(document).ready(function() {
            $("#list-book").owlCarousel({
                loop: false,
                margin: 50,
                nav: true,
                responsive: {
                    0: {
                        items: 1,
                    },
                    600: {
                        items: 3,
                    },
                    1000: {
                        items: 4,
                    },
                },
            });
        });
        $(document).ready(function() {
            $("#book-search").owlCarousel({
                loop: false,
                margin: 30,
                nav: true,
                navText: [
                    // Left Arrow
                    `<button class="owl-prev">
         <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" width="30" height="30" viewBox="0 0 512 512">
          <path d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l128 128c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 288H480c17.7 0 32-14.3 32-32s-14.3-32-32-32H109.3l73.4-73.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L9.4 233.4z"/>
        </svg>
      </button>`,

                    // Right Arrow (flipped path)
                    `<button class="owl-next">
        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" width="30" height="30" viewBox="0 0 512 512">
          <path d="M502.6 278.6c12.5-12.5 12.5-32.8 0-45.3l-128-128c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L402.7 224H32c-17.7 0-32 14.3-32 32s14.3 32 32 32h370.7l-73.4 73.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l128-128z"/>
        </svg>

      </button>`,
                ],
                responsive: {
                    0: {
                        items: 1
                    },
                    600: {
                        items: 3
                    },
                    1000: {
                        items: 4
                    },
                },
            });
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const countrySelect = document.getElementById("CountryMain");
            const owl = $('#list-book');
            const allItems = $('#list-book .item').clone(); // backup of all items
            const noBooksMessage = document.getElementById("no-books-message");

            function refreshOwl(itemsToShow) {
                owl.trigger('destroy.owl.carousel');
                owl.html('');
                if (itemsToShow.length > 0) {
                    noBooksMessage.style.display = 'none';
                    owl.append(itemsToShow);
                    owl.owlCarousel({
                        loop: false,
                        margin: 15,
                        nav: true,
                        dots: false,
                        responsive: {
                            0: {
                                items: 1
                            },
                            600: {
                                items: 2
                            },
                            1000: {
                                items: 4
                            }
                        }
                    });
                } else {
                    noBooksMessage.style.display = 'block';
                }
            }

            countrySelect.addEventListener("change", function() {
                const selectedCountry = this.value;

                if (selectedCountry === "") {
                    refreshOwl(allItems.clone());
                } else {
                    let filteredItems = [];
                    allItems.each(function() {
                        if ($(this).data('country') === selectedCountry) {
                            filteredItems.push($(this).clone());
                        }
                    });

                    refreshOwl(filteredItems);
                }
            });
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const modalCountrySelect = document.getElementById("CountryModal");
            const modalOwl = $('#book-search');
            const modalAllItems = $('#book-search .item').clone(); // Backup all items
            const noBooksModalMessage = document.getElementById("no-books-modal-message");

            function refreshModalOwl(itemsToShow) {
                modalOwl.trigger('destroy.owl.carousel');
                modalOwl.html('');

                if (itemsToShow.length > 0) {
                    noBooksModalMessage.style.display = 'none';
                    modalOwl.append(itemsToShow);
                    modalOwl.owlCarousel({
                        loop: false,
                        margin: 15,
                        nav: true,
                        dots: false,
                        navText: [
                            // Left Arrow
                            `<button class="owl-prev">
         <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" width="30" height="30" viewBox="0 0 512 512">
          <path d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l128 128c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 288H480c17.7 0 32-14.3 32-32s-14.3-32-32-32H109.3l73.4-73.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L9.4 233.4z"/>
        </svg>
      </button>`,

                            // Right Arrow (flipped path)
                            `<button class="owl-next">
        <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" width="30" height="30" viewBox="0 0 512 512">
          <path d="M502.6 278.6c12.5-12.5 12.5-32.8 0-45.3l-128-128c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L402.7 224H32c-17.7 0-32 14.3-32 32s14.3 32 32 32h370.7l-73.4 73.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l128-128z"/>
        </svg>

      </button>`,
                        ],
                        responsive: {
                            0: {
                                items: 1
                            },
                            600: {
                                items: 2
                            },
                            1000: {
                                items: 4
                            }
                        }
                    });
                } else {
                    noBooksModalMessage.style.display = 'block';
                }
            }

            // Initial setup (optional if you auto-show modal with full list)
            refreshModalOwl(modalAllItems.clone());

            modalCountrySelect.addEventListener("change", function() {
                const selectedCountry = this.value;

                if (selectedCountry === "") {
                    refreshModalOwl(modalAllItems.clone());
                } else {
                    const filteredItems = modalAllItems.filter(function() {
                        return $(this).data('country') === selectedCountry;
                    }).clone();

                    refreshModalOwl(filteredItems);
                }
            });
        });
    </script>
