---
import { localizePath } from 'astro-i18next';
import OffCanvas from '@components/OffCanvas/OffCanvas.astro';
import OffCanvasBtn from '@components/OffCanvas/OffCanvasBtn.astro';
import LangSelector from '@components/LangSelector.astro';

const links = [
  { href: localizePath('/'), text: 'Home' },
  { href: localizePath('/blog'), text: 'Blog' },
  { href: localizePath('/projects'), text: 'Projects' },
  { href: localizePath('/curriculum'), text: 'Curriculum' },
  { href: localizePath('/contact'), text: 'Contact' },
];
---

<div id="main-navbar" class="pt-1">
  <nav class="navbar navbar-desktop d-none d-lg-block container">
    <ul class="list-unstyle hstack">
      {
        links.map((link) => (
          <li class="nav-item">
            <a class="nav-link" href={link.href}>
              {link.text}
            </a>
          </li>
        ))
      }
      <li class="nav-item">
        <LangSelector />
      </li>
    </ul>
  </nav>

  <div class="text-end d-lg-none">
    <OffCanvasBtn />
    <OffCanvas>
      <nav class="navbar navbar-mobile">
        <ul class="list-unstyle text-start">
          {
            links.map((link) => (
              <li class="nav-item mb-3">
                <a class="nav-link" href={link.href}>
                  {link.text}
                </a>
              </li>
            ))
          }
          <li class="nav-item mb-3">
            <LangSelector />
          </li>
        </ul>
      </nav>
    </OffCanvas>
  </div>
</div>

<script>
  const setActiveLink = () => {
    const links =
      document.querySelectorAll<HTMLAnchorElement>(`#main-navbar a`);

    links.forEach((link) => {
      if (link.pathname === '/' && location.pathname === '/') {
        link.classList.add('active');
        return;
      }

      if (link.pathname === '/' && location.pathname !== '/') {
        link.classList.remove('active');
        return;
      }

      location.pathname.startsWith(link.pathname)
        ? link.classList.add('active')
        : link.classList.remove('active');
    });
  };
  // Add active class to the current link
  document.addEventListener('astro:page-load', setActiveLink, { once: true });
  document.addEventListener('astro:after-swap', setActiveLink);
</script>

<style lang="scss">
  nav {
    width: 100%;
  }

  .navbar-desktop ul {
    width: fit-content;
    margin-left: auto;

    .nav-item {
      margin-bottom: 0;
    }
  }

  ul {
    padding: 0;
  }

  li > a {
    padding: 0.25rem 0.5rem;
  }

  a {
    --boder-color: transparent;
    border: 1px solid transparent;
    border-radius: 4px;
    text-decoration: none;

    transition: background-color 200ms, color 200ms;
  }

  a.active {
    border: 1px solid var(--prj-accent-bg);
  }

  a:hover {
    --border-color: var(--prj-accent-bg);
    background-color: var(--prj-accent-bg);
    color: var(--prj-accent-text);
    border: 1px solid var(--border-color);
  }
</style>
