'use client';

import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';

export const Dialog = DialogPrimitive.Root;
export const DialogTrigger = DialogPrimitive.Trigger;

export function DialogContent({
  className,
  placement = 'center',
  children,
  style,
  ...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
  placement?: 'center' | 'upper';
}) {
  const placementStyle: React.CSSProperties =
    placement === 'upper'
      ? {
          top: 'max(1.5rem, 10vh)',
          left: '50%',
          transform: 'translateX(-50%)',
          margin: 0
        }
      : {
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          margin: 0
        };

  const overlayZ = placement === 'upper' ? 'z-[300]' : 'z-[200]';
  const contentZ = placement === 'upper' ? 'z-[301]' : 'z-[201]';

  return (
    <DialogPrimitive.Portal>
      <DialogPrimitive.Overlay className={cn('fixed inset-0 bg-black/50 backdrop-blur-[1px]', overlayZ)} />
      <DialogPrimitive.Content
        className={cn('fixed w-[min(92vw,520px)] rounded-[28px] bg-white p-6 shadow-2xl', contentZ, className)}
        style={{ ...placementStyle, ...style }}
        {...props}
      >
        {children}
        <DialogPrimitive.Close className="absolute right-5 top-5 rounded-full p-1 hover:bg-[#f4f5f8]" aria-label="Закрыть">
          <X className="h-4 w-4" />
        </DialogPrimitive.Close>
      </DialogPrimitive.Content>
    </DialogPrimitive.Portal>
  );
}

export function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
  return <div className={cn('mb-5 flex flex-col gap-1', className)} {...props} />;
}

export function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
  return <DialogPrimitive.Title className={cn('text-xl font-semibold', className)} {...props} />;
}
