@extends('layouts.app')

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet">


<style>
    <style>
        .custom-flex-column {
      display: flex;
      flex-direction: column;
      align-items: center;
      /* padding-top: 1rem;
      padding-left: 1rem;
      padding-right: 1rem; */
    }


    .btn-icon i {
        margin: 0;
    }

    .error_red {
        width: 100%;
        margin-top: 0.25rem;
        font-size: 80%;
        color: #dc3545;
    }

    .custom-flex-normal {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .custom-radius {
      border-radius: 40px;
    }

    .custom-shadow {
      box-shadow: 0px 6px 6px #46291B !important;
    }

    #chat-box {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    padding: 1rem;
    max-height: 500px; /* Adjust as needed */
    overflow-y: auto;
}

.message-wrapper {
    display: flex;
}

.text-left {
    justify-content: flex-start;
}

.text-right {
    justify-content: flex-end;
}

p {
    display: inline-block;
    margin: 0;
}


.toast {
    visibility: hidden;
    min-width: 250px;
    margin-left: -125px;
    background-color: #333;
    color: #fff;
    text-align: center;
    border-radius: 2px;
    padding: 16px;
    position: fixed;
    z-index: 100;
    right: 30px;
    top: 30px;
    font-size: 17px;
  }

  .toast.show {
    visibility: visible;
    animation: fadeInOut 3s;
  }

  @keyframes fadeInOut {
    0% {
      opacity: 0;
    }
    10% {
      opacity: 1;
    }
    90% {
      opacity: 1;
    }
    100% {
      opacity: 0;
    }
  }

  /* Success (green) */
  .toast.success {
    background-color: #28a745;
  }

  /* Error (red) */
  .toast.error {
    background-color: #dc3545;
  }

  #common-interests-message {
    position: absolute; /* Position it above the chat box */
    
    left: 75%; /* Center it horizontally */
    transform: translateX(-50%); /* Center the message precisely */
    /* background-color: rgba(255, 255, 255, 0.8); Semi-transparent background */
    padding: 10px 20px;
    border-radius: 8px;
    /* box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); */
    z-index: 10; /* Make sure it appears above the chat box */
    
}

#chat-box {
    position: relative; /* Necessary for the overlay positioning */
}

/* Show the message if there's content */
#common-interests-message.show {
    display: block;
}


/* Gender Button Style */
.gender-btn {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    background-color: #f0f0f0;
    border-radius: 20px;
    cursor: pointer;
    border: 2px solid transparent;
    transition: all 0.3s ease;
    font-size: 14px;
}

.gender-btn img {
    margin-right: 8px;
}

.gender-btn:hover {
    background-color: #ddd;
}

.gender-btn.active {
    background-color: #AF8F6F;
    color: white;
    border: 2px solid #5D432A;
}

#gender-selection {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin-top: 20px;
}



#gender-button img {
    margin-right: 8px;
}

/* Popup Styling */
#popup, #gender-popup, #interests-popup {
    transition: opacity 0.3s ease, visibility 0.3s ease;
}

#popup.hidden, #gender-popup.hidden, #interests-popup.hidden {
    opacity: 0;
    visibility: hidden;
}


.country-btn {
        background-color: #5D432A;
        padding: 10px;
        border-radius: 8px;
        text-align: center;
        cursor: pointer;
        transition: transform 0.2s, background-color 0.2s;
    }

    .country-btn:hover {
        transform: scale(1.05);
        background-color: #7A5B3C;
    }

    .country-btn img {
        display: block;
        margin: 0 auto;
    }


    </style>
</style>

@section('content')
<div class="h-screen relative w-full bg-[#F8F4E1] custom-flex-column">
    <div class="h-full w-full max-w-[1400px]">
        <div class="w-full h-[10%] mb-4 custom-flex-normal">
            <a href="/">
                <img class="h-[3.5vw] min-h-[60px]" src="images/logo.png" alt="mainLogo" />
            </a>
        </div>

        <div class="w-full h-[86%] flex flex-col items-center">
        <div class="w-full h-[60%] lg:h-[70%] flex flex-col lg:flex-row lg:mb-2 gap-2">
    <!-- Left side -->
    <div id="local-stream" class="w-full h-[50%] bg-[#D8D2C2]/40 custom-radius-three lg:h-full lg:custom-radius-four backdrop-blur-md flex flex-col items-center justify-center relative">
    <!-- Video Stream Placeholder -->
    
    <!-- Controls -->
    <div id="controls" 
         class="absolute bottom-10 z-50 flex items-center justify-center space-x-6 bg-gray-800/90 p-4 rounded-full shadow-lg transform translate-y-1/2 hidden">
        <!-- Mute Button -->
        <button id="mic-btn" onclick="toggleMic()" class="text-white text-2xl hover:text-blue-400">
            <i class="fas fa-microphone"></i>
        </button>
        <!-- Video Toggle Button -->
        <button id="video-btn" onclick="toggleVideo()" class="text-white text-2xl hover:text-blue-400">
            <i class="fas fa-video"></i>
        </button>
        <button id="switch-camera-btn" onclick="switchCamera()" class="text-white text-2xl hover:text-blue-400">
    <i class="fas fa-camera"></i>
