"use client";
import { parts } from "./fieldset.anatomy.js";
import { useEnvironmentContext } from "../../providers/environment/use-environment-context.js";
import { useSafeLayoutEffect } from "../../utils/use-safe-layout-effect.js";
import { useId, useRef, useState } from "react";
import { dataAttr } from "@zag-js/dom-query";
//#region src/components/fieldset/use-fieldset.ts
var 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();
			setTextElements({
				hasErrorText: !!docOrShadowRoot.getElementById(errorTextId),
				hasHelperText: !!docOrShadowRoot.getElementById(helperTextId)
			});
		};
		checkTextElements();
		const observer = new (env.getWindow()).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
	};
};
//#endregion
export { useFieldset };
