'use client';

import { X } from 'lucide-react';
import { useEffect } from 'react';
import { createPortal } from 'react-dom';

/**
 * Full-bleed preview for an image attachment.
 *
 * Deliberately local and hand-rolled rather than `@edr/ui-common`'s FileViewer:
 * that component is Mantine-based and this app mounts no MantineProvider, so
 * importing it would throw at runtime. All we need here is a backdrop and an
 * `<img>`.
 *
 * Portalled to `document.body` because its call site is nested inside the chat
 * panel, which is `overflow-hidden` and lives in the launcher's `z-30` stacking
 * context. Rendered in place, the z-[120] below would be trapped in that context
 * and mean nothing; portalled, it genuinely reaches the modal tier and paints
 * over the chat that opened it.
 *
 * Only ever rendered for image mime types: `<img>` cannot execute its source,
 * whereas navigating to or framing an attachment could. SVG is excluded from the
 * allowed upload types upstream for exactly this reason.
 */
export function ImagePreview({
  src,
  alt,
  onClose,
}: {
  src: string;
  alt: string;
  onClose: () => void;
}) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return createPortal(
    <div
      onClick={onClose}
      role="dialog"
      aria-modal="true"
      aria-label={alt}
      className="fixed inset-0 z-[120] flex items-center justify-center bg-black/80 p-6"
    >
      <button
        onClick={onClose}
        aria-label="Close preview"
        className="absolute right-4 top-4 rounded-full bg-white/10 p-2 text-white transition hover:bg-white/20"
      >
        <X size={20} />
      </button>
      {/* Stop the backdrop's close handler firing when the image itself is
          clicked — panning a zoomed screenshot shouldn't dismiss it. */}
      {/* Plain <img>: `src` is a blob: object URL fetched through the
          authenticated client, which next/image cannot optimize. */}
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src={src}
        alt={alt}
        onClick={(e) => e.stopPropagation()}
        className="max-h-full max-w-full rounded-lg object-contain shadow-2xl"
      />
    </div>,
    document.body,
  );
}

export default ImagePreview;
