// src/components/Select/Select.tsx
import { create, useStore } from "zustand";
import {
  useEffect,
  useRef,
  useState,
  useCallback,
  forwardRef,
  isValidElement,
  Children,
  cloneElement,
  useId
} from "react";
import { createPortal } from "react-dom";
import { CaretDown, Check, WarningCircle } from "phosphor-react";

// src/utils/utils.ts
import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
function cn(...inputs) {
  return twMerge(clsx(inputs));
}

// src/components/Select/Select.tsx
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
var VARIANT_CLASSES = {
  outlined: "border-2 rounded-lg focus:border-primary-950",
  underlined: "border-b-2 focus:border-primary-950",
  rounded: "border-2 rounded-full focus:border-primary-950"
};
var SIZE_CLASSES = {
  small: "text-sm",
  medium: "text-md",
  large: "text-lg",
  "extra-large": "text-lg"
};
var HEIGHT_CLASSES = {
  small: "h-8",
  medium: "h-9",
  large: "h-10",
  "extra-large": "h-12"
};
var PADDING_CLASSES = {
  small: "px-2 py-1",
  medium: "px-3 py-2",
  large: "px-4 py-3",
  "extra-large": "px-5 py-4"
};
function createSelectStore(onValueChange) {
  return create((set) => ({
    open: false,
    setOpen: (open) => set({ open }),
    value: "",
    setValue: (value) => set({ value }),
    selectedLabel: "",
    setSelectedLabel: (label) => set({ selectedLabel: label }),
    onValueChange,
    triggerRect: null,
    setTriggerRect: (rect) => set({ triggerRect: rect })
  }));
}
var useSelectStore = (externalStore) => {
  if (!externalStore) {
    throw new Error(
      "Component must be used within a Select (store is missing)"
    );
  }
  return externalStore;
};
function getLabelAsNode(children) {
  if (typeof children === "string" || typeof children === "number") {
    return children;
  }
  const flattened = Children.toArray(children);
  if (flattened.length === 1) return flattened[0];
  return /* @__PURE__ */ jsx(Fragment, { children: flattened });
}
var injectStore = (children, store, size, selectId) => {
  return Children.map(children, (child) => {
    if (isValidElement(child)) {
      const typedChild = child;
      const newProps = {
        store
      };
      if (typedChild.type === SelectTrigger) {
        newProps.size = size;
        newProps.selectId = selectId;
      }
      if (typedChild.type === SelectContent) {
        newProps.selectId = selectId;
      }
      if (typedChild.props.children) {
        newProps.children = injectStore(
          typedChild.props.children,
          store,
          size,
          selectId
        );
      }
      return cloneElement(typedChild, newProps);
    }
    return child;
  });
};
var Select = ({
  children,
  defaultValue = "",
  className,
  value: propValue,
  onValueChange,
  size = "small",
  label,
  helperText,
  errorMessage,
  id
}) => {
  const storeRef = useRef(null);
  storeRef.current ??= createSelectStore(onValueChange);
  const store = storeRef.current;
  const selectRef = useRef(null);
  const { open, setOpen, setValue, selectedLabel } = useStore(store, (s) => s);
  const generatedId = useId();
  const selectId = id ?? `select-${generatedId}`;
  const findLabelForValue = (children2, targetValue) => {
    let found = null;
    const search = (nodes) => {
      Children.forEach(nodes, (child) => {
        if (!isValidElement(child)) return;
        const typedChild = child;
        if (typedChild.type === SelectItem && typedChild.props.value === targetValue) {
          if (typeof typedChild.props.children === "string")
            found = typedChild.props.children;
        }
        if (typedChild.props.children && !found)
          search(typedChild.props.children);
      });
    };
    search(children2);
    return found;
  };
  useEffect(() => {
    if (!selectedLabel && defaultValue) {
      const label2 = findLabelForValue(children, defaultValue);
      if (label2) store.setState({ selectedLabel: label2 });
    }
  }, [children, defaultValue, selectedLabel]);
  useEffect(() => {
    const handleClickOutside = (event) => {
      const target = event.target;
      const isInsideTrigger = selectRef.current?.contains(target);
      const portaledMenu = document.body.querySelector(
        `[role="menu"][data-select-id="${selectId}"]`
      );
      const isInsidePortaledMenu = portaledMenu?.contains(target);
      if (!isInsideTrigger && !isInsidePortaledMenu) {
        setOpen(false);
      }
    };
    const handleArrowKeys = (event) => {
      const selectContent = document.body.querySelector(
        `[role="menu"][data-select-id="${selectId}"]`
      );
      if (selectContent) {
        event.preventDefault();
        const items = Array.from(
          selectContent.querySelectorAll(
            '[role="menuitem"]:not([aria-disabled="true"])'
          )
        ).filter((el) => el instanceof HTMLElement);
        const focused = document.activeElement;
        const currentIndex = items.findIndex((item) => item === focused);
        let nextIndex;
        if (event.key === "ArrowDown") {
          nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % items.length;
        } else {
          nextIndex = currentIndex === -1 ? items.length - 1 : (currentIndex - 1 + items.length) % items.length;
        }
        items[nextIndex]?.focus();
      }
    };
    if (open) {
      document.addEventListener("mousedown", handleClickOutside);
      document.addEventListener("keydown", handleArrowKeys);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleArrowKeys);
    };
  }, [open, selectId, setOpen]);
  useEffect(() => {
    if (propValue === void 0) return;
    setValue(propValue);
    const label2 = findLabelForValue(children, propValue);
    store.setState({ selectedLabel: label2 ?? "" });
  }, [propValue, children]);
  const sizeClasses = SIZE_CLASSES[size];
  return /* @__PURE__ */ jsxs("div", { className: cn("w-full", className), children: [
    label && /* @__PURE__ */ jsx(
      "label",
      {
        htmlFor: selectId,
        className: cn("block font-bold text-text-900 mb-1.5", sizeClasses),
        children: label
      }
    ),
    /* @__PURE__ */ jsx("div", { className: cn("relative w-full"), ref: selectRef, children: injectStore(children, store, size, selectId) }),
    (helperText || errorMessage) && /* @__PURE__ */ jsxs("div", { className: "mt-1.5 gap-1.5", children: [
      helperText && /* @__PURE__ */ jsx("p", { className: "text-sm text-text-500", children: helperText }),
      errorMessage && /* @__PURE__ */ jsxs("p", { className: "flex gap-1 items-center text-sm text-indicator-error", children: [
        /* @__PURE__ */ jsx(WarningCircle, { size: 16 }),
        " ",
        errorMessage
      ] })
    ] })
  ] });
};
var SelectValue = ({
  placeholder,
  store: externalStore
}) => {
  const store = useSelectStore(externalStore);
  const selectedLabel = useStore(store, (s) => s.selectedLabel);
  const value = useStore(store, (s) => s.value);
  return /* @__PURE__ */ jsx("span", { className: "text-inherit flex gap-2 items-center", children: selectedLabel || placeholder || value });
};
var SelectTrigger = forwardRef(
  ({
    className,
    invalid = false,
    variant = "outlined",
    store: externalStore,
    disabled,
    size = "medium",
    selectId,
    type = "button",
    ...props
  }, ref) => {
    const store = useSelectStore(externalStore);
    const open = useStore(store, (s) => s.open);
    const internalRef = useRef(null);
    const setRefs = useCallback(
      (element) => {
        internalRef.current = element;
        if (typeof ref === "function") {
          ref(element);
        } else if (ref) {
          ref.current = element;
        }
      },
      [ref]
    );
    const updateTriggerRect = useCallback(() => {
      if (internalRef.current) {
        const rect = internalRef.current.getBoundingClientRect();
        store.setState({
          triggerRect: {
            top: rect.top,
            left: rect.left,
            width: rect.width,
            height: rect.height
          }
        });
      }
    }, [store]);
    useEffect(() => {
      if (!open) return;
      const handleUpdate = () => {
        updateTriggerRect();
      };
      window.addEventListener("scroll", handleUpdate, true);
      window.addEventListener("resize", handleUpdate);
      return () => {
        window.removeEventListener("scroll", handleUpdate, true);
        window.removeEventListener("resize", handleUpdate);
      };
    }, [open, updateTriggerRect]);
    const toggleOpen = () => {
      const newOpen = !open;
      if (newOpen) {
        updateTriggerRect();
      }
      store.setState({ open: newOpen });
    };
    const variantClasses = VARIANT_CLASSES[variant];
    const heightClasses = HEIGHT_CLASSES[size];
    const paddingClasses = PADDING_CLASSES[size];
    return /* @__PURE__ */ jsxs(
      "button",
      {
        ref: setRefs,
        id: selectId,
        type,
        className: cn(
          "flex w-full items-center justify-between border-border-300",
          heightClasses,
          paddingClasses,
          invalid && `${variant == "underlined" ? "border-b-2" : "border-2"} border-indicator-error text-text-600`,
          disabled ? "cursor-not-allowed text-text-400 pointer-events-none opacity-50" : "cursor-pointer hover:bg-background-50 focus:bg-accent focus:text-accent-foreground hover:bg-accent hover:text-accent-foreground",
          !invalid && !disabled ? "text-text-700" : "",
          variantClasses,
          className
        ),
        onClick: toggleOpen,
        "aria-expanded": open,
        "aria-haspopup": "listbox",
        "aria-controls": open ? "select-content" : void 0,
        ...props,
        children: [
          props.children,
          /* @__PURE__ */ jsx(
            CaretDown,
            {
              className: cn(
                "h-[1em] w-[1em] opacity-50 transition-transform",
                open ? "rotate-180" : ""
              )
            }
          )
        ]
      }
    );
  }
);
SelectTrigger.displayName = "SelectTrigger";
function applyVerticalPosition(styles, triggerRect, side, align, gap) {
  styles.top = side === "top" ? triggerRect.top - gap : triggerRect.top + triggerRect.height + gap;
  styles.transform = side === "top" ? "translateY(-100%)" : void 0;
  if (align === "start") {
    styles.left = triggerRect.left;
  } else if (align === "center") {
    styles.left = triggerRect.left + triggerRect.width / 2;
    styles.transform = side === "top" ? "translate(-50%, -100%)" : "translateX(-50%)";
  } else {
    styles.left = triggerRect.left + triggerRect.width;
    styles.transform = side === "top" ? "translate(-100%, -100%)" : "translateX(-100%)";
  }
}
function applyHorizontalPosition(styles, triggerRect, side, align, gap) {
  styles.left = side === "left" ? triggerRect.left - gap : triggerRect.left + triggerRect.width + gap;
  styles.transform = side === "left" ? "translateX(-100%)" : void 0;
  if (align === "start") {
    styles.top = triggerRect.top;
  } else if (align === "center") {
    styles.top = triggerRect.top + triggerRect.height / 2;
    styles.transform = side === "left" ? "translate(-100%, -50%)" : "translateY(-50%)";
  } else {
    styles.top = triggerRect.top + triggerRect.height;
    styles.transform = side === "left" ? "translate(-100%, -100%)" : "translateY(-100%)";
  }
}
var SelectContent = forwardRef(
  ({
    children,
    className,
    align = "start",
    side = "bottom",
    store: externalStore,
    selectId,
    ...props
  }, ref) => {
    const store = useSelectStore(externalStore);
    const open = useStore(store, (s) => s.open);
    const triggerRect = useStore(store, (s) => s.triggerRect);
    const [mounted, setMounted] = useState(false);
    useEffect(() => {
      setMounted(true);
    }, []);
    if (!open || !mounted) return null;
    const getPositionStyles = () => {
      if (!triggerRect) {
        return {};
      }
      const gap = 4;
      const styles = {
        position: "fixed",
        zIndex: 9999
      };
      const isVertical = side === "top" || side === "bottom";
      if (isVertical) {
        applyVerticalPosition(styles, triggerRect, side, align, gap);
      } else {
        applyHorizontalPosition(styles, triggerRect, side, align, gap);
      }
      return styles;
    };
    const content = /* @__PURE__ */ jsx(
      "div",
      {
        role: "menu",
        ref,
        "data-select-id": selectId,
        style: getPositionStyles(),
        className: cn(
          "bg-secondary min-w-[210px] max-h-[300px] overflow-y-auto overflow-x-hidden rounded-md border p-1 shadow-md border-border-100",
          className
        ),
        ...props,
        children
      }
    );
    return createPortal(content, document.body);
  }
);
SelectContent.displayName = "SelectContent";
var SelectItem = forwardRef(
  ({
    className,
    children,
    value,
    disabled = false,
    store: externalStore,
    truncate = false,
    ...props
  }, ref) => {
    const store = useSelectStore(externalStore);
    const {
      value: selectedValue,
      setValue,
      setOpen,
      setSelectedLabel,
      onValueChange
    } = useStore(store, (s) => s);
    const handleClick = (e) => {
      const labelNode = getLabelAsNode(children);
      if (!disabled) {
        setValue(value);
        setSelectedLabel(labelNode);
        setOpen(false);
        onValueChange?.(value);
      }
      props.onClick?.(e);
    };
    return /* @__PURE__ */ jsxs(
      "div",
      {
        role: "menuitem",
        "aria-disabled": disabled,
        ref,
        className: `
          bg-secondary focus-visible:bg-background-50
          relative flex select-none items-center gap-2 rounded-sm p-3 outline-none transition-colors [&>svg]:size-4 [&>svg]:shrink-0
          ${className}
          ${disabled ? "cursor-not-allowed text-text-400 pointer-events-none opacity-50" : "cursor-pointer hover:bg-background-50 text-text-700 focus:bg-accent focus:text-accent-foreground hover:bg-accent hover:text-accent-foreground"}
          ${selectedValue === value && "bg-background-50"}
        `,
        onClick: handleClick,
        onKeyDown: (e) => {
          if (e.key === "Enter" || e.key === " ") handleClick(e);
        },
        tabIndex: disabled ? -1 : 0,
        ...props,
        children: [
          /* @__PURE__ */ jsx("span", { className: "absolute right-2 flex h-3.5 w-3.5 items-center justify-center", children: selectedValue === value && /* @__PURE__ */ jsx(Check, { className: "" }) }),
          truncate ? /* @__PURE__ */ jsx("span", { className: "truncate block max-w-[200px]", children }) : children
        ]
      }
    );
  }
);
SelectItem.displayName = "SelectItem";
var Select_default = Select;
export {
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  createSelectStore,
  Select_default as default,
  getLabelAsNode,
  useSelectStore
};
//# sourceMappingURL=index.mjs.map