</button>
        <!-- End Call Button -->
        <button onclick="endCall()" class="text-red-500 text-2xl hover:text-red-700">
            <i class="fas fa-phone"></i>
        </button>
    </div>
</div>



            <!-- Right side with name and matching users -->
            <div id="remote-streams" class="w-full h-[50%] bg-[#D8D2C2]/40 custom-radius-two lg:h-full lg:custom-radius-five backdrop-blur-md flex flex-col items-center justify-center">
                <!-- Display User Name -->
                <div id="userName" class="text-center text-xl font-bold text-gray-800 hidden">
                    <!-- User name will be inserted here -->
                </div>
                
                <!-- Matching Users Container -->
                <div id="matchingUsersContainer" class="mt-4 w-full flex flex-col items-center hidden">
                    <!-- Matching users will be dynamically inserted here -->
                </div>




            </div>
</div>

    <div class="w-full h-[40%] lg:h-[30%] py-3 lg:py-0 pt-3 flex flex-col lg:flex-row gap-2">
        <div class="h-[45%] lg:h-full lg:flex lg:flex-row-reverse gap-2 lg:w-1/2">
            <div class="flex w-full lg:w-1/2 justify-between gap-2 mb-2 lg:mb-0">
            <div class="relative z-60 flex-1">
    <button onclick="openCountryPopup()" class="py-2 px-6 lg:h-full lg:rounded-lg w-full active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] text-xs whitespace-nowrap text-[#AF8F6F] uppercase custom-shadow">
        <span id="selected-country">
            <img id="selected-flag" src="https://upload.wikimedia.org/wikipedia/en/4/41/Flag_of_India.svg" alt="Flag" class="inline-block w-4 h-4 mr-2" style="height: 40px; width: 40px;">
        </span>
        Country
    </button>
</div>

                <div class="flex-1 flex lg:h-full justify-between lg:flex-col gap-3">
                <div class="relative z-60 lg:h-full flex-1">
    <button id="gender-button" class="py-2 px-6 w-full lg:h-full lg:rounded-lg active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] text-xs whitespace-nowrap text-[#AF8F6F] uppercase custom-shadow flex items-center justify-center">
        <img src="images/man.png" alt="Male Logo" class="mr-2 w-5 h-5" style="height:40px;width:40px;"> I am
    </button>
</div>
                    <div class="relative z-60 lg:h-full flex-1">
                        <button class="py-2 px-6 w-full lg:h-full lg:rounded-lg active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] text-xs whitespace-nowrap text-[#AF8F6F] uppercase custom-shadow">
                            Looking For
                        </button>
                    </div>
                </div>
            </div>
            <div class="flex w-full lg:w-1/2 justify-between lg:flex-row-reverse gap-2">
                <div class="relative z-60 flex-1">
                    <button onclick="openPopup()" class="py-2 px-[2vw] lg:h-full lg:rounded-lg w-full active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] text-xs whitespace-nowrap text-[#AF8F6F] uppercase custom-shadow">
                        Choose Interest
                    </button>
                </div>
                <div class="flex-1 flex lg:h-full justify-between lg:flex-col gap-3">
                        <div class="relative z-60 lg:h-full flex-1">
                            <button id="next-btn" onclick="connectNextUser()" class="py-2 px-6 w-full lg:h-full lg:rounded-lg active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] text-xs whitespace-nowrap bg-[#AF8F6F] uppercase custom-shadow">
                                Next
                            </button>
         
                        </div>
                    <div class="relative z-60 lg:h-full flex-1">
                        <button id="stop-button" class="py-2 px-6 w-full lg:h-full lg:rounded-lg active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] text-xs whitespace-nowrap bg-[#AF8F6F] uppercase custom-shadow">
                            Stop
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="h-[65%] lg:h-full w-full lg:w-1/2 pt-2 lg:pt-0">
        <div id="common-interests-message" class="hidden text-center">
    <!-- Common Interests message will be displayed here if there are any -->
