import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'
import FormActionBar from '../components/FormActionBar'

const FormEditorActionsContext = createContext(null)

export function FormEditorActionsProvider({ children }) {
  const [config, setConfig] = useState(null)
  const value = useMemo(() => ({ config, setConfig }), [config])

  return <FormEditorActionsContext.Provider value={value}>{children}</FormEditorActionsContext.Provider>
}

/** Mobile: FormActionBar statt Bottom-Nav; Desktop: Fallback (Nav ist ohnehin ausgeblendet). */
export function FormEditorBottomSlot({ children }) {
  const ctx = useContext(FormEditorActionsContext)
  const config = ctx?.config

  if (config) {
    return (
      <div className="form-editor-mobile-dock" data-testid="form-editor-mobile-dock">
        <FormActionBar {...config} placement="bottom" variant="page" />
      </div>
    )
  }

  return children
}

/** @param {Record<string, unknown> | null} config FormActionBar-Props */
export function useFormEditorActions(config) {
  const setConfig = useContext(FormEditorActionsContext)?.setConfig

  useEffect(() => {
    if (!setConfig) return undefined
    setConfig(config ?? null)
    return () => setConfig(null)
  }, [setConfig, config])
}
