import { fullname } from 'hooks/useNavUser'
import React, { useEffect } from 'react'
import { useTypedSelector } from 'redux/rootReducer'
import { selectUserData } from 'redux/User/selector'
import { getCelloService } from 'services'

const Cello = () => {
  useSelf()

  /*
  This component has no view as it is rendered from the Cello library 

   Ref : https://docs.cello.so/docs/javascript-browser
  */
  return <></>
}

export default Cello

export function useSelf() {
  const user = useTypedSelector(selectUserData)
  const fullName = fullname(user)

  useEffect(() => {
    const initializeCello = async () => {
      const celloData = await getCelloService().generateCelloToken()

      if (celloData) {
        ;(window as any).cello = (window as any).cello || { cmd: [] }
        ;(window as any).cello.cmd.push(async function (cello: any) {
          try {
            await cello.boot({
              productId: celloData.productId,
              token: celloData.token,
              language: 'en',
              productUserDetails: { fullName, email: user?.email },
              onTokenExpiring: updateCelloToken,
              onTokenExpired: updateCelloToken
            })
          } catch (error) {
            console.error('Failed to boot cello:', error)
          }
        })
      }
    }

    const updateCelloToken = async () => {
      const newTokenData = await getCelloService().generateCelloToken()
      try {
        if (newTokenData?.token) {
          await (window as any).cello('updateToken', newTokenData.token)
        }
      } catch (error) {
        console.error('Error updating cello token')
      }
    }

    initializeCello()
  }, [user, fullName])

  return {}
}
