"use client"

import { createContext, useContext } from "react"

import type {
  PaymentEvent,
  TrackingPosition,
} from "@scandic-hotels/tracking/types"
import type { BreakfastPackages } from "@scandic-hotels/trpc/routers/hotels/output"

export type TrackingFunctions = {
  trackBookingSearchClick: (
    searchTerm: string,
    searchType: "hotel" | "destination"
  ) => void
  trackAccordionItemOpen: (option: string) => void
  trackOpenSidePeek: (input: {
    name: string | null
    hotelId: string
    includePathname?: boolean
    roomTypeCode?: string | null
  }) => void
  trackGenericEvent(data: any): void
  trackLoginClick(position: TrackingPosition & (string & {})): void
  trackPaymentEvent(payment: PaymentEvent): void
  trackGlaSaveCardAttempt(args: {
    hotelId: string
    hasSavedCreditCard: boolean
    creditCardType?: string
    lateArrivalGuarantee: "mandatory" | "yes" | "no" | "na"
  }): void
  trackUpdatePaymentMethod(args: { method: string }): void
  trackBreakfastSelection(args: {
    breakfastPackage: BreakfastPackages[number]
    hotelId: string
    units: number
  }): void
  trackBedSelection(bedType: string): void
}

export const TrackingContext = createContext<TrackingFunctions | undefined>(
  undefined
)

export const useTrackingContext = (): TrackingFunctions => {
  const context = useContext(TrackingContext)

  if (!context) {
    throw new Error(
      "useTrackingContext must be used within a BookingFlowTrackingProvider. Did you forget to use the provider in the consuming app?"
    )
  }

  return context
}
