import { jsxs, jsx } from 'react/jsx-runtime';
import { useCallback } from 'react';
import { ChevronsUpDown, X } from 'lucide-react';
import { useLayerStore } from '../../../../lib/ui-builder/store/layer-store.mjs';
import { Button } from '../../../button.mjs';
import { Badge } from '../../../badge.mjs';
import { AddComponentsPopover } from '../components/add-component-popover.mjs';
import { hasLayerChildren } from '../../../../lib/ui-builder/store/layer-utils.mjs';

function ChildrenSearchableSelect({ layer, onChange }) {
  const { selectLayer, removeLayer, selectedLayerId, findLayerById } = useLayerStore();
  const selectedLayer = findLayerById(selectedLayerId);
  return /* @__PURE__ */ jsxs("div", { className: "w-full space-y-4", children: [
    /* @__PURE__ */ jsx(AddComponentsPopover, { parentLayerId: layer.id, onChange, children: /* @__PURE__ */ jsxs(
      Button,
      {
        variant: "outline",
        role: "combobox",
        className: "w-full justify-between",
        children: [
          "Add Component",
          /* @__PURE__ */ jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 opacity-50" })
        ]
      }
    ) }),
    hasLayerChildren(layer) && /* @__PURE__ */ jsx("div", { className: "w-full flex gap-2 flex-wrap", children: selectedLayer && hasLayerChildren(selectedLayer) && selectedLayer.children.map((child) => /* @__PURE__ */ jsx(
      ChildLayerBadge,
      {
        child,
        selectLayer,
        removeLayer
      },
      child.id
    )) })
  ] });
}
function ChildLayerBadge({ child, selectLayer, removeLayer }) {
  const handleSelect = useCallback(() => {
    selectLayer(child.id);
  }, [selectLayer, child.id]);
  const handleRemove = useCallback(() => {
    removeLayer(child.id);
  }, [removeLayer, child.id]);
  return /* @__PURE__ */ jsxs(Badge, { className: "flex items-center space-x-2 pl-2 pr-0 py-0", variant: "secondary", children: [
    /* @__PURE__ */ jsx(Button, { className: "p-0 h-5", variant: "link", size: "sm", onClick: handleSelect, children: nameForLayer(child) }),
    /* @__PURE__ */ jsx(Button, { className: "p-0 size-6 rounded-full", variant: "ghost", size: "icon", onClick: handleRemove, children: /* @__PURE__ */ jsx(X, { className: "w-4 h-4" }) })
  ] }, child.id);
}
const nameForLayer = (layer) => {
  return layer.name || layer.type.replaceAll("_", "");
};

export { ChildrenSearchableSelect };
