// بسم الله الرحمن الرحيم

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import './App.css'
import App from './App.tsx'
import { NhostProvider, NhostClient } from '@nhost/react'
import { ApolloClient, InMemoryCache, createHttpLink, split } from "@apollo/client"
import { ApolloProvider } from "@apollo/client/react";
import { setContext } from '@apollo/client/link/context'
import { GraphQLWsLink } from '@apollo/client/link/subscriptions'
import { createClient } from 'graphql-ws'
import { getMainDefinition } from '@apollo/client/utilities'

// Initialize Nhost client
const nhost = new NhostClient({
  authUrl: 'https://onekeyword-auth-76aaf2ee939c.hosted.ghaymah.systems', 
  storageUrl: 'https://onekeyword-auth-76aaf2ee939c.hosted.ghaymah.systems',
  functionsUrl: 'https://onekeyword-auth-76aaf2ee939c.hosted.ghaymah.systems',
  graphqlUrl: 'https://onekeyword-auth-76aaf2ee939c.hosted.ghaymah.systems',
})

// Auth link for Apollo Client
const authLink = setContext(async (_, { headers }) => {
  // Get the authentication state from Nhost
  const isAuthenticated = await nhost.auth.isAuthenticatedAsync()
  
  if (isAuthenticated) {
    const token = nhost.auth.getAccessToken()
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : '',
      }
    }
  } else {
    // Use public role when not authenticated
    return {
      headers: {
        ...headers,
        'x-hasura-role': 'public',
      }
    }
  }
})

// HTTP link for queries and mutations
const httpLink = createHttpLink({
  uri: 'https://hasura-bc7db43160df.hosted.ghaymah.systems/v1/graphql',
  
})

// WebSocket link for subscriptions
const wsLink = new GraphQLWsLink(
  createClient({
    url: 'wss://hasura-bc7db43160df.hosted.ghaymah.systems/v1/graphql',
    connectionParams: async () => {
      const isAuthenticated = await nhost.auth.isAuthenticatedAsync()
      
      if (isAuthenticated) {
        const token = nhost.auth.getAccessToken()
        return {
          headers: {
            authorization: token ? `Bearer ${token}` : '',
          }
        }
      } else {
        return {
          headers: {
            'x-hasura-role': 'public',
          }
        }
      }
    },
  })
)

// Split links based on operation type
const splitLink = split(
  ({ query }) => {
    const definition = getMainDefinition(query)
    return (
      definition.kind === 'OperationDefinition' &&
      definition.operation === 'subscription'
    )
  },
  wsLink,
  authLink.concat(httpLink)
)

// Apollo Client setup
const client = new ApolloClient({
  link: splitLink,
  cache: new InMemoryCache(),
})

createRoot(document.getElementById('root')!).render(
  <NhostProvider nhost={nhost}>
    <StrictMode>
      <ApolloProvider client={client}>
        <App />
      </ApolloProvider>
    </StrictMode>
  </NhostProvider>,
)