import { firaMono, firaSans } from "@/app/[lang]/(live)/fonts"

import Header from "@/components/MyPages/Header"
import Sidebar from "@/components/MyPages/Sidebar"

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

import type { LangParams, LayoutArgs } from "@/types/params"
import { request } from "@/lib/graphql/request"
import {
  GetNavigationMyPagesData,
  NavigationItem,
  MenuItem,
} from "@/types/requests/myPages/navigation"
import { GetNavigationMyPages } from "@/lib/graphql/Query/NavigationMyPages.graphql"

export default async function MyPagesLayout({
  children,
  params,
}: React.PropsWithChildren<LayoutArgs<LangParams>>) {
  const response = await request<GetNavigationMyPagesData>(
    GetNavigationMyPages,
    {
      locale: params.lang,
    }
  )

  function mapMenuItems(navigationItems: NavigationItem[]) {
    return navigationItems.map(({ item }): MenuItem => {
      const {
        title,
        url,
        system: { uid },
      } = item.pageConnection.edges[0].node
      return {
        title,
        uid,
        url,
        linkText: item.link_text,
        subItems: item.sub_items ? mapMenuItems(item.sub_items) : null,
      }
    })
  }

  const navigation = response.data.all_navigation_my_pages.items[0]
  const menuItems = mapMenuItems(navigation.items)

  return (
    <div className={`${firaMono.variable} ${firaSans.variable} ${styles.page}`}>
      <Header lang={params.lang} />
      <div className={styles.content}>
        <Sidebar menuItems={menuItems} />
        {children}
      </div>
    </div>
  )
}
