import App from 'next/app'
import { ChakraProvider } from '@chakra-ui/react'
import Layout from '~/components/layout'
import theme from '~/src/theme'
import '~/src/style.scss'

export default function MyApp({ Component, pageProps, globals, menus }) {
  return (
    <ChakraProvider theme={theme}>
      <Layout globals={globals} menus={menus}>
        <Component {...pageProps} />
      </Layout>
    </ChakraProvider>
  )
}

MyApp.getInitialProps = async (context) => {
  const pageProps = await App.getInitialProps(context)

  let url = new URL(`${process.env.NEXT_PUBLIC_DIRECTUS_API_URL}/items/globals`)
  url.searchParams.append('fields[]', '*')
  url.searchParams.append('limit', 1)
  const resG = await fetch(url.toString())
  let { data: globals } = await resG.json()

  url = new URL(`${process.env.NEXT_PUBLIC_DIRECTUS_API_URL}/items/menus`)
  url.searchParams.append('fields[]', '*')
  url.searchParams.append('fields[]', 'menus_menu_items.sort')
  url.searchParams.append('fields[]', 'menus_menu_items.menu_items_id.label')
  url.searchParams.append('fields[]', 'menus_menu_items.menu_items_id.url')
  url.searchParams.append('fields[]', 'menus_menu_items.menu_items_id.sort')
  url.searchParams.append('limit', -1)
  const resM = await fetch(url.toString())
  const { data: menus } = await resM.json()

  return {
    ...pageProps,
    globals,
    menus: menus.map((m) => ({
      id: m.id,
      items: m.menus_menu_items.sort((a, b) => a.sort - b.sort).map((mm) => mm.menu_items_id),
    })),
  }
}
