'use client';
import { dataAttr } from '@zag-js/dom-query';
import { useState, useId, useRef } from 'react';
import { useEnvironmentContext } from '../../providers/environment/use-environment-context.js';
import { useSafeLayoutEffect } from '../../utils/use-safe-layout-effect.js';
import { parts } from './fieldset.anatomy.js';

const useFieldset = (props = {}) => {
  const { disabled = false, invalid = false } = props;
  const env = useEnvironmentContext();
  const [textElements, setTextElements] = useState({ hasErrorText: false, hasHelperText: false });
  const uid = useId();
  const id = props.id ?? uid;
  const rootRef = useRef(null);
  const legendId = `fieldset::${id}::legend`;
  const errorTextId = `fieldset::${id}::error-text`;
  const helperTextId = `fieldset::${id}::helper-text`;
  useSafeLayoutEffect(() => {
    const rootNode = rootRef.current;
    if (!rootNode) return;
    const checkTextElements = () => {
      const docOrShadowRoot = env.getRootNode();
      const hasErrorText = !!docOrShadowRoot.getElementById(errorTextId);
      const hasHelperText = !!docOrShadowRoot.getElementById(helperTextId);
      setTextElements({ hasErrorText, hasHelperText });
    };
    checkTextElements();
    const win = env.getWindow();
    const observer = new win.MutationObserver(checkTextElements);
    observer.observe(rootNode, { childList: true, subtree: true });
    return () => observer.disconnect();
  }, [env, errorTextId, helperTextId]);
  const ids = [];
  if (textElements.hasErrorText && invalid) ids.push(errorTextId);
  if (textElements.hasHelperText) ids.push(helperTextId);
  const labelIds = ids.length > 0 ? ids.join(" ") : void 0;
  const getRootProps = () => ({
    ...parts.root.attrs,
    ref: rootRef,
    disabled,
    "data-disabled": dataAttr(disabled),
    "data-invalid": dataAttr(invalid),
    "aria-labelledby": legendId,
    "aria-describedby": labelIds
  });
  const getLegendProps = () => ({
    id: legendId,
    ...parts.legend.attrs,
    "data-disabled": dataAttr(disabled),
    "data-invalid": dataAttr(invalid)
  });
  const getHelperTextProps = () => ({
    id: helperTextId,
    ...parts.helperText.attrs
  });
  const getErrorTextProps = () => ({
    id: errorTextId,
    ...parts.errorText.attrs,
    "aria-live": "polite"
  });
  return {
    refs: {
      rootRef
    },
    ids: {
      legend: legendId,
      errorText: errorTextId,
      helperText: helperTextId
    },
    disabled,
    invalid,
    getRootProps,
    getLegendProps,
    getHelperTextProps,
    getErrorTextProps
  };
};

export { useFieldset };
