// packages/core/src/components/popover/popover-trigger.tsx
import type { Component, JSX } from "solid-js";
import { mergeProps, splitProps } from "solid-js";
import { Dynamic } from "solid-js/web";
import { useInternalPopoverContext } from "./popover-context";

export interface PopoverTriggerProps
  extends Omit<JSX.HTMLAttributes<HTMLButtonElement>, "children"> {
  /** Render as a different element or component. */
  as?: string | Component;
  children?: JSX.Element | ((props: JSX.HTMLAttributes<HTMLElement>) => JSX.Element);
}

/**
 * Toggles the popover when clicked. Supports polymorphic rendering via `as`
 * and children-as-function for full control.
 */
export function PopoverTrigger(props: PopoverTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["as", "children", "onClick"]);
  const ctx = useInternalPopoverContext();

  const handleClick: JSX.EventHandler<HTMLElement, MouseEvent> = (e) => {
    if (typeof local.onClick === "function")
      local.onClick(e as MouseEvent & { currentTarget: HTMLButtonElement; target: Element });
    ctx.setOpen(!ctx.isOpen());
  };

  const triggerProps = mergeProps(rest, {
    get "aria-haspopup"() {
      return "dialog" as const;
    },
    get "aria-expanded"() {
      return ctx.isOpen();
    },
    get "aria-controls"() {
      return ctx.contentId();
    },
    get "data-state"() {
      return ctx.isOpen() ? "open" : "closed";
    },
    onClick: handleClick,
  });

  if (typeof local.children === "function") {
    return <>{local.children(triggerProps as JSX.HTMLAttributes<HTMLElement>)}</>;
  }

  return (
    <Dynamic
      component={local.as ?? "button"}
      ref={(el: HTMLElement) => ctx.setTriggerRef(el)}
      {...triggerProps}
    >
      {local.children}
    </Dynamic>
  );
}