</div>
    <div
        id="chat-box"
        class="h-[75%] max-h-[160px] lg:max-h-full w-full bg-[#D8D2C2]/40 rounded-xl backdrop-blur-md mb-3 p-2 overflow-y-scroll"
    >
        <!-- Chat messages will be dynamically added here -->
    </div>
    <div class="h-[20%] flex items-center w-full px-1 border-2 border-[#5D432A] rounded-xl">
        <input
            id="message"
            class="w-full bg-transparent px-3 outline-none"
            type="text"
            placeholder="Type a message"
        />
        <button onclick="sendMessage()" class="cursor-pointer active:scale-95">
            <img class="h-8" src="images/send-arr.png" alt="Send" />
        </button>
    </div>
</div>
</div>
    </div>
    <!-- Popup for selecting interests -->
<div id="popup" class="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm flex items-center justify-center z-50 hidden">
    <div class="bg-[#AF8F6F] p-6 rounded-lg w-[90%] max-w-[400px]">
        <div class="flex items-start justify-between">
            <h2 class="font-medium text-2xl leading-6 mb-4 text-[#fff]">
                Choose <br /> Interests
            </h2>
            <button onclick="closePopup()" class="text-[#F8F4E1] text-xl active:scale-105 hover:text-[#5D432A]">X</button>
        </div>
        <div class="flex flex-wrap gap-2 mb-4 max-h-[140px] overflow-y-scroll shadow-lg" id="interest-buttons">
            <!-- Interest buttons will be generated dynamically here -->
        </div>
        <div class="bg-[#F8F4E1] flex mb-3 p-2 rounded-[40px]" id="selected-interests">
            <div class="flex flex-wrap gap-2 mb-4">
                <!-- Selected interests will be displayed here -->
            </div>
        </div>
        <button onclick="submitInterests()" class="py-2 px-6 bg-[#5D432A] text-white rounded-full uppercase font-semibold">
    Continue
</button>
<input type="hidden" id="current-user-id" value="{{ $user->id }}">
<input type="hidden" id="popup-type" value="{{ $type }}">

    </div>
</div>
</div>


<div id="gender-popup" class="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm flex items-center justify-center z-50 hidden">
    <div class="bg-[#AF8F6F] p-6 rounded-lg w-[90%] max-w-[400px]">
        <div class="flex items-start justify-between">
            <h2 class="font-medium text-2xl leading-6 mb-4 text-[#fff]">
                Choose Your Gender
            </h2>
            <button onclick="closeGenderPopup()" class="text-[#F8F4E1] text-xl active:scale-105 hover:text-[#5D432A]">X</button>
        </div>
        <div id="gender-selection" class="flex gap-4 mt-4">
            <button id="male-btn" class="gender-btn">
                <img src="images/man.png" alt="Male Logo" class="w-6 h-6"> Male
            </button>
            <button id="female-btn" class="gender-btn">
                <img src="images/woman.png" alt="Female Logo" class="w-6 h-6"> Female
            </button>
            <button id="couple-btn" class="gender-btn">
                <img src="images/couple.png" alt="Couple Logo" class="w-6 h-6"> Couple
            </button>
        </div>
    </div>
</div>


<div id="country-popup" class="fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm flex items-center justify-center z-50 hidden">
    <div class="bg-[#AF8F6F] p-6 rounded-lg w-[90%] max-w-[400px]">
        <div class="flex items-start justify-between">
            <h2 class="font-medium text-2xl leading-6 mb-4 text-[#fff]">
                Choose Your Country
            </h2>
            <button onclick="closeCountryPopup()" class="text-[#F8F4E1] text-xl active:scale-105 hover:text-[#5D432A]">X</button>
        </div>
        <div id="country-selection" class="grid grid-cols-3 gap-4 mt-4 max-h-[300px] overflow-y-scroll">
            <!-- Dynamic country buttons with scores -->
        </div>
    </div>
</div>


<script src="https://js.pusher.com/7.0/pusher.min.js"></script>


<script src="https://cdn.agora.io/sdk/web/AgoraRTC_N.js"></script>
<script src="https://cdn.agora.io/sdk/web/AgoraRTC_N-production.js"></script>


<script>
    let interests = [];
    let selectedInterests = [];
    let matchingUsers = [];
    let connectedUser = null;
    let client, localStream, remoteStream; 
    let currentUserIndex = 0; 
    


    let currentCameraIndex = 0;
let cameras = [];

