"use strict";

import React, { createContext, useCallback, useContext, useLayoutEffect, useMemo, useState } from 'react';
import { FlatList, Pressable, StyleSheet, View } from 'react-native';
import { useTheme } from "../theme/use-theme.js";
import { Text } from "../typography/index.js";
import { Button } from "../button/index.js";
import { useDialogContext, useDialogControl } from "../dialog/context.js";
import { SheetShell } from "../dialog/SheetShell.js";
import { RadioIndicator } from "../radio-indicator/index.js";
import { useInteractionState } from "../hooks/useInteractionState.js";
import { ChevronTopBottom_Stroke2_Corner0_Rounded as ChevronUpDownIcon } from "../icons/Chevron.js";
import { defaultItemValueExtractor, ItemContext, useItemContext } from "./common.js";
import { jsx as _jsx } from "react/jsx-runtime";
export { useItemContext };

// ---------------------------------------------------------------------------
// Context
// ---------------------------------------------------------------------------

const SelectContext = /*#__PURE__*/createContext(null);
SelectContext.displayName = 'SelectContext';
const ValueStoreContext = /*#__PURE__*/createContext([undefined, () => {}]);
ValueStoreContext.displayName = 'SelectValueStoreContext';
function useSelectContext() {
  const ctx = useContext(SelectContext);
  if (!ctx) {
    throw new Error('Select components must be used within a Select.Root');
  }
  return ctx;
}

// ---------------------------------------------------------------------------
// Root
// ---------------------------------------------------------------------------

export function Root({
  children,
  value,
  onValueChange,
  disabled
}) {
  const control = useDialogControl();
  const valueStoreState = useState(undefined);
  const ctx = useMemo(() => ({
    control,
    value,
    onValueChange,
    disabled
  }), [control, value, onValueChange, disabled]);
  return /*#__PURE__*/_jsx(SelectContext.Provider, {
    value: ctx,
    children: /*#__PURE__*/_jsx(ValueStoreContext.Provider, {
      value: valueStoreState,
      children: children
    })
  });
}

// ---------------------------------------------------------------------------
// Trigger
// ---------------------------------------------------------------------------

export function Trigger({
  children,
  label
}) {
  const {
    control
  } = useSelectContext();
  const {
    state: focused,
    onIn: onFocus,
    onOut: onBlur
  } = useInteractionState();
  const {
    state: pressed,
    onIn: onPressIn,
    onOut: onPressOut
  } = useInteractionState();
  if (typeof children === 'function') {
    return children({
      control,
      state: {
        hovered: false,
        focused,
        pressed
      },
      props: {
        onPress: () => control.open(),
        onFocus,
        onBlur,
        accessibilityLabel: label
      }
    });
  }
  return /*#__PURE__*/_jsx(Button, {
    accessibilityLabel: label,
    onPress: () => control.open(),
    variant: "secondary",
    size: "large",
    style: styles.triggerButton,
    children: children
  });
}

// ---------------------------------------------------------------------------
// ValueText
// ---------------------------------------------------------------------------

export function ValueText({
  placeholder,
  children: extractLabel = defaultExtractLabel,
  style
}) {
  const [storedValue] = useContext(ValueStoreContext);
  const theme = useTheme();
  const display = storedValue != null ? extractLabel(storedValue) : placeholder;
  return /*#__PURE__*/_jsx(Text, {
    numberOfLines: 1,
    style: [styles.valueText, {
      color: storedValue != null ? theme.colors.text : theme.colors.textSecondary
    }, ...(style ? [style] : [])],
    children: display
  });
}
function defaultExtractLabel(item) {
  if (item != null && typeof item === 'object' && 'label' in item) {
    return item.label;
  }
  return String(item);
}

// ---------------------------------------------------------------------------
// Icon
// ---------------------------------------------------------------------------

export function Icon(_props) {
  const theme = useTheme();
  return /*#__PURE__*/_jsx(ChevronUpDownIcon, {
    size: "sm",
    fill: theme.colors.textSecondary
  });
}

// ---------------------------------------------------------------------------
// Content
// ---------------------------------------------------------------------------

