import { useEffect, type ReactNode } from 'react'
import { isAbortError } from '../lib/api'
import { getBusinessDomain } from '../lib/config'
import { resolveTenantByDomain } from '../services/tenantService'
import { applyBusinessPrimaryColor, resetBusinessPrimaryColor } from '../utils/applyBusinessTheme'
import { normalizeBusinessPrimaryColorId } from '../utils/businessPrimaryColors'

export function BusinessThemeProvider({ children }: { children: ReactNode }) {
  useEffect(() => {
    const controller = new AbortController()
    const domain = getBusinessDomain()

    async function loadTheme() {
      try {
        const tenant = await resolveTenantByDomain(domain, controller.signal)
        if (controller.signal.aborted) return
        applyBusinessPrimaryColor(
          normalizeBusinessPrimaryColorId(tenant.primaryColor),
        )
      } catch (err) {
        if (isAbortError(err) || controller.signal.aborted) return
        applyBusinessPrimaryColor(undefined)
      }
    }

    void loadTheme()

    return () => {
      controller.abort()
      resetBusinessPrimaryColor()
    }
  }, [])

  return children
}
