// packages/core/src/components/text-field/text-field-root.tsx
import type { JSX } from "solid-js";
import { createUniqueId, splitProps } from "solid-js";
import { createRegisterId } from "../../primitives/create-register-id";
import { TextFieldContextProvider, type TextFieldContextValue } from "./text-field-context";

export interface TextFieldRootProps extends JSX.HTMLAttributes<HTMLDivElement> {
  disabled?: boolean;
  invalid?: boolean;
  required?: boolean;
  children: JSX.Element;
}

/**
 * Root container for TextField. Provides context to all TextField parts.
 */
export function TextFieldRoot(props: TextFieldRootProps): JSX.Element {
  const [local, rest] = splitProps(props, ["disabled", "invalid", "required", "children"]);
  const inputId = createUniqueId();
  const [descriptionId, setDescriptionId] = createRegisterId();
  const [errorMessageId, setErrorMessageId] = createRegisterId();

  const ctx: TextFieldContextValue = {
    inputId: () => inputId,
    descriptionId,
    errorMessageId,
    invalid: () => local.invalid ?? false,
    disabled: () => local.disabled ?? false,
    required: () => local.required ?? false,
    setDescriptionId,
    setErrorMessageId,
  };

  return (
    <TextFieldContextProvider value={ctx}>
      <div
        data-invalid={local.invalid || undefined}
        data-disabled={local.disabled || undefined}
        {...rest}
      >
        {local.children}
      </div>
    </TextFieldContextProvider>
  );
}
