'use client';

import * as React from 'react';

const Popover = ({ children, open, onOpenChange }: any) => {
  return (
    <div className="relative">
      {React.Children.map(children, child => React.cloneElement(child, { open, onOpenChange }))}
    </div>
  );
};

const PopoverTrigger = ({ children, asChild, onOpenChange, open }: any) => {
  if (asChild) {
    return React.cloneElement(children, {
      onClick: () => onOpenChange?.(!open),
    });
  }
  return (
    <button onClick={() => onOpenChange?.(!open)} type="button">
      {children}
    </button>
  );
};

const PopoverContent = React.forwardRef<HTMLDivElement, any>(
  ({ className, children, open, align = 'center', ...props }, ref) => {
    if (!open) return null;

    const alignClass = {
      start: 'left-0',
      center: 'left-1/2 -translate-x-1/2',
      end: 'right-0',
    }[align];

    return (
      <div
        ref={ref}
        className={`absolute z-50 mt-2 w-full min-w-[8rem] overflow-hidden rounded-md border bg-popover p-4 text-popover-foreground shadow-md ${alignClass} ${className || ''}`}
        {...props}
      >
        {children}
      </div>
    );
  }
);
PopoverContent.displayName = 'PopoverContent';

export { Popover, PopoverTrigger, PopoverContent };
