import { homeHrefs } from "@/constants/homeHrefs"
import { env } from "@/env/server"
import {
  getCurrentHeader,
  getLanguageSwitcher,
  getMyPagesNavigation,
  getName,
} from "@/lib/trpc/memoizedRequests"

import { getLang } from "@/i18n/serverContext"

import LanguageSwitcher from "./LanguageSwitcher"
import { MainMenu } from "./MainMenu"
import MyPagesMobileDropdown from "./MyPagesMobileDropdown"
import OfflineBanner from "./OfflineBanner"
import TopMenu from "./TopMenu"

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

export default async function Header() {
  const [data, user, languages, navigation] = await Promise.all([
    getCurrentHeader(getLang()),
    getName(),
    getLanguageSwitcher(),
    getMyPagesNavigation(),
  ])

  if (!navigation || !languages || !data?.header) {
    return null
  }

  const homeHref = homeHrefs[env.NODE_ENV][getLang()]
  const { frontpageLinkText, logo, menu, topMenu } = data.header

  const topMenuMobileLinks = topMenu.links
    .filter((link) => link.show_on_mobile)
    .sort((a, b) => (a.sort_order_mobile < b.sort_order_mobile ? 1 : -1))

  return (
    <header className={styles.header} role="banner">
      <OfflineBanner />
      <TopMenu
        frontpageLinkText={frontpageLinkText}
        homeHref={homeHref}
        links={topMenu.links}
        languageSwitcher={<LanguageSwitcher urls={languages.urls} />}
      />
      <MainMenu
        frontpageLinkText={frontpageLinkText}
        homeHref={homeHref}
        links={menu.links}
        logo={logo}
        topMenuMobileLinks={topMenuMobileLinks}
        languageSwitcher={<LanguageSwitcher urls={languages.urls} />}
        myPagesMobileDropdown={
          <MyPagesMobileDropdown navigation={navigation} />
        }
        bookingHref={homeHref}
        user={user}
      />
    </header>
  )
}
