const { useState, useRef, useEffect } = React;

window.CustomSelect = function CustomSelect({ value, onChange, options, name, isFilter = false, placeholderAll = "All Options" }) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef(null);

  useEffect(() => {
    function handleClickOutside(event) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <div className="relative w-full" ref={dropdownRef}>
      <div 
        className="w-full bg-white border-2 border-gray-200 rounded-lg shadow-sm focus:border-blue-500 text-xs sm:text-sm py-2 sm:py-2.5 md:py-3 px-2.5 sm:px-3 hover:border-gray-300 transition-colors outline-none cursor-pointer flex items-center justify-between"
        onClick={() => setIsOpen(!isOpen)}
      >
        <span className={value ? "font-medium text-gray-800 truncate mr-1" : "text-gray-500 truncate mr-1"}>
          {value === 'All' ? placeholderAll : value || 'Select an option'}
        </span>
        <i data-lucide="chevron-down" className="w-3.5 h-3.5 sm:w-4 sm:h-4 text-gray-500 flex-shrink-0"></i>
      </div>

      {isOpen && (
        <div className="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-auto">
          {isFilter && (
            <div 
              className="px-3 sm:px-4 py-2 sm:py-2.5 hover:bg-gray-50 cursor-pointer text-xs sm:text-sm border-b border-gray-100 font-medium text-gray-600"
              onClick={() => { onChange({ target: { name, value: 'All' }}); setIsOpen(false); }}
            >
              {placeholderAll}
            </div>
          )}
          {options.map(option => (
            <div 
              key={option}
              className="px-3 sm:px-4 py-2 sm:py-2.5 hover:bg-gray-50 cursor-pointer text-xs sm:text-sm font-medium text-gray-800"
              onClick={() => { 
                onChange({ target: { name, value: option } }); 
                setIsOpen(false); 
              }}
            >
              {option}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
