import { Auth0Provider } from '@auth0/auth0-react'
import { or } from '../utils/types'
import AuthWrapper from '../providers/auth'
import HTTPProvider from '../providers/http'
import App from './App'
import { useState } from 'react'

function AuthHTTPWrapper() {
  const [gotToken, setGotToken] = useState(false)

  let url: string | undefined = window.location.origin;
  let audience: string | undefined;
  if (window.location.origin === "https://staging.brandxtech.ca") {
    url = import.meta.env.VITE_AUTH0_CLIENT_STAGING_DOMAIN;
    audience = import.meta.env.VITE_AUTH0_STAGING_AUDIENCE;
  } else {
    url = import.meta.env.VITE_AUTH0_CLIENT_DOMAIN;
    audience = import.meta.env.VITE_AUTH0_AUDIENCE;
  }

  let client_id = import.meta.env.VITE_AUTH0_BXT_CLIENT_ID;

  return (
    <Auth0Provider
      domain={or(url, "")}
      clientId={or(client_id, "")}
      authorizationParams={{
        audience: or(audience, ""),
        redirect_uri: window.location.origin + "/callback"
      }}
      useRefreshTokens={true}
      cacheLocation='localstorage'
    >
      <AuthWrapper>
        <HTTPProvider setGotToken={setGotToken}>
          {gotToken ? 
            <App/>
            :
            <p>hi</p>
          }
        </HTTPProvider>
      </AuthWrapper>
    </Auth0Provider>
  )
}

export default AuthHTTPWrapper
