'use client';

/**
 * Image block — a thumbnail that opens a fullscreen zoom/pan lightbox on
 * click (Telegram / WhatsApp style). The outer frame (radius / border /
 * shadow) is owned by the shared `BLOCK_SURFACE` in MessageBlocks; here we
 * only render the image and the lightbox dialog.
 */

import { useState } from 'react';

import { Dialog, DialogContent, DialogTitle } from '@djangocfg/ui-core/components';

import { LazyImageViewer } from '../../../../media/ImageViewer/lazy';
import type { ImageBlock } from '../../../types/block';
import type { BlockRendererProps } from './types';

export default function ImageBlockRenderer({ block }: BlockRendererProps<ImageBlock>) {
  const [open, setOpen] = useState(false);
  const alt = block.alt ?? 'image';

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        aria-label={`Open image${block.alt ? `: ${block.alt}` : ''}`}
        className="block w-full cursor-zoom-in transition-opacity hover:opacity-95 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
      >
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src={block.src} alt={alt} className="max-h-96 w-full object-cover" />
      </button>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="h-[90vh] w-[90vw] max-w-[1400px] overflow-hidden p-0 sm:rounded-xl">
          <DialogTitle className="sr-only">{alt}</DialogTitle>
          {open && (
            <LazyImageViewer
              images={[{ file: { name: alt, path: block.src }, src: block.src }]}
              inDialog
              autoFocus
            />
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}