async function switchCamera() {
    try {
        // Get available cameras
        cameras = await AgoraRTC.getCameras();

        if (cameras.length <= 1) {
            console.warn('No alternative cameras available to switch.');
            return;
        }

        // Increment to the next camera
        currentCameraIndex = (currentCameraIndex + 1) % cameras.length;

        // Stop the current video track
        if (localVideoTrack) {
            await localVideoTrack.stop();
            await localVideoTrack.close();
        }

        // Use the selected camera
        localVideoTrack = await AgoraRTC.createCameraVideoTrack({
            cameraId: cameras[currentCameraIndex].deviceId,
        });

        // Play the new video track in the local stream container
        localVideoTrack.play('local-stream');

        // Publish the new track to the Agora channel
        if (client) {
            await client.unpublish([localVideoTrack]);
            await client.publish([localVideoTrack]);
        }
    } catch (error) {
        console.error('Error switching camera:', error);
    }
}

   
  // Fetch interests and render buttons
async function fetchInterests() {
    try {


        const type = document.getElementById('popup-type').value;


        const response = await fetch(`{{ route('get.interests') }}?type=${type}`);
        const data = await response.json();
        interests = data;
        renderInterestButtons();
    } catch (error) {
        console.error('Error fetching interests:', error);
    }
}

// Connect to the next user in the list
async function connectNextUser() {
    if (matchingUsers.length === 0) {
        showToast('No matching users found.', 'error');
        return;
    }

    currentUserIndex = (currentUserIndex + 1) % matchingUsers.length;
    const nextUser = matchingUsers[currentUserIndex];
    await connectUser(nextUser);
}

// Toggle the interest selection and update the UI
function toggleInterest(interestTitle) {
    const index = selectedInterests.indexOf(interestTitle);
    if (index > -1) {
        selectedInterests.splice(index, 1);  // Deselect
    } else {
        selectedInterests.push(interestTitle);  // Select
    }
    renderSelectedInterests();
    renderInterestButtons();  // Re-render the buttons to reflect the changes
}

// Disconnect the user and update the active status
async function handleDisconnect() {
    try {
        // End the current call if it exists
        await endCurrentCall();

        // Make API request to update active status
        const response = await fetch("{{ route('update.active.status') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify({
                active_status: 0
            })
        });

        const data = await response.json();

        if (data.success) {
            // Reset any necessary UI elements or states
            connectedUser = null;
            matchingUsers = [];
            currentUserIndex = 0;
            document.getElementById('chat-box').innerHTML = '';

          
          
                window.location.reload();  // Reload the page
            
        } else {
            showToast('Failed to disconnect', 'error');
        }
    } catch (error) {
        console.error('Error updating active status:', error);
        showToast('An error occurred while disconnecting', 'error');
    }
}

// Add event listener for button click to handle disconnect
document.getElementById('stop-button').addEventListener('click', handleDisconnect);

// Call handleDisconnect on page load, if needed
// if (!sessionStorage.getItem('reloaded')) {
//     handleDisconnect();  // Call the function on page load
// }

// Render the interest buttons based on selection
function renderInterestButtons() {
    const interestButtonsContainer = document.getElementById('interest-buttons');
    interestButtonsContainer.innerHTML = '';  // Clear any existing buttons

    interests.forEach(interest => {
        const button = document.createElement('button');
        button.textContent = interest.title;
        button.className = `py-2 px-4 rounded-full border text-sm font-medium
            ${selectedInterests.includes(interest.title)
                ? "bg-[#5D432A] text-white"
                : "bg-[#F8F4E1] text-[#5D432A] border-[#5D432A]"}`;
        button.onclick = () => toggleInterest(interest.title);  // Toggle selection on click
        interestButtonsContainer.appendChild(button);
    });
}

// Render the selected interests as chips
function renderSelectedInterests() {
    const selectedInterestsContainer = document.getElementById('selected-interests').firstElementChild;
    selectedInterestsContainer.innerHTML = '';  // Clear the current selected interests

    selectedInterests.forEach(interest => {
        const chip = document.createElement('span');
        chip.textContent = interest;
        chip.className = 'py-1 px-2 rounded bg-[#5D432A] text-white text-xs';
        selectedInterestsContainer.appendChild(chip);
    });
}

