"use client"

import { useEffect, useState } from "react"
import {
  authPortalBaseUrl,
  DEFAULT_APP_SWITCHER_CONFIG,
  mergeWithLocalApp,
  parseAppSwitcherConfig,
  type AppSwitcherConfig,
} from "@/lib/app-switcher-config"

export function useAppSwitcherConfig(): {
  config: AppSwitcherConfig
  isLoading: boolean
} {
  const [config, setConfig] = useState<AppSwitcherConfig>(() =>
    mergeWithLocalApp(DEFAULT_APP_SWITCHER_CONFIG),
  )
  const [isLoading, setIsLoading] = useState(Boolean(authPortalBaseUrl()))

  useEffect(() => {
    const base = authPortalBaseUrl()
    if (!base) {
      setConfig(mergeWithLocalApp(DEFAULT_APP_SWITCHER_CONFIG))
      setIsLoading(false)
      return
    }

    let cancelled = false
    setIsLoading(true)
    fetch(`${base}/api/v1/app-switcher`)
      .then((res) => (res.ok ? res.json() : Promise.reject()))
      .then((raw: unknown) => {
        if (cancelled) return
        const parsed = parseAppSwitcherConfig(raw)
        setConfig(mergeWithLocalApp(parsed ?? DEFAULT_APP_SWITCHER_CONFIG))
      })
      .catch(() => {
        if (!cancelled) setConfig(mergeWithLocalApp(DEFAULT_APP_SWITCHER_CONFIG))
      })
      .finally(() => {
        if (!cancelled) setIsLoading(false)
      })

    return () => {
      cancelled = true
    }
  }, [])

  return { config, isLoading }
}
