import { logout } from "@/constants/routes/handleAuth"
import { serverClient } from "@/lib/trpc/server"

import Link from "@/components/TempDesignSystem/Link"
import { getIntl } from "@/i18n"

import LoginButton from "../LoginButton"

import styles from "./topMenu.module.css"

import type { TopMenuProps } from "@/types/components/current/header/topMenu"

function capitalize(str: string) {
  return str.charAt(0).toUpperCase().toUpperCase() + str.slice(1).toLowerCase()
}

export default async function TopMenu({
  frontpageLinkText,
  homeHref,
  links,
  languageSwitcher,
  lang,
}: TopMenuProps) {
  const { formatMessage } = await getIntl()
  const user = await serverClient().user.name()
  return (
    <div className={styles.topMenu}>
      <div className={styles.container}>
        <a className={styles.homeLink} href={homeHref}>
          {frontpageLinkText}
        </a>

        <ul className={styles.list}>
          {languageSwitcher ? (
            <li className={styles.langSwitcher}>{languageSwitcher}</li>
          ) : null}

          {links.map(({ link }, i) => (
            <li key={link.href + i}>
              <a className={styles.link} href={link.href}>
                {link.title}
              </a>
            </li>
          ))}
          <li className={styles.sessionContainer}>
            {user ? (
              <>
                {user ? (
                  <Link
                    href={logout[lang]}
                    className={styles.sessionLink}
                    prefetch={false}
                  >
                    {capitalize(user.firstName)}
                  </Link>
                ) : null}
                <div className={styles.loginSeparator} />
                <Link
                  href={logout[lang]}
                  className={styles.sessionLink}
                  prefetch={false}
                >
                  {formatMessage({ id: "Log out" })}
                </Link>
              </>
            ) : (
              <LoginButton
                position="hamburger menu"
                trackingId="loginStartTopMeny"
                className={`${styles.sessionLink} ${styles.loginLink}`}
                lang={lang}
              >
                {formatMessage({ id: "Log in" })}
              </LoginButton>
            )}
          </li>
        </ul>
      </div>
    </div>
  )
}
