import type { Accessor } from "solid-js";
import { createContext, useContext } from "solid-js";

/** Internal context shared between all AlertDialog parts. */
export interface InternalAlertDialogContextValue {
  isOpen: Accessor<boolean>;
  setOpen: (open: boolean) => void;
  contentId: Accessor<string>;
  titleId: Accessor<string | undefined>;
  setTitleId: (id: string | undefined) => void;
  descriptionId: Accessor<string | undefined>;
  setDescriptionId: (id: string | undefined) => void;
}

const InternalAlertDialogContext = createContext<InternalAlertDialogContextValue>();

/**
 * Returns the internal AlertDialog context. Throws if used outside <AlertDialog>.
 */
export function useInternalAlertDialogContext(): InternalAlertDialogContextValue {
  const ctx = useContext(InternalAlertDialogContext);
  if (!ctx) {
    throw new Error(
      "[PettyUI] AlertDialog parts must be used inside <AlertDialog>.\n" +
        "  Fix: Wrap AlertDialog.Content, AlertDialog.Trigger, etc. inside <AlertDialog>.",
    );
  }
  return ctx;
}

export const InternalAlertDialogContextProvider = InternalAlertDialogContext.Provider;

/** Public context exposed to consumers via AlertDialog.useContext(). */
export interface AlertDialogContextValue {
  /** Whether the alert dialog is currently open. */
  open: Accessor<boolean>;
}

const AlertDialogContext = createContext<AlertDialogContextValue>();

/**
 * Returns the public AlertDialog context. Throws if used outside <AlertDialog>.
 */
export function useAlertDialogContext(): AlertDialogContextValue {
  const ctx = useContext(AlertDialogContext);
  if (!ctx) {
    throw new Error("[PettyUI] AlertDialog.useContext() called outside of <AlertDialog>.");
  }
  return ctx;
}

export const AlertDialogContextProvider = AlertDialogContext.Provider;
