import type { JSX } from "solid-js";
import { Show, createEffect, onCleanup, splitProps } from "solid-js";
import { createDismiss } from "../../utilities/dismiss/create-dismiss";
import { useInternalComboboxContext } from "./combobox-context";

export interface ComboboxContentProps extends JSX.HTMLAttributes<HTMLDivElement> {
  /** Keep mounted when closed. @default false */
  forceMount?: boolean | undefined;
  children?: JSX.Element | undefined;
}

/**
 * Floating dropdown content for Combobox. Contains the listbox with items.
 * Handles dismiss on outside click; Escape is handled by the input.
 */
export function ComboboxContent(props: ComboboxContentProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "forceMount"]);
  const ctx = useInternalComboboxContext();

  const dismiss = createDismiss({
    getContainer: () => ctx.contentRef(),
    onDismiss: () => ctx.close(),
    dismissOnEscape: false,
  });

  createEffect(() => {
    if (ctx.isOpen()) {
      dismiss.attach();
    } else {
      dismiss.detach();
    }
    onCleanup(() => dismiss.detach());
  });

  return (
    <Show when={local.forceMount || ctx.isOpen()}>
      <div
        ref={(el) => ctx.setContentRef(el)}
        id={ctx.contentId}
        role="listbox"
        aria-orientation="vertical"
        aria-labelledby={ctx.inputId}
        data-state={ctx.isOpen() ? "open" : "closed"}
        style={ctx.floatingStyle()}
        onPointerLeave={() => ctx.navigation.clearHighlight()}
        {...rest}
      >
        {local.children}
      </div>
    </Show>
  );
}
