import { useMemo } from 'react'

import { useLocation } from 'react-router'

import { getClientSettings } from 'features/AuthStore/helpers'
import { useLexicsStore } from 'features/LexicsStore'

export const useParamsUrl = () => {
  const location = useLocation()
  const { lang } = useLexicsStore()

  const {
    client_id,
    nonce,
    redirect_uri,
    response_mode,
    response_type,
    scope,
    state,
  } = getClientSettings()

  const urlSearchParams = useMemo(() => new URLSearchParams(location.search), [location.search])

  // safari начал поддержку Object.fromEntries с версии 12.1
  const params = useMemo(() => (
    Array.from(urlSearchParams.entries()).reduce((acc, [key, value]) => ({
      ...acc,
      [key]: value,
    }), {})),
  [urlSearchParams])

  return {
    client_id,
    nonce,
    redirect_uri,
    response_mode,
    response_type,
    scope,
    state,
    ...params,
    lang,
  }
}
