"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createCombobox = createCombobox;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _useTheme = require("../theme/use-theme.js");
var _useControllableState = require("../hooks/useControllableState.js");
var _index = require("../typography/index.js");
var _index2 = require("../item/index.js");
var _index3 = require("../search-input/index.js");
var _tokens = require("../styles/tokens.js");
var _Chevron = require("../icons/Chevron.js");
var _Check = require("../icons/Check.js");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/**
 * Structural shape of the `Popover` module, satisfied by both the native and
 * web platform forks. Defined explicitly (rather than `typeof import(...)`) so
 * the slightly different render-return types between forks (web `Content` may
 * return `null`) don't make the modules mutually unassignable.
 */

function defaultFilter(option, query) {
  const q = query.trim().toLowerCase();
  if (!q) return true;
  return option.label.toLowerCase().includes(q) || (option.description?.toLowerCase().includes(q) ?? false);
}

/**
 * Build the `Combobox` bound to a platform `Popover` module. The platform
 * entry files (`index.ts` / `index.web.ts`) inject the correct one (native
 * bottom sheet vs web anchored panel) — this repo never relies on implicit
 * `.web` resolution. The combobox logic is single-source.
 *
 * `Combobox` is a filterable autocomplete select that delegates its overlay to
 * Bloom's `Popover` and composes `SearchInput` + `Item`. The trigger + panel
 * read the overlay control from `Popover` context (via an inner component) so
 * selecting an option reliably closes the overlay on every platform.
 */
function createCombobox(Popover) {
  function ComboboxInner({
    options,
    value,
    onValueChange,
    placeholder,
    label,
    emptyText,
    filter,
    query: queryProp,
    onQueryChange,
    disabled,
    maxListHeight
  }) {
    const theme = (0, _useTheme.useTheme)();
    const {
      control
    } = Popover.usePopoverContext();
    const searchRef = (0, _react.useRef)(null);
    const [query, setQuery] = (0, _useControllableState.useControllableState)({
      value: queryProp,
      defaultValue: '',
      onChange: onQueryChange
    });
    const selectedOption = (0, _react.useMemo)(() => options.find(o => o.value === value) ?? null, [options, value]);
    const filtered = (0, _react.useMemo)(() => options.filter(o => filter(o, query)), [options, filter, query]);
    const handleSelect = (0, _react.useCallback)(option => {
      if (option.disabled) return;
      onValueChange(option.value);
      setQuery('');
      control.close();
    }, [onValueChange, setQuery, control]);
    const accessibleLabel = label ?? placeholder;
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(Popover.Trigger, {
        label: accessibleLabel,
        children: ({
          props
        }) => /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.Pressable, {
          ...props,
          disabled: disabled,
          onPress: () => {
            if (disabled) return;
            props.onPress();
            if (_reactNative.Platform.OS === 'web') {
              requestAnimationFrame(() => searchRef.current?.focus());
            }
          },
          accessibilityState: {
            disabled: disabled ?? false
          },
          style: [styles.trigger, {
            backgroundColor: theme.colors.contrast50,
            borderColor: theme.colors.borderLight
          }, disabled && styles.disabled],
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_index.Text, {
            numberOfLines: 1,
            style: [styles.triggerText, {
              color: selectedOption ? theme.colors.text : theme.colors.textSecondary
            }],
            children: selectedOption ? selectedOption.label : placeholder
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Chevron.ChevronTopBottom_Stroke2_Corner0_Rounded, {
            size: "xs",
            fill: theme.colors.textSecondary
          })]
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(Popover.Content, {
        label: accessibleLabel,
        placement: "bottom-start",
        minWidth: 240,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: styles.searchWrap,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_index3.SearchInput, {
            ref: searchRef,
            label: label ?? 'Search',
            value: query,
            onChangeText: setQuery,
            onClearText: () => setQuery(''),
            autoFocus: _reactNative.Platform.OS !== 'web'
          })
        }), filtered.length === 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: styles.empty,
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_index.Text, {
            style: {
              color: theme.colors.textSecondary,
              fontSize: _tokens.fontSize.sm
            },
            children: emptyText
          })
        }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.ScrollView, {
          style: {
            maxHeight: maxListHeight
          },
          keyboardShouldPersistTaps: "handled",
          showsVerticalScrollIndicator: false,
          children: filtered.map(option => {
            const isSelected = option.value === value;
            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_index2.Item, {
              title: option.label,
              subtitle: option.description,
              density: "compact",
              disabled: option.disabled,
              selected: isSelected,
              role: "option",
              onPress: () => handleSelect(option),
              trailing: isSelected ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Check.Check_Stroke2_Corner0_Rounded, {
                size: "sm",
                fill: theme.colors.primary
              }) : null
            }, String(option.value));
          })
        })]
      })]
    });
  }
  function Combobox({
    options,
    value,
    onValueChange,
    placeholder = 'Select…',
    label,
    emptyText = 'No results',
    filter = defaultFilter,
    query,
    onQueryChange,
    disabled = false,
    maxListHeight = 280,
    style,
    testID
  }) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(Popover.Root, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: style,
        testID: testID,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(ComboboxInner, {
          options: options,
          value: value,
          onValueChange: onValueChange,
          placeholder: placeholder,
          label: label,
          emptyText: emptyText,
          filter: filter,
          query: query,
          onQueryChange: onQueryChange,
          disabled: disabled,
          maxListHeight: maxListHeight
        })
      })
    });
  }
  Combobox.displayName = 'Combobox';
  return Combobox;
}
const styles = _reactNative.StyleSheet.create({
  trigger: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: _tokens.space.sm,
    paddingVertical: _tokens.space.sm,
    paddingHorizontal: _tokens.space.md,
    borderRadius: _tokens.borderRadius.sm,
    borderWidth: 1,
    minHeight: 44,
    width: '100%'
  },
  triggerText: {
    flex: 1,
    fontSize: _tokens.fontSize.md
  },
  disabled: {
    opacity: 0.5
  },
  searchWrap: {
    paddingHorizontal: _tokens.space.sm,
    paddingTop: _tokens.space.sm,
    paddingBottom: _tokens.space.xs
  },
  empty: {
    paddingHorizontal: _tokens.space.lg,
    paddingVertical: _tokens.space.lg,
    alignItems: 'center'
  }
});
//# sourceMappingURL=Combobox.js.map