"use client" // Error components must be Client Components

import { useParams, usePathname } from "next/navigation"
import { useEffect } from "react"

import { findLang } from "@/constants/languages"
import { login } from "@/constants/routes/handleAuth"
import { SESSION_EXPIRED } from "@/server/errors/trpc"

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

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

import { LangParams } from "@/types/params"

export default function Error({
  error,
}: {
  error: Error & { digest?: string }
}) {
  const params = useParams<LangParams>()

  useEffect(() => {
    // Log the error to an error reporting service
    console.error(error)

    if (error.message === SESSION_EXPIRED) {
      const loginUrl = login[params.lang]
      window.location.assign(loginUrl)
    }
  }, [error, params.lang])

  const pathname = usePathname()
  const lang = findLang(pathname)

  return (
    <div
      className={`${firaMono.variable} ${firaSans.variable} ${styles.layout}`}
    >
      <div className={styles.content}>{lang}: Something went wrong!</div>
    </div>
  )
}