export function Content({
  items,
  valueExtractor = defaultItemValueExtractor,
  ...props
}) {
  const {
    control,
    ...context
  } = useSelectContext();
  const [, setStoredValue] = useContext(ValueStoreContext);
  useLayoutEffect(() => {
    const item = items.find(candidate => valueExtractor(candidate) === context.value);
    if (item !== undefined) {
      setStoredValue(item);
    }
  }, [items, context.value, valueExtractor, setStoredValue]);
  return /*#__PURE__*/_jsx(ContentInner, {
    control: control,
    items: items,
    valueExtractor: valueExtractor,
    ...props,
    value: context.value,
    onValueChange: context.onValueChange,
    disabled: context.disabled
  });
}
function ContentInner({
  label = 'Select an option',
  items,
  renderItem,
  valueExtractor = defaultItemValueExtractor,
  control,
  ...contextValues
}) {
  const theme = useTheme();
  const render = useCallback(({
    item,
    index
  }) => {
    return renderItem(item, index, contextValues.value);
  }, [renderItem, contextValues.value]);
  const ctx = useMemo(() => ({
    control,
    value: contextValues.value,
    onValueChange: contextValues.onValueChange,
    disabled: contextValues.disabled
  }), [control, contextValues.value, contextValues.onValueChange, contextValues.disabled]);
  return /*#__PURE__*/_jsx(SheetShell, {
    control: control,
    label: label,
    header: /*#__PURE__*/_jsx(View, {
      style: styles.contentHeader,
      children: /*#__PURE__*/_jsx(Text, {
        style: [styles.contentHeaderText, {
          color: theme.colors.text
        }],
        children: label
      })
    }),
    children: /*#__PURE__*/_jsx(SelectContext.Provider, {
      value: ctx,
      children: /*#__PURE__*/_jsx(FlatList, {
        data: items,
        renderItem: render,
        keyExtractor: valueExtractor,
        style: styles.flatList
      })
    })
  });
}

// ---------------------------------------------------------------------------
// Item context + value extractor (shared across platforms)
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Item
// ---------------------------------------------------------------------------

export function Item({
  children,
  value,
  label,
  style
}) {
  const theme = useTheme();
  const {
    close
  } = useDialogContext();
  const {
    value: selectedValue,
    onValueChange
  } = useSelectContext();
  const {
    state: focused,
    onIn: onFocus,
    onOut: onBlur
  } = useInteractionState();
  const {
    state: pressed,
    onIn: onPressIn,
    onOut: onPressOut
  } = useInteractionState();
  const isSelected = value === selectedValue;
  const handlePress = useCallback(() => {
    close(() => {
      onValueChange?.(value);
    });
  }, [close, onValueChange, value]);
  const itemCtx = useMemo(() => ({
    selected: isSelected,
    hovered: false,
    focused,
    pressed
  }), [isSelected, focused, pressed]);
  return /*#__PURE__*/_jsx(Pressable, {
    accessibilityRole: "radio",
    accessibilityLabel: label,
    accessibilityState: {
      checked: isSelected
    },
    onPress: handlePress,
    onFocus: onFocus,
    onBlur: onBlur,
    onPressIn: onPressIn,
    onPressOut: onPressOut,
    style: [styles.item, (focused || pressed) && {
      backgroundColor: theme.colors.contrast50
    }, style],
    children: /*#__PURE__*/_jsx(ItemContext.Provider, {
      value: itemCtx,
      children: children
    })
  });
}

// ---------------------------------------------------------------------------
// ItemText
// ---------------------------------------------------------------------------

export function ItemText({
  children,
  style
}) {
  const {
    selected
  } = useItemContext();
  return /*#__PURE__*/_jsx(Text, {
    style: [styles.itemText, selected && styles.itemTextSelected, ...(style ? [style] : [])],
    children: children
  });
}

// ---------------------------------------------------------------------------
// ItemIndicator
// ---------------------------------------------------------------------------

export function ItemIndicator({
  icon: IconComponent
}) {
  const {
    selected
  } = useItemContext();
  if (IconComponent) {
    return /*#__PURE__*/_jsx(View, {
      style: styles.itemIndicatorIcon,
      children: selected && /*#__PURE__*/_jsx(IconComponent, {
        size: "md"
      })
    });
  }
  return /*#__PURE__*/_jsx(RadioIndicator, {
    selected: selected
  });
}

// ---------------------------------------------------------------------------
// Separator
// ---------------------------------------------------------------------------

export function Separator() {
  const theme = useTheme();
  return /*#__PURE__*/_jsx(View, {
    style: [styles.separator, {
      borderBottomColor: theme.colors.borderLight
    }]
  });
}

// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------

const styles = StyleSheet.create({
  triggerButton: {
    flex: 1,
    justifyContent: 'space-between',
    paddingLeft: 16,
    paddingRight: 12
  },
  valueText: {
    fontSize: 16,
    fontWeight: '400'
  },
  contentHeader: {
    paddingTop: 24,
    paddingBottom: 8,
    paddingHorizontal: 16
  },
  contentHeaderText: {
    fontSize: 20,
    fontWeight: '700',
    textAlign: 'left'
  },
  flatList: {
    flexGrow: 0
  },
  item: {
    flex: 1,
    paddingHorizontal: 16,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingVertical: 12
  },
  itemText: {
    fontSize: 16
  },
  itemTextSelected: {
    fontWeight: '600'
  },
  itemIndicatorIcon: {
    width: 24
  },
  separator: {
    flex: 1,
    borderBottomWidth: 1,
    marginHorizontal: 16,
    marginVertical: 4
  }
});
//# sourceMappingURL=index.js.map