// Open the popup and fetch interests
window.openPopup = function () {
    const type = document.getElementById('popup-type').value; // Get type from hidden input
    fetchInterests(type); // Fetch interests dynamically based on the type
    document.getElementById('popup').classList.remove('hidden'); // Show the popup
};


  
    function submitInterests() {
    const interestsString = selectedInterests.join(',');
    if (interestsString.trim() === '') {
        showToast('Please select at least one interest', 'error');
        return;
    }

    fetch("{{ route('connect.similar') }}", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({ interests: interestsString })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            showToast(data.error, 'error');
        } else {
            matchingUsers = data.matching_users;
            currentUserIndex = 0;
            const matchingUsersContainer = document.getElementById('matchingUsersContainer');
            matchingUsersContainer.innerHTML = '';
            
            if (matchingUsers.length > 0) {
                matchingUsers.forEach(user => {
                    const userDiv = document.createElement('div');
                    userDiv.classList.add('matching-user', 'mb-2', 'p-2', 'bg-gray-100', 'rounded');
                    userDiv.innerHTML = `
                        <p class="font-bold">${user.name}</p>
                        <p class="text-gray-600">${user.number}</p>
                    `;
                    matchingUsersContainer.appendChild(userDiv);
                });
                connectUser(matchingUsers[currentUserIndex]);
            } else {
                showToast("No matching users found.", 'error');
                matchingUsersContainer.innerHTML = '<p>No matching users found.</p>';
                document.getElementById('chat-box').innerHTML = '';
                location.reload(); // Reload the page if no matching user is found
            }
            closePopup();
        }
    })
    .catch(error => showToast('An error occurred while submitting your interests.', 'error'));
}


 
async function connectUser(user) {
    if (user) {
        connectedUser = user;
        const chatBox = document.getElementById('chat-box');
        const commonInterestsMessageContainer = document.getElementById('common-interests-message');

        // Clear the chat box after displaying messages
        chatBox.innerHTML = '';

        // Display common interests if they exist
        if (user.common_interests && user.common_interests.length > 0) {
            const commonInterestsMessage = {
                message: `Common Interests with ${user.name}: ${user.common_interests.join(', ')}`,
                system: true
            };
            
            // Display the common interests message above the chat box
            commonInterestsMessageContainer.textContent = commonInterestsMessage.message;
            commonInterestsMessageContainer.classList.remove('hidden');
            // displayMessage(commonInterestsMessage, 'system');  // Optionally, display it in the chat as well
        } else {
            // If no common interests, hide the common interests message container
            commonInterestsMessageContainer.classList.add('hidden');
        }

        // Proceed with loading the chat and video call
        loadChat();
        showToast(`You are now connected with ${user.name}`, 'success');  // Show toast for the connection
        console.log('Connected user:', connectedUser);

        await startVideoCall(user);  // Start video call after chat load
    } else {
        showToast('No user found with this interest.', 'error');
        document.getElementById('chat-box').innerHTML = '';
        location.reload();
    }
}







    async function endCurrentCall() {
        if (window.currentVideoCall) {
            const { localAudioTrack, localVideoTrack, client } = window.currentVideoCall;
            
            if (localAudioTrack) {
                localAudioTrack.close();
            }
            if (localVideoTrack) {
                localVideoTrack.close();
            }
            if (client) {
                await client.leave();
            }
            
            document.getElementById('local-stream').classList.add('hidden');
            document.getElementById('remote-streams').classList.add('hidden');
            document.getElementById('controls').classList.add('hidden');
            
            const remoteStreams = document.getElementById('remote-streams');
            remoteStreams.innerHTML = '';
            
            window.currentVideoCall = null;
        }
    }

    

    async function startVideoCall(targetUser) {


   const currentUserId = document.getElementById('current-user-id').value;

    
    const channelName = `call-${Math.max(targetUser.id, currentUserId)}-${Math.min(targetUser.id, currentUserId)}`;
    let currentUserUid = Math.floor(Math.random() * 999999) + 1;
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    
    // Clean up existing call
    await endCurrentCall();
    
    let localAudioTrack, localVideoTrack, client;
    let isAudioMuted = false, isVideoMuted = false;

    window.toggleMic = async () => {
        if (!localAudioTrack) return;
        isAudioMuted = !isAudioMuted;
        await localAudioTrack.setEnabled(!isAudioMuted);
        document.getElementById('mic-btn').innerHTML = isAudioMuted 
            ? '<i class="fas fa-microphone-slash"></i>' 
            : '<i class="fas fa-microphone"></i>';
    };

    window.toggleVideo = async () => {
        if (!localVideoTrack) return;
        isVideoMuted = !isVideoMuted;
        await localVideoTrack.setEnabled(!isVideoMuted);
        document.getElementById('video-btn').innerHTML = isVideoMuted 
            ? '<i class="fas fa-video-slash"></i>' 
            : '<i class="fas fa-video"></i>';
    };

    window.endCall = async () => {
        await cleanup();
        document.getElementById('local-stream').classList.add('hidden');
        document.getElementById('remote-streams').classList.add('hidden');
        document.getElementById('controls').classList.add('hidden');
        
    };

    async function cleanup() {
        if (localAudioTrack) {
            localAudioTrack.close();
            localAudioTrack = null;
        }
        if (localVideoTrack) {
            localVideoTrack.close();
            localVideoTrack = null;
        }
        if (client) {
            await client.leave();
            client = null;
        }
        const remoteStreams = document.getElementById('remote-streams');
        if (remoteStreams) {
            remoteStreams.innerHTML = '';
        }
    }

    try {
        // Include both user IDs in the token request
        const response = await fetch('generatetoken', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
            },
            body: JSON.stringify({ 
                channel_name: channelName, 
                uid: currentUserUid,
                current_user_id: currentUserId,
                target_user_id: targetUser.id 
            }),
        });
        const { token } = await response.json();

        client = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' });

        client.on('user-published', async (user, mediaType) => {
            try {
                await client.subscribe(user, mediaType);
                if (mediaType === 'video') {
                    const container = document.createElement('div');
                    container.id = `remote-${user.uid}`;
                    container.className = 'remote-video w-full h-full bg-black rounded-lg';
                    document.getElementById('remote-streams').appendChild(container);
                    user.videoTrack.play(container.id);
                } else if (mediaType === 'audio') {
                    user.audioTrack.play();
                }
            } catch (error) {
                console.error('Error handling remote user:', error);
            }
        });

        client.on('user-unpublished', (user, mediaType) => {
            if (mediaType === 'video') {
                const remoteContainer = document.getElementById(`remote-${user.uid}`);
                if (remoteContainer) {
                    remoteContainer.remove();
                }
            }
        });

        // Add connection state change handler
        client.on('connection-state-change', (curState, prevState) => {
            console.log(`Connection state changed from ${prevState} to ${curState}`);
            if (curState === 'DISCONNECTED') {
                cleanup();
            }
        });

        [localAudioTrack, localVideoTrack] = await AgoraRTC.createMicrophoneAndCameraTracks();
        await client.join('5f7750d1d4014970a4b6d5b8f26022eb', channelName, token, currentUserUid);

        document.getElementById('local-stream').classList.remove('hidden');
        document.getElementById('remote-streams').classList.remove('hidden');
        document.getElementById('controls').classList.remove('hidden');
        localVideoTrack.play('local-stream');
        await client.publish([localAudioTrack, localVideoTrack]);

        window.currentVideoCall = {
            client,
            localAudioTrack,
            localVideoTrack,
            channelName,
            targetUserId: targetUser.id
        };
    } catch (error) {
        console.error('Error:', error);
        await cleanup();
        showToast('Failed to establish video call', 'error');
    }
}


  function handleStreamAdded(event) {
        client.subscribe(event.stream, (err) => {
            console.error('Error subscribing to stream:', err);
        });
    }

    function handleStreamSubscribed(event) {
        remoteStream = event.stream;
        remoteStream.play('remote-stream');
    }

    
    function handleStreamRemoved(event) {
        const stream = event.stream;
        stream.stop();
        document.getElementById('remote-stream').remove();
    }

    function handlePeerLeave(event) {
        const stream = event.stream;
        stream.stop();
        document.getElementById('remote-stream').remove();
    }

  
    window.closePopup = function () {
        document.getElementById('popup').classList.add('hidden');
    };

   
    Pusher.logToConsole = true;
    const pusher = new Pusher('5a24d96c1f9906c8472d', { cluster: 'ap2' });
    const channel = pusher.subscribe('chat.' + "{{ auth()->id() }}");

   
    channel.bind('new-message', function (data) {
        if (connectedUser && data.chat.user_id === connectedUser.id) {
            displayMessage(data.chat, 'receiver');
        }
    });

    const chatBox = document.getElementById('chat-box');
    const messageInput = document.getElementById('message');


    function loadChat() {
    if (!connectedUser) {
        return;
    }

    fetch("{{ route('chat.getMessages', ':receiverId') }}".replace(':receiverId', connectedUser.id))
        .then(response => response.json())
        .then(data => {
           
            chatBox.innerHTML = '';

            
            data.forEach(chat => {
                const senderType = chat.senderType; 
                displayMessage(chat, senderType); 
            });

            
            chatBox.scrollTop = chatBox.scrollHeight;
        })
        // .catch(error => alert('Error loading chat messages.'));
}



