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

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

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

    void loadTheme()

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

  return children
}
