export type ResolvedMarket = {
  eventRef: string
  marketRef: string
  label: string
  selections: Array<{
    selectionRef: string
    label: string
    price: { display: string; decimal?: number; version?: string }
  }>
}

export type MhseEventReference = {
  matchHypeId: string | null
  externalId: string | null
  connectionKey: string
  startsAt: string | null
  sport: { id: string | null; name: string | null }
  competition: { id: string | null; name: string | null }
}

export type OfferResolutionContext = {
  schemaVersion: 1
  requestId: string
  experienceKey: string
  instanceId: string
  itemId: string
  locale: string
  event: MhseEventReference
  copy: {
    headline: string
    subheadline: string | null
    description: string | null
  }
}

export type AddToBetslipInput = {
  requestId: string
  experienceKey: string
  instanceId: string
  itemId: string
  event: MhseEventReference
  market: ResolvedMarket
  selection: ResolvedMarket['selections'][number]
}

export type MhseEventName =
  | 'experience_viewed'
  | 'story_viewed'
  | 'feed_opened'
  | 'content_changed'
  | 'feed_closed'
  | 'video_started'
  | 'video_quartile'
  | 'video_completed'
  | 'offer_requested'
  | 'offer_resolved'
  | 'offer_viewed'
  | 'betslip_requested'
  | 'betslip_result'
  | 'bet_placed'
  | 'error'

export type MhsePublicEvent = {
  schemaVersion: 1
  eventId: string
  eventName: MhseEventName
  instanceId: string
  experienceKey: string
  itemId: string | null
  requestId: string | null
  sequence: number
  occurredAt: string
  properties: Record<string, string | number | boolean | null>
}

export type BetResult =
  | { status: 'added' }
  | { status: 'auth_required' }
  | { status: 'price_changed'; market: ResolvedMarket }
  | { status: 'suspended' }
  | { status: 'restricted'; reasonCode?: string }
  | { status: 'error'; code?: string; retryable?: boolean }

export type MatchHypeSportsbookOptions = {
  target: string | HTMLElement
  clientId: string
  experienceKey: string
  locale?: string
  /** Opaque sportsbook event IDs in preferred display order. Unknown IDs are ignored. */
  preferredEventIds?: string[]
  runtimeBaseUrl?: string
  betBridge?: {
    resolveOffers(
      context: OfferResolutionContext
    ): Promise<ResolvedMarket | null> | ResolvedMarket | null
    addToBetslip(input: AddToBetslipInput): Promise<BetResult> | BetResult
    openBetslip?(): Promise<void> | void
  }
  onEvent?(event: MhsePublicEvent): void
}

export type MatchHypeSportsbookInstance = {
  open(contentId?: string): void
  close(): void
  destroy(): void
  reportBetPlaced(input: {
    attributionRequestIds: string[]
    stakeMinor?: number
    currency?: string
  }): void
}

declare global {
  interface Window {
    MatchHypeSportsbook: {
      version: '1.0.0'
      mount(options: MatchHypeSportsbookOptions): Promise<MatchHypeSportsbookInstance>
    }
  }
}

export {}