function displayMessage(chat, senderType) {
    const messageWrapper = document.createElement('div');
    messageWrapper.className = 'message-wrapper mb-2';

    const message = document.createElement('p');
    message.className = 'py-1 px-4 max-w-[70%] sm:max-w-[50%] font-medium text-sm border-2 rounded-xl';

    if (senderType === 'system') {
        // Style for system messages (common interests)
        message.classList.add('text-gray-600', 'bg-gray-100', 'border-gray-300', 'mx-auto');
        messageWrapper.classList.add('text-center');
        // Make sure system messages are added like regular messages (permanent)
        messageWrapper.classList.add('system-message');
    } else if (senderType === 'user') {
        message.classList.add('text-[#AF8F6F]', 'border-[#5D432A]', 'bg-white');
        messageWrapper.classList.add('text-right');
    } else if (senderType === 'receiver') {
        message.classList.add('text-white', 'bg-[#AF8F6F]', 'border-[#5D432A]');
        messageWrapper.classList.add('text-left');
    }

    message.textContent = chat.message;
    messageWrapper.appendChild(message);
    chatBox.appendChild(messageWrapper);
    chatBox.scrollTop = chatBox.scrollHeight;
}




// Function to send a message if connected
function sendMessage() {
    if (!connectedUser) {
        alert('Please connect with a user first.');
        return;
    }

    const message = messageInput.value.trim();
    if (message === '') {
        alert('Message cannot be empty.');
        return;
    }

    fetch("{{ route('chat.sendMessage') }}", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({ receiver_id: connectedUser.id, message: message })
    })
        .then(response => response.json())
        .then(data => {
            displayMessage({ message: message }, 'user');
            messageInput.value = '';
        })
        .catch(error => alert('Error sending message.'));
}


