"use strict";

import React, { useCallback, useMemo, useRef } from 'react';
import { Platform, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { useTheme } from "../theme/use-theme.js";
import { useControllableState } from "../hooks/useControllableState.js";
import { Text } from "../typography/index.js";
import { Item } from "../item/index.js";
import { SearchInput } from "../search-input/index.js";
import { borderRadius, fontSize, space } from "../styles/tokens.js";
import { ChevronTopBottom_Stroke2_Corner0_Rounded as ChevronUpDownIcon } from "../icons/Chevron.js";
import { Check_Stroke2_Corner0_Rounded as CheckIcon } from "../icons/Check.js";

/**
 * 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.
 */
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
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.
 */
export function createCombobox(Popover) {
  function ComboboxInner({
    options,
    value,
    onValueChange,
    placeholder,
    label,
    emptyText,
    filter,
    query: queryProp,
    onQueryChange,
    disabled,
    maxListHeight
  }) {
    const theme = useTheme();
    const {
      control
    } = Popover.usePopoverContext();
    const searchRef = useRef(null);
    const [query, setQuery] = useControllableState({
      value: queryProp,
      defaultValue: '',
      onChange: onQueryChange
    });
    const selectedOption = useMemo(() => options.find(o => o.value === value) ?? null, [options, value]);
    const filtered = useMemo(() => options.filter(o => filter(o, query)), [options, filter, query]);
    const handleSelect = useCallback(option => {
      if (option.disabled) return;
      onValueChange(option.value);
      setQuery('');
      control.close();
    }, [onValueChange, setQuery, control]);
    const accessibleLabel = label ?? placeholder;
    return /*#__PURE__*/_jsxs(_Fragment, {
      children: [/*#__PURE__*/_jsx(Popover.Trigger, {
        label: accessibleLabel,
        children: ({
          props
        }) => /*#__PURE__*/_jsxs(Pressable, {
          ...props,
          disabled: disabled,
          onPress: () => {
            if (disabled) return;
            props.onPress();
            if (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__*/_jsx(Text, {
            numberOfLines: 1,
            style: [styles.triggerText, {
              color: selectedOption ? theme.colors.text : theme.colors.textSecondary
            }],
            children: selectedOption ? selectedOption.label : placeholder
          }), /*#__PURE__*/_jsx(ChevronUpDownIcon, {
            size: "xs",
            fill: theme.colors.textSecondary
          })]
        })
      }), /*#__PURE__*/_jsxs(Popover.Content, {
        label: accessibleLabel,
        placement: "bottom-start",
        minWidth: 240,
        children: [/*#__PURE__*/_jsx(View, {
          style: styles.searchWrap,
          children: /*#__PURE__*/_jsx(SearchInput, {
            ref: searchRef,
            label: label ?? 'Search',
            value: query,
            onChangeText: setQuery,
            onClearText: () => setQuery(''),
            autoFocus: Platform.OS !== 'web'
          })
        }), filtered.length === 0 ? /*#__PURE__*/_jsx(View, {
          style: styles.empty,
          children: /*#__PURE__*/_jsx(Text, {
            style: {
              color: theme.colors.textSecondary,
              fontSize: fontSize.sm
            },
            children: emptyText
          })
        }) : /*#__PURE__*/_jsx(ScrollView, {
          style: {
            maxHeight: maxListHeight
          },
          keyboardShouldPersistTaps: "handled",
          showsVerticalScrollIndicator: false,
          children: filtered.map(option => {
            const isSelected = option.value === value;
            return /*#__PURE__*/_jsx(Item, {
              title: option.label,
              subtitle: option.description,
              density: "compact",
              disabled: option.disabled,
              selected: isSelected,
              role: "option",
              onPress: () => handleSelect(option),
              trailing: isSelected ? /*#__PURE__*/_jsx(CheckIcon, {
                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__*/_jsx(Popover.Root, {
      children: /*#__PURE__*/_jsx(View, {
        style: style,
        testID: testID,
        children: /*#__PURE__*/_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 = StyleSheet.create({
  trigger: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: space.sm,
    paddingVertical: space.sm,
    paddingHorizontal: space.md,
    borderRadius: borderRadius.sm,
    borderWidth: 1,
    minHeight: 44,
    width: '100%'
  },
  triggerText: {
    flex: 1,
    fontSize: fontSize.md
  },
  disabled: {
    opacity: 0.5
  },
  searchWrap: {
    paddingHorizontal: space.sm,
    paddingTop: space.sm,
    paddingBottom: space.xs
  },
  empty: {
    paddingHorizontal: space.lg,
    paddingVertical: space.lg,
    alignItems: 'center'
  }
});
//# sourceMappingURL=Combobox.js.map