<link rel="stylesheet" href="/css/navbar.css"/>

<% 
let currentPath = req.originalUrl; 
%>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">    
    <a class="navbar-brand" href="/"><img src="img/travel-icon.png" class="brand-img" alt="Travel Icon"> Experiences Site</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <% if (req.session && req.session.authorized) { %>
        <span class="navbar-text">Logged in as <%= req.session.username %></span>
    <% } %>
    <div class="collapse navbar-collapse" id="navbarNav">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item <%= currentPath === '/' ? 'active' : '' %>">
                <a class="nav-link" href="/">Home</a>
            </li>
            <li class="nav-item <%= currentPath.startsWith('/experiences') ? 'active' : '' %>">
                <a class="nav-link" href="/experiences">Browse Experiences</a>
            </li>           
            <li class="nav-item <%= currentPath.startsWith('/addExperience') ? 'active' : '' %>">
                <a class="nav-link" href="/addExperience">Add New Experience</a>
            </li>
            <li class="nav-item <%= currentPath.startsWith('/contact') ? 'active' : '' %>">
                <a class="nav-link" href="/contact">Contact Us</a>
            </li>
            <% if (req.session && req.session.authorized) { %>
                <li class="nav-item <%= currentPath.startsWith('/logout') ? 'active' : '' %>">
                    <a class="nav-link logout-link" href="/logout">Logout</a>
                </li>
            <% } else { %>
                <li class="nav-item <%= currentPath.startsWith('/login') ? 'active' : '' %>">
                    <a class="nav-link" href="/login">Login</a>
                </li>
            <% } %>
        </ul>
    </div>
</nav>
<script>
    document.querySelector('.logout-link').addEventListener('click', function(e) {
        e.preventDefault(); // Prevent the default link click action
    
        fetch('/logout', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })  
        .then(response => {
            if (response.ok) {
                // Reloading the current page after successful logout
                location.reload();
            } else {
                console.error('Failed to log out');
            }
        });
    });
    </script>
    