messageInput.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        event.preventDefault();  // Prevents the Enter key from submitting a form
        sendMessage();  // Call sendMessage function
    }
});

// Fetch interests or other initial setup
document.addEventListener('DOMContentLoaded', () => {
    fetchInterests();

    // Refresh the chat every 5 seconds
    setInterval(loadChat, 2000);
});



function showToast(message, type = 'success') {
  const toast = document.createElement('div');
  toast.classList.add('toast', type);  // Add the type (success or error)
  toast.textContent = message;

  document.body.appendChild(toast);

  // Show the toast and remove it after a short delay
  setTimeout(() => {
    toast.classList.add('show');
  }, 100);

  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 500);
  }, 3000);
}
</script>
<script>
  document.getElementById("gender-button").addEventListener("click", function() {
    const genderPopup = document.getElementById("gender-popup");
    genderPopup.classList.remove("hidden"); // Show the gender popup
});

// Close Gender Selection Popup
function closeGenderPopup() {
    const genderPopup = document.getElementById("gender-popup");
    genderPopup.classList.add("hidden"); // Hide the gender popup
}

// Gender Button Logic (Change Logo and Update "I am" Button)
document.getElementById("male-btn").addEventListener("click", function() {
    updateGenderButton("Male", "images/man.png");
    closeGenderPopup(); // Close the gender popup after selection
});
document.getElementById("female-btn").addEventListener("click", function() {
    updateGenderButton("Female", "images/woman.png");
    closeGenderPopup(); // Close the gender popup after selection
});
document.getElementById("couple-btn").addEventListener("click", function() {
    updateGenderButton("Couple", "images/couple.png");
    closeGenderPopup(); // Close the gender popup after selection
});

// Update "I am" Button with Selected Gender
function updateGenderButton(gender, logo) {
    const genderButton = document.getElementById("gender-button");
    genderButton.innerHTML = `<img src="${logo}" alt="${gender} Logo" class="mr-2 w-5 h-5" style="height:40px;width:40px;"> I am`;
}
</script>

