// packages/core/src/components/dialog/dialog-root.tsx
import { createUniqueId } from "solid-js";
import type { JSX } from "solid-js";
import {
  type CreateDisclosureStateOptions,
  createDisclosureState,
} from "../../primitives/create-disclosure-state";
import { createRegisterId } from "../../primitives/create-register-id";
import {
  DialogContextProvider,
  InternalDialogContextProvider,
  type InternalDialogContextValue,
} from "./dialog-context";
import type { DialogRootProps } from "./dialog.props";

export type { DialogRootProps };

/**
 * Root component. Manages open state, provides context to all Dialog parts.
 * Renders no DOM elements itself.
 */
export function DialogRoot(props: DialogRootProps): JSX.Element {
  const disclosure = createDisclosureState({
    get open() {
      return props.open;
    },
    get defaultOpen() {
      return props.defaultOpen;
    },
    get onOpenChange() {
      return props.onOpenChange;
    },
  } as CreateDisclosureStateOptions);

  const contentId = createUniqueId();
  const [titleId, setTitleId] = createRegisterId();
  const [descriptionId, setDescriptionId] = createRegisterId();
  const internalCtx: InternalDialogContextValue = {
    isOpen: disclosure.isOpen,
    setOpen: (open) => (open ? disclosure.open() : disclosure.close()),
    modal: () => props.modal ?? true,
    contentId: () => contentId,
    titleId,
    setTitleId,
    descriptionId,
    setDescriptionId,
  };

  return (
    <InternalDialogContextProvider value={internalCtx}>
      <DialogContextProvider value={{ open: disclosure.isOpen, modal: () => props.modal ?? true }}>
        {props.children}
      </DialogContextProvider>
    </InternalDialogContextProvider>
  );
}
