import React, { useState, useRef, useEffect } from "react";

export default function CustomSelect({ value, name, options, onChange, placeholder }) {
  const [open, setOpen] = useState(false);
  const wrapperRef = useRef(null);

  const selectedLabel =
    options.find((opt) => opt.value === value)?.label || placeholder;

  const handleSelect = (val) => {
    onChange({ target: { name, value: val } });
    setOpen(false);
  };

  useEffect(() => {
    const handleClick = (e) => {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, []);

  return (
    <div ref={wrapperRef} className="custom-select">
      <div className="select-selected" onClick={() => setOpen(!open)}>
        {selectedLabel}
      </div>
      
      <div className="select-items" style={{ display: open ? "block" : "none" }}>
        {options.map((opt) => (
          <div
            key={opt.value}
            data-value={opt.value}
            onClick={() => handleSelect(opt.value)}
          >
            {opt.label}
          </div>
        ))}
      </div>
    </div>
  );
}
