import * as PopoverPrimitive from "@radix-ui/react-popover";
import { forwardRef, type ComponentPropsWithoutRef, type ElementRef } from "react";

import { popoverContentVariants } from "./popover.variants";
import { cn } from "../lib/cn";
import type { VariantProps } from "../lib/cva";
import { createDataAttributes, createSlot } from "../lib/contracts";

export const Popover = PopoverPrimitive.Root;
export const PopoverTrigger = PopoverPrimitive.Trigger;
export const PopoverAnchor = PopoverPrimitive.Anchor;
export const PopoverPortal = PopoverPrimitive.Portal;
export const PopoverClose = PopoverPrimitive.Close;

export type PopoverContentProps = ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> &
  VariantProps<typeof popoverContentVariants>;

export const PopoverContent = forwardRef<
  ElementRef<typeof PopoverPrimitive.Content>,
  PopoverContentProps
>(function PopoverContent(
  { className, sideOffset = 10, size, ...props },
  ref
) {
  return (
    <PopoverPortal>
      <PopoverPrimitive.Content
        {...props}
        {...createSlot("content")}
        {...createDataAttributes({ size })}
        className={cn(popoverContentVariants({ size }), className)}
        ref={ref}
        sideOffset={sideOffset}
      />
    </PopoverPortal>
  );
});

export const PopoverArrow = forwardRef<
  ElementRef<typeof PopoverPrimitive.Arrow>,
  ComponentPropsWithoutRef<typeof PopoverPrimitive.Arrow>
>(function PopoverArrow({ className, ...props }, ref) {
  return (
    <PopoverPrimitive.Arrow
      {...props}
      {...createSlot("arrow")}
      className={cn("fill-[var(--color-card)]", className)}
      ref={ref}
    />
  );
});
