"use strict";

/**
 * ContextMenu — Web implementation
 *
 * Opens a positioned dropdown menu on right-click (contextmenu event).
 * Uses Bloom's Portal for rendering the menu above other content.
 */
import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { Pressable, StyleSheet, View } from 'react-native';
import { useTheme } from "../theme/use-theme.js";
import { Text } from "../typography/index.js";
import { Portal } from "../portal/index.web.js";
import { useInteractionState } from "../hooks/useInteractionState.js";
import { ItemCtx, useItemContext } from "./context.js";

// ---------------------------------------------------------------------------
// Web-specific context (extends base with position)
// ---------------------------------------------------------------------------
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const WebContextMenuContext = /*#__PURE__*/createContext(null);
WebContextMenuContext.displayName = 'WebContextMenuContext';
function useWebContextMenuContext() {
  const ctx = useContext(WebContextMenuContext);
  if (!ctx) {
    throw new Error('ContextMenu components must be used within a ContextMenu.Root');
  }
  return ctx;
}

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

export function Root({
  children
}) {
  const [position, setPosition] = useState(null);
  const isOpen = position !== null;
  const ctx = useMemo(() => ({
    isOpen,
    position,
    open: () => {
      /* open is handled by the Trigger's contextmenu event */
    },
    close: () => setPosition(null)
  }), [isOpen, position]);

  /**
   * We store the setPosition in a ref so the Trigger can call it
   * without needing a stable identity on `open`.
   */
  return /*#__PURE__*/_jsx(WebContextMenuContext.Provider, {
    value: ctx,
    children: /*#__PURE__*/_jsx(SetPositionContext.Provider, {
      value: setPosition,
      children: children
    })
  });
}
const SetPositionContext = /*#__PURE__*/createContext(() => {});
SetPositionContext.displayName = 'ContextMenuSetPositionContext';

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

export function Trigger({
  children,
  label,
  hint,
  style
}) {
  const ctx = useWebContextMenuContext();
  const setPosition = useContext(SetPositionContext);
  const triggerRef = useRef(null);
  const handleContextMenu = useCallback(e => {
    e.preventDefault();
    setPosition({
      x: e.clientX,
      y: e.clientY
    });
  }, [setPosition]);
  useEffect(() => {
    const node = triggerRef.current;
    if (!node) return;
    // On web, View refs resolve to DOM elements
    const element = node;
    element.addEventListener('contextmenu', handleContextMenu);
    return () => {
      element.removeEventListener('contextmenu', handleContextMenu);
    };
  }, [handleContextMenu]);
  return /*#__PURE__*/_jsx(View, {
    ref: triggerRef,
    style: style,
    children: children({
      isOpen: ctx.isOpen,
      state: {
        hovered: false,
        focused: false,
        pressed: false
      },
      props: {
        onPress: null,
        onLongPress: null,
        onFocus: null,
        onBlur: null,
        accessibilityLabel: label,
        accessibilityHint: hint ?? 'Right-click to open context menu'
      }
    })
  });
}

// ---------------------------------------------------------------------------
// Outer
// ---------------------------------------------------------------------------

export function Outer({
  children,
  style
}) {
  const ctx = useWebContextMenuContext();
  const theme = useTheme();
  const {
    isOpen,
    close,
    position
  } = ctx;
  useEffect(() => {
    if (!isOpen || typeof document === 'undefined') return;
    const handleKeyDown = e => {
      if (e.key === 'Escape') {
        close();
      }
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, close]);
  if (!isOpen || !position) return null;
  return /*#__PURE__*/_jsxs(Portal, {
    children: [/*#__PURE__*/_jsx(Pressable, {
      style: styles.backdrop,
      onPress: close,
      accessibilityLabel: "Close context menu"
    }), /*#__PURE__*/_jsx(View, {
      style: [styles.dropdown, {
        top: position.y,
        left: position.x,
        backgroundColor: theme.isDark ? theme.colors.backgroundSecondary : theme.colors.background,
        borderColor: theme.colors.borderLight,
        shadowColor: theme.colors.shadow
      }, style],
      children: children
    })]
  });
}

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

export function Item({
  children,
  label,
  onPress,
  disabled = false,
  style
}) {
  const theme = useTheme();
  const {
    close
  } = useWebContextMenuContext();
  const {
    state: hovered,
    onIn: onMouseEnter,
    onOut: onMouseLeave
  } = useInteractionState();
  const {
    state: focused,
    onIn: onFocus,
    onOut: onBlur
  } = useInteractionState();
  const isHighlighted = (hovered || focused) && !disabled;
  const handlePress = useCallback(() => {
    onPress();
    close();
  }, [onPress, close]);
  const itemCtx = useMemo(() => ({
    disabled
  }), [disabled]);
  return /*#__PURE__*/_jsx(Pressable, {
    accessibilityHint: "",
    accessibilityLabel: label,
    disabled: disabled,
    onPress: handlePress,
    onFocus: onFocus,
    onBlur: onBlur,
    onMouseEnter,
    onMouseLeave,
    style: [styles.item, isHighlighted && {
      backgroundColor: theme.isDark ? theme.colors.contrast50 : theme.colors.backgroundSecondary
    }, style],
    children: /*#__PURE__*/_jsx(ItemCtx.Provider, {
      value: itemCtx,
      children: children
    })
  });
}

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

export function ItemText({
  children,
  style
}) {
  const theme = useTheme();
  const {
    disabled
  } = useItemContext();
  return /*#__PURE__*/_jsx(Text, {
    numberOfLines: 1,
    ellipsizeMode: "middle",
    style: [styles.itemText, {
      color: disabled ? theme.colors.textTertiary : theme.colors.text
    }, ...(style ? [style] : [])],
    children: children
  });
}

// ---------------------------------------------------------------------------
// ItemIcon
// ---------------------------------------------------------------------------

export function ItemIcon({
  icon: Comp
}) {
  const theme = useTheme();
  const {
    disabled
  } = useItemContext();
  return /*#__PURE__*/_jsx(Comp, {
    size: "md",
    fill: disabled ? theme.colors.textTertiary : theme.colors.textSecondary
  });
}

// ---------------------------------------------------------------------------
// Group
// ---------------------------------------------------------------------------

export function Group({
  children
}) {
  return /*#__PURE__*/_jsx(_Fragment, {
    children: children
  });
}

// ---------------------------------------------------------------------------
// Divider
// ---------------------------------------------------------------------------

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

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

const styles = StyleSheet.create({
  backdrop: {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 50,
    // Opt back in from the Portal root's `pointer-events: none`.
    pointerEvents: 'auto'
  },
  dropdown: {
    position: 'fixed',
    zIndex: 60,
    borderRadius: 8,
    padding: 4,
    borderWidth: 1,
    overflow: 'hidden',
    shadowOpacity: 0.15,
    shadowRadius: 12,
    shadowOffset: {
      width: 0,
      height: 4
    },
    minWidth: 180,
    maxWidth: 280,
    // Opt back in from the Portal root's `pointer-events: none`.
    pointerEvents: 'auto'
  },
  item: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    paddingVertical: 8,
    borderRadius: 6,
    overflow: 'hidden',
    paddingHorizontal: 10,
    minHeight: 32
  },
  itemText: {
    flex: 1,
    fontWeight: '600'
  },
  divider: {
    height: 1,
    marginVertical: 4
  }
});
//# sourceMappingURL=index.web.js.map