import { useEffect, useState } from 'react'

import { cdnUrls, useLinks } from '../core'
import { Environment, isObject } from '../utils'
import { FooterColumnData } from './footer.types'

type FooterLinksTemplates = {
  columns?: FooterColumnData[]
  linkedIn?: string
}

/** Loads templates for Footer links and enriches them with urls from LinksContext. */
export function useFooterLinks(env: Environment) {
  const [templates, setTemplates] = useState<FooterLinksTemplates>({})
  const [links] = useLinks()

  useEffect(() => {
    loadFooterlinks()

    async function loadFooterlinks() {
      try {
        const response = await fetch(`${cdnUrls[env]}/common/data/links/footer.json`)
        if (!response.ok) return

        const data = await response.json()

        if (isObject(data)) setTemplates(data)
      } catch {
        console.error('Failed to retrieve footer data.')
      }
    }
  }, [env])

  const columns: FooterColumnData[] | undefined = templates.columns?.map(column =>
    column.map(section => ({
      ...section,
      links: section.links?.map(link => ({ ...link, url: links?.[link?.id ?? ''] })),
    })),
  )

  return { columns, linkedIn: templates.linkedIn }
}
