// Ein Hook für Alert/Confirm/Prompt-Dialoge — ersetzt die zuvor in jeder View
// duplizierte showAlert/showConfirm-Logik + den lokalen Dialog-State.
//
// Nutzung:
//   const { showAlert, showConfirm, showPrompt, dialogElement } = useDialog()
//   ...
//   showConfirm("Titel", "Wirklich?", () => doIt())
//   return (<>{dialogElement}...</>)

import { useCallback, useState } from "react"
import { CustomDialog } from "@/components/CustomDialog"

interface DialogState {
  type: "alert" | "confirm" | "prompt"
  title: string
  message: string
  defaultValue?: string
  autoValue?: string
  autoLabel?: string
  onConfirm: (val?: string) => void
  onCancel?: () => void
}

export function useDialog() {
  const [dialog, setDialog] = useState<DialogState | null>(null)
  const close = useCallback(() => setDialog(null), [])

  const showAlert = useCallback((title: string, message: string, onConfirm?: () => void) => {
    setDialog({
      type: "alert", title, message,
      onConfirm: () => { setDialog(null); onConfirm?.() },
    })
  }, [])

  const showConfirm = useCallback(
    (title: string, message: string, onConfirm: () => void, onCancel?: () => void) => {
      setDialog({
        type: "confirm", title, message,
        onConfirm: () => { setDialog(null); onConfirm() },
        onCancel: () => { setDialog(null); onCancel?.() },
      })
    }, [])

  const showPrompt = useCallback(
    (title: string, message: string, defaultValue: string,
     onConfirm: (val?: string) => void, onCancel?: () => void,
     opts?: { autoValue?: string; autoLabel?: string }) => {
      setDialog({
        type: "prompt", title, message, defaultValue,
        autoValue: opts?.autoValue, autoLabel: opts?.autoLabel,
        onConfirm: (val) => { setDialog(null); onConfirm(val) },
        onCancel: () => { setDialog(null); onCancel?.() },
      })
    }, [])

  const dialogElement = dialog ? <CustomDialog {...dialog} /> : null

  return { showAlert, showConfirm, showPrompt, close, dialogElement }
}
