import React from "react"
import ReactDOM from "react-dom/client"
import App from "./App"
import ClientTicketPortal from "./ClientTicketPortal.jsx"
import DomainAdmin from "./DomainAdmin.jsx"
import ForgotDomainPassword from "./ForgotDomainPassword.jsx"
import "./styles.css"
import "./wizard-setup.css"
import "./assist-asm.css"
import "./client-ticket-portal.css"
import { initTelemetry } from "./lib/telemetry"

initTelemetry()

function parseAssistPath() {
  const m = window.location.pathname.replace(/\/$/, "").match(/^\/assist\/([^/]+)/)
  return m ? m[1] : null
}

const urlParams = new URLSearchParams(window.location.search)
const ticketFromUrl = urlParams.get('ticket')?.trim()?.toUpperCase()
const sessionFromUrl = urlParams.get('session')?.trim()
const assistSessionId = parseAssistPath()
const assistTakeoverToken = new URLSearchParams(window.location.search).get("token")

const rootEl = document.getElementById('root')
const path = window.location.pathname.replace(/\/$/, '') || '/'

if (path === '/admin/forgot-password') {
  ReactDOM.createRoot(rootEl).render(
    <React.StrictMode>
      <ForgotDomainPassword />
    </React.StrictMode>,
  )
} else if (path === '/admin' || path.startsWith('/admin/')) {
  ReactDOM.createRoot(rootEl).render(
    <React.StrictMode>
      <DomainAdmin />
    </React.StrictMode>,
  )
} else if (ticketFromUrl && !assistSessionId) {
  ReactDOM.createRoot(rootEl).render(
    <React.StrictMode>
      <ClientTicketPortal ticketId={ticketFromUrl} sessionId={sessionFromUrl || ''} />
    </React.StrictMode>,
  )
} else {
  ReactDOM.createRoot(rootEl).render(
  <React.StrictMode>
    <App
      assistSessionId={assistSessionId}
      asmMode={Boolean(assistSessionId)}
      assistTakeoverToken={assistTakeoverToken}
    />
  </React.StrictMode>,
)
}