<script>
    // Static list of 30 countries with flag URLs
    const countries = [
        { name: "India", flag: "https://upload.wikimedia.org/wikipedia/en/4/41/Flag_of_India.svg" },
        { name: "USA", flag: "https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg" },
        { name: "UK", flag: "https://upload.wikimedia.org/wikipedia/en/a/ae/Flag_of_the_United_Kingdom.svg" },
        { name: "Canada", flag: "https://upload.wikimedia.org/wikipedia/commons/c/cf/Flag_of_Canada.svg" },
        { name: "Australia", flag: "https://upload.wikimedia.org/wikipedia/commons/b/b9/Flag_of_Australia.svg" },
        { name: "Germany", flag: "https://upload.wikimedia.org/wikipedia/en/b/ba/Flag_of_Germany.svg" },
        { name: "France", flag: "https://upload.wikimedia.org/wikipedia/en/c/c3/Flag_of_France.svg" },
        { name: "Italy", flag: "https://upload.wikimedia.org/wikipedia/en/0/03/Flag_of_Italy.svg" },
        { name: "Japan", flag: "https://upload.wikimedia.org/wikipedia/en/9/9e/Flag_of_Japan.svg" },
        { name: "China", flag: "https://upload.wikimedia.org/wikipedia/commons/0/0f/Flag_of_China.svg" },
        { name: "Russia", flag: "https://upload.wikimedia.org/wikipedia/en/f/f3/Flag_of_Russia.svg" },
        { name: "Brazil", flag: "https://upload.wikimedia.org/wikipedia/en/0/05/Flag_of_Brazil.svg" },
        { name: "South Africa", flag: "https://upload.wikimedia.org/wikipedia/commons/a/af/Flag_of_South_Africa.svg" },
        { name: "Mexico", flag: "https://upload.wikimedia.org/wikipedia/commons/f/fc/Flag_of_Mexico.svg" },
        { name: "Argentina", flag: "https://upload.wikimedia.org/wikipedia/commons/1/1a/Flag_of_Argentina.svg" },
        { name: "South Korea", flag: "https://upload.wikimedia.org/wikipedia/commons/0/09/Flag_of_South_Korea.svg" },
        { name: "Spain", flag: "https://upload.wikimedia.org/wikipedia/en/9/9a/Flag_of_Spain.svg" },
        { name: "Netherlands", flag: "https://upload.wikimedia.org/wikipedia/commons/2/20/Flag_of_the_Netherlands.svg" },
        { name: "Switzerland", flag: "https://upload.wikimedia.org/wikipedia/commons/f/f3/Flag_of_Switzerland.svg" },
        { name: "Sweden", flag: "https://upload.wikimedia.org/wikipedia/en/4/4c/Flag_of_Sweden.svg" },
        { name: "Norway", flag: "https://upload.wikimedia.org/wikipedia/commons/d/d9/Flag_of_Norway.svg" },
        { name: "Denmark", flag: "https://upload.wikimedia.org/wikipedia/commons/9/9c/Flag_of_Denmark.svg" },
        { name: "Belgium", flag: "https://upload.wikimedia.org/wikipedia/commons/6/65/Flag_of_Belgium.svg" },
        { name: "Portugal", flag: "https://upload.wikimedia.org/wikipedia/commons/5/5c/Flag_of_Portugal.svg" },
        { name: "Saudi Arabia", flag: "https://upload.wikimedia.org/wikipedia/commons/0/0d/Flag_of_Saudi_Arabia.svg" },
        { name: "Turkey", flag: "https://upload.wikimedia.org/wikipedia/commons/b/b4/Flag_of_Turkey.svg" },
        { name: "New Zealand", flag: "https://upload.wikimedia.org/wikipedia/commons/3/3e/Flag_of_New_Zealand.svg" },
        { name: "Singapore", flag: "https://upload.wikimedia.org/wikipedia/commons/4/48/Flag_of_Singapore.svg" },
        { name: "Malaysia", flag: "https://upload.wikimedia.org/wikipedia/commons/6/66/Flag_of_Malaysia.svg" },
        { name: "Indonesia", flag: "https://upload.wikimedia.org/wikipedia/commons/9/9f/Flag_of_Indonesia.svg" }
    ];

    // Function to open the popup
    function openCountryPopup() {
        document.getElementById("country-popup").classList.remove("hidden");
        populateCountries();
    }

    // Function to close the popup
    function closeCountryPopup() {
        document.getElementById("country-popup").classList.add("hidden");
    }

    // Function to populate countries in the popup
    function populateCountries() {
        const countrySelection = document.getElementById("country-selection");
        countrySelection.innerHTML = ""; // Clear existing content

        countries.forEach(country => {
            const button = document.createElement("button");
            button.className = "country-btn";
            button.innerHTML = `
                <img src="${country.flag}" alt="${country.name} Flag" class="w-6 h-6 mx-auto">
                <span class="text-xs text-white mt-2 block">${country.name}</span>
            `;
            button.onclick = () => selectCountry(country.name, country.flag);

            countrySelection.appendChild(button);
        });
    }

    // Function to handle country selection
    function selectCountry(countryName, flagUrl) {
        document.getElementById("selected-country").innerHTML = `
            <img src="${flagUrl}" alt="${countryName} Flag" class="inline-block w-4 h-4 mr-2" style="height: 40px; width: 40px;">
          
        `;
        closeCountryPopup();
    }
</script>

    








@endsection

