"use client"

import { createContext, useContext } from "react"

type RegisterCardRef = (path: string, el: HTMLDivElement | null) => void

const DriveCardRefContext = createContext<RegisterCardRef | null>(null)

export function DriveCardRefProvider({
  registerCardRef,
  children,
}: {
  registerCardRef: RegisterCardRef
  children: React.ReactNode
}) {
  return (
    <DriveCardRefContext.Provider value={registerCardRef}>
      {children}
    </DriveCardRefContext.Provider>
  )
}

export function useDriveCardRefRegistrar(): RegisterCardRef | null {
  return useContext(DriveCardRefContext)
}

export function mergeDriveCardRefs(
  path: string,
  explicit: ((el: HTMLDivElement | null) => void) | undefined,
  fromContext: RegisterCardRef | null
) {
  return (el: HTMLDivElement | null) => {
    explicit?.(el)
    fromContext?.(path, el)
  }
}
