
// imports
import clsx from 'clsx';
import { Combobox } from '@headlessui/react';
import React, { useRef, useEffect } from 'react';

// Component for rendering the slash command combobox
const SlashCombobox = ({ items, onSelect, editor, editorRef, selectedIndex }) => {
  // Reference to the combobox DOM element
  const ref = useRef(null);

  // Position the combobox above the editor
  useEffect(() => {
    if (items.length > 0 && editorRef.current) {
      // Get the combobox element
      const el = ref.current;
      // Get the bounding rectangle of the editor
      const editorRect = editorRef.current.getBoundingClientRect();
      
      // Position the combobox above the editor
      el.style.bottom = `${window.innerHeight - editorRect.top}px`;
      el.style.left = `${editorRect.left}px`;
      el.style.width = `${editorRect.width}px`;
    }
  }, [items.length, editorRef]);

  // Render the combobox
  return (
    <div ref={ref} className="fixed z-10">
      <Combobox value={items[selectedIndex]} onChange={onSelect}>
        <div className="overflow-auto py-1 w-full max-h-60 shadow-lg card">
          <Combobox.Options static>
            {items.map((item, index) => (
              <Combobox.Option
                key={item.name}
                value={item}
                className={clsx(
                  'relative cursor-default select-none py-2 px-4',
                  selectedIndex === index ? 'bg-primary-600 text-white' : ''
                )}
              >
                <span className={clsx('block truncate', selectedIndex === index && 'font-semibold')}>
                  /{item.name}
                </span>
                <span className={clsx('block truncate text-sm', 
                  selectedIndex === index ? 'text-primary-200' : '')}>
                  {item.description}
                </span>
              </Combobox.Option>
            ))}
          </Combobox.Options>
        </div>
      </Combobox>
    </div>
  );
};

// Custom plugin to handle slash commands in the editor
export const withSlashCommands = editor => {
  const { isInline, isVoid } = editor;

  // Override isInline to treat slash commands as inline elements
  editor.isInline = element => {
    return element.type === 'slash-command' ? true : isInline(element);
  };

  // Override isVoid to treat slash commands as void elements
  editor.isVoid = element => {
    return element.type === 'slash-command' ? true : isVoid(element);
  };

  return editor;
};

/**
 * slash combobox
 */
export default SlashCombobox;