/** Parse an UltiMeet / Jitsi room URL returned by the backend. */
export function parseMeetUrl(raw: string): {
  room: string
  jwt?: string
  embedUrl: string
} | null {
  const trimmed = raw.trim()
  if (!trimmed) return null

  try {
    const url = trimmed.startsWith("http")
      ? new URL(trimmed)
      : new URL(trimmed, "https://placeholder.local")

    const pathMatch = url.pathname.match(/\/meet\/([^/]+)\/?$/i)
    if (!pathMatch?.[1]) return null

    const room = decodeURIComponent(pathMatch[1])
    const jwt = url.searchParams.get("jwt") ?? undefined
    const embedUrl = jwt
      ? `${url.origin}/meet/${encodeURIComponent(room)}?jwt=${encodeURIComponent(jwt)}`
      : `${url.origin}/meet/${encodeURIComponent(room)}`

    return { room, jwt, embedUrl }
  } catch {
    return null
  }
}

export function isUltiMeetUrl(raw: string): boolean {
  return parseMeetUrl(raw) !== null
}

/** In-app join route for agenda links (keeps users inside UltiSuite). */
export function meetJoinPath(meetUrl: string): string {
  return `/meet/join?u=${encodeURIComponent(meetUrl)}`
}

export function meetRoomPath(room: string, jwt?: string): string {
  const base = `/meet/${encodeURIComponent(room)}`
  if (!jwt) return base
  return `${base}?jwt=${encodeURIComponent(jwt)}`
}
