"use client";
import { jsx } from "react/jsx-runtime";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { useState, useCallback } from "react";
import { DropdownContext } from "./DropdownContext.js";
const DropdownRoot = ({
  type,
  modal = false,
  onOpenChange: passedOnOpenChange,
  children,
  ...props
}) => {
  const primitiveProps = { ...props, modal };
  let value = null;
  let onValueChange = null;
  if ("value" in primitiveProps) {
    value = primitiveProps.value ?? null;
    delete primitiveProps.value;
  }
  if ("onValueChange" in primitiveProps) {
    onValueChange = primitiveProps.onValueChange ?? null;
    delete primitiveProps.onValueChange;
  }
  const [selectedValue, setSelectedValue] = useState(value);
  const onOpenChange = useCallback(
    (open) => {
      if (type === "select" && open) {
        setSelectedValue(value);
        setTimeout(() => {
          var _a, _b;
          const items = Array.from(((_b = (_a = document.activeElement) == null ? void 0 : _a.parentNode) == null ? void 0 : _b.children) ?? []);
          const selectedItem = items.find((item) => {
            const itemValue = item.getAttribute("data-value");
            return itemValue === (value !== null ? String(value) : null);
          });
          if (selectedItem) {
            selectedItem.focus();
          }
        }, 0);
      }
      passedOnOpenChange == null ? void 0 : passedOnOpenChange(open);
    },
    [type, value, passedOnOpenChange]
  );
  return /* @__PURE__ */ jsx(
    DropdownContext.Provider,
    {
      value: {
        type,
        value,
        onValueChange,
        selectedValue,
        setSelectedValue
      },
      children: /* @__PURE__ */ jsx(DropdownMenuPrimitive.Root, { ...primitiveProps, onOpenChange, children })
    }
  );
};
DropdownRoot.displayName = "Dropdown";
export {
  DropdownRoot
};
