"use client"
import ModalRadix from '@/components/shared/ModalRadix'
import { createContext, useContext, useState, ReactNode } from 'react'

interface ModalContextType {
  open: (content: ReactNode) => void
  close: () => void
}

const ModalContext = createContext<ModalContextType | undefined>(undefined)

export const ModalProvider = ({ children }: { children: ReactNode }) => {
  const [modalContent, setModalContent] = useState<ReactNode | null>(null)

  const open = (content: ReactNode) => setModalContent(content)
  const close = () => setModalContent(null)

  return (
    <ModalContext.Provider value={{ open, close }}>
      {children}
      <ModalRadix open={!!modalContent} onClose={close}>
        {modalContent}
      </ModalRadix>
    </ModalContext.Provider>
  )
}

export const useModal = () => {
  const ctx = useContext(ModalContext)
  if (!ctx) throw new Error('useModal must be used within a ModalProvider')
  return ctx
}
