import React from 'react'
import ReactDOM from 'react-dom/client'
import { HeroUIProvider } from '@heroui/react'
import App from './App'
import './styles/index.less'
import './sdk/index.css'
import 'github-markdown-css/github-markdown.css'
import 'react-photo-view/dist/react-photo-view.css'

const rootEl = document.getElementById('root')

document.documentElement.classList.add('light')

if (!Object.hasOwn) {
  Object.defineProperty(Object, 'hasOwn', {
    value(object: any, property: PropertyKey) {
      if (object == null) {
        throw new TypeError('Cannot convert undefined or null to object')
      }
      return Object.prototype.hasOwnProperty.call(Object(object), property)
    },
    configurable: true,
    enumerable: false,
    writable: true,
  })
}

async function loadSDK(): Promise<void> {
  return new Promise((resolve) => {
    const checkAndInitSDK = () => {
      const ChatSDK = (window as any).ChatSDK
      if (ChatSDK && ChatSDK.createChatSDK) {
        const toolId = typeof window !== 'undefined' ? sessionStorage.getItem('currentToolId') : null
        console.log('[SDK] toolId:', toolId)
        const config = {
          code: import.meta.env.VITE_SDK_CODE || 'default_code',
          channel: import.meta.env.VITE_SDK_CHANNEL || 'default_channel',
          toolId,
          mock: import.meta.env.VITE_SDK_MOCK === 'true',
          apiBaseUrl: import.meta.env.VITE_SDK_API_BASE_URL,
        }
        try {
          ChatSDK.createChatSDK(config)
          console.log('[SDK] 初始化成功')
        }
 catch (error) {
          console.error('[SDK] 初始化失败:', error)
        }
        resolve()
        return true
      }
      return false
    }

    if (checkAndInitSDK()) {
      return
    }

    const script = document.createElement('script')
    script.src = '/sdream-ai/sdk/index.js'
    script.type = 'text/javascript'
    script.onload = () => {
      if (checkAndInitSDK()) {
        return
      }
      console.warn('[SDK] SDK加载成功，但未找到ChatSDK，将使用原生实现')
      resolve()
    }
    script.onerror = (event) => {
      console.error('[SDK] ChatSDK 脚本加载失败:', event)
      console.warn('[SDK] 将使用原生实现')
      resolve()
    }
    document.body.appendChild(script)
  })
}

async function initApp() {
  await loadSDK()

  if (rootEl) {
    const root = ReactDOM.createRoot(rootEl)
    root.render(
      <HeroUIProvider className="h-full">
        <App />
      </HeroUIProvider>,
    )
  }
}

initApp()
