import { jsx } from 'react/jsx-runtime';
import MultipleSelector from '../../../../../../../ui/src/components/multi-select.mjs';
import { useTags } from '../../hooks/blog-hooks.mjs';

function TagsMultiSelect({
  value,
  onChange,
  placeholder
}) {
  const { tags } = useTags();
  const tagMap = /* @__PURE__ */ new Map();
  const idToTagMap = /* @__PURE__ */ new Map();
  (tags || []).forEach((tag) => {
    tagMap.set(tag.name.toLowerCase(), tag);
    tagMap.set(tag.slug, tag);
    idToTagMap.set(tag.id, tag);
  });
  const options = (tags || []).map((tag) => ({
    value: tag.id,
    label: tag.name
  }));
  const selectedOptions = (value || []).map((tag) => {
    if ("id" in tag && tag.id) {
      return {
        value: tag.id,
        label: tag.name
      };
    }
    const existingTag = tagMap.get(tag.name.toLowerCase());
    return {
      value: existingTag?.id || tag.name,
      label: tag.name
    };
  });
  const handleChange = (newOptions) => {
    const tagObjects = newOptions.map((option) => {
      const existingTag = idToTagMap.get(option.value) || Array.from(tagMap.values()).find(
        (tag) => tag.name.toLowerCase() === option.value.toLowerCase()
      );
      if (existingTag) {
        return {
          id: existingTag.id,
          name: existingTag.name,
          slug: existingTag.slug
        };
      }
      return { name: option.value };
    });
    onChange(tagObjects);
  };
  return /* @__PURE__ */ jsx(
    MultipleSelector,
    {
      value: selectedOptions,
      onChange: handleChange,
      placeholder: placeholder ?? "Search or create tags...",
      options,
      creatable: true,
      hidePlaceholderWhenSelected: true,
      className: "w-full"
    }
  );
}

export { TagsMultiSelect };
