import {useMemo} from 'react'

import {parseUrl} from '../../utils/parseUrl'

interface UseDeeplinkReturnType {
  /**
   * The path of the deeplink.
   */
  path?: string
  /**
   * The query parameters of the deeplink.
   */
  queryParams?: {[key: string]: string | undefined}
  /**
   * The hash of the deeplink.
   */
  hash?: string
}

export const useDeeplink = (): UseDeeplinkReturnType => {
  const {initialUrl, handle} = window.minisParams

  return useMemo(() => {
    if (!initialUrl) {
      return {
        path: undefined,
        queryParams: undefined,
        hash: undefined,
      }
    }

    const parsedUrl = parseUrl(initialUrl)
    const deeplinkPathnamePrefix = `/mini/${handle}`

    return {
      path: parsedUrl.pathname.startsWith(deeplinkPathnamePrefix)
        ? parsedUrl.pathname.replace(deeplinkPathnamePrefix, '')
        : parsedUrl.pathname,
      queryParams: parsedUrl.query,
      hash: parsedUrl.hash,
    }
  }, [handle, initialUrl])
}
