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

export default function GlassSelect({
  id,
  value,
  onChange,
  options = [],
  placeholder = "Select…",
  disabled = false,
  className = "",
  variant = "underline",
  "aria-label": ariaLabel,
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef(null);
  const listId = useId();

  const selected = options.find((o) => String(o.value) === String(value));
  const displayLabel = selected?.label ?? placeholder;

  useEffect(() => {
    if (!open) return undefined;

    const onDocPointer = (event) => {
      if (!rootRef.current?.contains(event.target)) {
        setOpen(false);
      }
    };

    const onKey = (event) => {
      if (event.key === "Escape") {
        setOpen(false);
      }
    };

    document.addEventListener("mousedown", onDocPointer);
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("mousedown", onDocPointer);
      document.removeEventListener("keydown", onKey);
    };
  }, [open]);

  const pick = (nextValue) => {
    onChange(String(nextValue));
    setOpen(false);
  };

  return (
    <div
      className={["swi-glass-select-root", className].filter(Boolean).join(" ")}
    >
      <div
        ref={rootRef}
        className={[
          "swi-glass-select",
          variant === "glass" ? "swi-glass-select--glass" : "",
          open ? "is-open" : "",
          disabled ? "is-disabled" : "",
        ]
          .filter(Boolean)
          .join(" ")}
      >
      <button
        type="button"
        id={id}
        className="swi-glass-select__trigger"
        aria-haspopup="listbox"
        aria-expanded={open}
        aria-controls={listId}
        aria-label={ariaLabel}
        disabled={disabled}
        onClick={() => {
          if (!disabled) setOpen((wasOpen) => !wasOpen);
        }}
      >
        <span
          className={[
            "swi-glass-select__value",
            !selected ? "is-placeholder" : "",
          ]
            .filter(Boolean)
            .join(" ")}
        >
          {displayLabel}
        </span>
        <span className="swi-glass-select__chevron" aria-hidden="true" />
      </button>

      {open ? (
        <ul id={listId} className="swi-glass-select__menu" role="listbox">
          {options.map((opt) => {
            const active = String(opt.value) === String(value);
            return (
              <li key={String(opt.value)} role="presentation">
                <button
                  type="button"
                  role="option"
                  aria-selected={active}
                  className={[
                    "swi-glass-select__option",
                    active ? "is-selected" : "",
                  ]
                    .filter(Boolean)
                    .join(" ")}
                  onClick={() => pick(opt.value)}
                >
                  {opt.label}
                </button>
              </li>
            );
          })}
        </ul>
      ) : null}
      </div>
    </div>
  );
}
