'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef } from 'react';
import { useMergedRefs } from '@base-ui/utils/useMergedRefs';
import { MagnifyingGlassIcon, XIcon } from '@graphprotocol/gds-react/icons';
import { useControlled, useCSSPropsPolyfill, useCSSState, useGDS } from "../hooks/index.js";
import { cn, getCSSPropsAttributes, splitProps } from "../utils/index.js";
import { Button } from "./Button.js";
import { Keyboard } from './Keyboard.js';
import { SearchMeta } from "./Search.meta.js";
export function Search({ ref: passedRef, size, layout, placeholder = 'Search...', value: controlledValue, defaultValue, onChange, focusKey = '/', className, style, ...props }) {
    useGDS();
    const { rootProps, nestedProps } = splitProps(props);
    const inputRef = useRef(null);
    const inputPassedRef = useMergedRefs(inputRef, passedRef);
    const previousActiveElementRef = useRef(null);
    const [value, setValue] = useControlled(controlledValue, defaultValue ?? '', onChange);
    const [stateRef, state] = useCSSState({
        pointer: undefined,
        focus: undefined,
        blank: value === '',
        open: value !== '',
    });
    const [cssPropsPolyfillStateRef, cssPropsPolyfillAttributes, cssProps] = useCSSPropsPolyfill(SearchMeta, { size, layout }, { ref: stateRef, returnPropValues: { size, layout } });
    useEffect(() => {
        if (!focusKey)
            return;
        function handleKeyDown(event) {
            if (event.key !== focusKey)
                return;
            const input = inputRef.current;
            if (!input)
                return;
            // Don't focus if already focused on an interactive element
            const activeElement = document.activeElement;
            if (activeElement instanceof HTMLInputElement ||
                activeElement instanceof HTMLTextAreaElement ||
                (activeElement instanceof HTMLElement && activeElement.isContentEditable)) {
                return;
            }
            // Don't focus if the input has an inert/hidden ancestor
            if (input.closest('[inert], [data-base-ui-inert], [aria-hidden="true"]')) {
                return;
            }
            event.preventDefault();
            // Store the currently focused element before focusing the input
            previousActiveElementRef.current = activeElement instanceof HTMLElement ? activeElement : null;
            input.focus();
            input.select();
        }
        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [focusKey]);
    return (_jsx("div", { ref: cssPropsPolyfillStateRef, "data-size": cssProps.size, "data-layout": cssProps.layout, className: cn(`gds-search root-flex flex-col u:h-max u:max-w-full
        u:hover:state-hover
        u:active:state-active
        u:data-[layout=compact]:data-[size=medium]:min-w-10
        u:data-[layout=compact]:data-[size=small]:min-w-8
        u:has-nested-not-blank/search-ref:expose-open
        u:has-nested-blank/search-ref:expose-blank
        u:has-nested-focus-visible/search-ref:expose-focus
        u:has-nested-focus-visible/search-ref:expose-open
        u:has-nested-active/search-clear-button:state-focus`, className), ...state.exposedAttributes, ...state.polyfillAttributes, ...getCSSPropsAttributes(SearchMeta, { size, layout }, style), ...cssPropsPolyfillAttributes, ...rootProps, children: _jsxs("div", { className: `
          flex h-(--height) grow overflow-clip text-form-text duration-300
          @prop-size-small/search:[--height:--spacing(8)]
          @prop-size-small/search:[--padding:--spacing(2)]
          @prop-size-medium/search:[--height:--spacing(10)]
          @prop-size-medium/search:[--padding:--spacing(2.5)]
          @prop-layout-compact/search:transition-[width]
          @prop-layout-compact/search:@state-not-open/search:w-(--height)
          @prop-layout-compact/search:@prop-size-small/search:animate-[width-1_1ms]
          @prop-layout-compact/search:@prop-size-medium/search:animate-[width-2_1ms]
        `, children: [_jsx("div", { className: `
            h-full w-(--gds-search-input-width) grow border border-form-idle transition
            @state-hover/search:border-form-hover
            @state-focus/search:border-focus
            @state-active/search:transition-none
            @prop-size-small/search:rounded-6
            @prop-size-medium/search:rounded-8
          ` }), _jsx("input", { ref: inputPassedRef, type: "search", placeholder: placeholder, "aria-label": placeholder || 'Search', value: value, onChange: (event) => setValue(event.target.value), onKeyDown: (event) => {
                        nestedProps.onKeyDown?.(event);
                        if (event.defaultPrevented)
                            return;
                        if (event.key === 'Escape' && value === '') {
                            event.preventDefault();
                            inputRef.current?.blur();
                            // Restore focus to the previous element if it still exists in the DOM
                            if (previousActiveElementRef.current &&
                                document.contains(previousActiveElementRef.current)) {
                                previousActiveElementRef.current.focus();
                                previousActiveElementRef.current = null;
                            }
                        }
                    }, className: `
            nested/search-ref absolute end-0 top-0 size-full ps-(--padding) pe-(--height) outline-0
            @state-not-focus/search:@state-blank/search:ps-[calc(var(--height)+var(--padding))]
            @state-focus/search:placeholder:text-transparent
            @prop-size-small/search:text-12
            @prop-size-medium/search:text-14
            @prop-layout-compact/search:@state-not-open/search:w-screen
            @prop-layout-compact/search:@state-not-open/search:opacity-0
          `, ...nestedProps }), _jsx("div", { className: `
            pointer-events-none absolute inset-y-0 start-0 flex w-(--height) items-center justify-center
            border-e border-form-idle transition
            @state-hover/search:border-form-hover
            @state-focus/search:hidden
            @prop-layout-compact/search:@state-not-open/search:border-0
            @prop-layout-compact/search:@state-open/search:@state-not-blank/search:hidden
            @prop-layout-full/search:@state-not-blank/search:hidden
          `, children: _jsx(MagnifyingGlassIcon, { alt: "", className: `
              @prop-size-small/search:prop-size-3.5
              @prop-size-medium/search:prop-size-4
            ` }) }), _jsxs("div", { className: `
            pointer-events-none absolute inset-y-0 end-0 grid w-(--height) place-items-center
            *:col-span-full *:row-span-full
          `, children: [_jsx(Button, { variant: "tertiary", size: "xsmall", tooltip: null, tabIndex: -1, onClick: () => {
                                setValue('');
                                inputRef.current?.focus();
                            }, className: `
              nested/search-clear-button pointer-events-auto size-6 var-[radius=var(--radius-4)]
              @state-blank/search:hidden
              @prop-layout-compact/search:@state-not-open/search:hidden
            `, children: _jsx(XIcon, { alt: "Clear" }) }), focusKey ? (_jsx(Keyboard, { size: "large", className: `
                @state-not-blank/search:hidden
                @state-focus/search:hidden
                @prop-layout-compact/search:@state-not-open/search:hidden
              `, children: focusKey })) : null] })] }) }));
}
//# sourceMappingURL=Search.js.map