import { forwardRef } from "react";

/**
 * Dropdown - uses the Popover API + CSS Anchor Positioning; no JS needed for open/close.
 *
 * DropdownButton:
 *   ghost:     boolean - ghost variant
 *   size:      "sm" | "lg" | (default)
 *   popoverId: string - id of the paired <DropdownMenu> (default: "prs-dropdown-menu")
 *
 * DropdownMenu:
 *   id:       string - must match popoverId on <DropdownButton>
 *   position: "top" | "left" | "right" | (default bottom)
 *   align:    "end" | "center" | (default start)
 *   open:     boolean - force open state
 */

export const DropdownButton = forwardRef(function DropdownButton(
  { ghost = false, size, popoverId = "prs-dropdown-menu", className = "", children, ...props },
  ref
) {
  const classes = [
    "prs-btn",
    "prs-dropdown-btn",
    ghost && "prs-btn-ghost",
    size === "sm" && "prs-btn-sm",
    size === "lg" && "prs-btn-lg",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <button
      ref={ref}
      className={classes}
      popoverTarget={popoverId}
      style={{ anchorName: "--anchor-menu" }}
      {...props}
    >
      {children}
    </button>
  );
});

export const DropdownMenu = forwardRef(function DropdownMenu(
  { id = "prs-dropdown-menu", position, align, open = false, className = "", children, ...props },
  ref
) {
  const classes = [
    "prs-menu",
    "prs-dropdown-menu",
    open && "prs-dropdown-menu_open",
    position === "top" && "prs-dropdown-menu-top",
    position === "left" && "prs-dropdown-menu-left",
    position === "right" && "prs-dropdown-menu-right",
    align === "end" && "prs-dropdown-menu-end",
    align === "center" && "prs-dropdown-menu-center",
    className,
  ]
    .filter(Boolean)
    .join(" ");

  return (
    <div
      ref={ref}
      id={id}
      className={classes}
      style={{ positionAnchor: "--anchor-menu" }}
      popover="auto"
      {...props}
    >
      {children}
    </div>
  );
});

/**
 * Dropdown - wrapper container
 *
 * children: <DropdownButton> + <DropdownMenu>
 */
const Dropdown = forwardRef(function Dropdown(
  { className = "", children, ...props },
  ref
) {
  return (
    <div ref={ref} className={["prs-dropdown", className].filter(Boolean).join(" ")} {...props}>
      {children}
    </div>
  );
});

export default Dropdown;
