"use client";

import { useEffect, useState } from "react";

type GalleryItem = { source: string; caption: string };

export default function PostGallery({ items }: { items: GalleryItem[] }) {
  const [selected, setSelected] = useState<GalleryItem | null>(null);
  useEffect(() => {
    if (!selected) return;
    const closeOnEscape = (event: KeyboardEvent) => { if (event.key === "Escape") setSelected(null); };
    document.addEventListener("keydown", closeOnEscape); document.body.style.overflow = "hidden";
    return () => { document.removeEventListener("keydown", closeOnEscape); document.body.style.overflow = ""; };
  }, [selected]);
  const source = (item: GalleryItem) => item.source.startsWith("/") ? item.source : "/hero-rehab.png";
  const blockImageAction = (event: React.SyntheticEvent) => event.preventDefault();
  return <>
    <div className="post-gallery">{items.map((item) => <figure key={item.source}><button type="button" className="gallery-image-button" onClick={() => setSelected(item)} aria-label={`${item.caption} 확대 보기`}><img src={source(item)} alt={item.caption} draggable={false} onContextMenu={blockImageAction} onDragStart={blockImageAction} /></button><figcaption>{item.caption}</figcaption></figure>)}</div>
    {selected && <div className="image-modal" role="dialog" aria-modal="true" aria-label={`${selected.caption} 확대 보기`} onClick={() => setSelected(null)}><div className="image-modal-content" onClick={(event) => event.stopPropagation()}><button type="button" className="image-modal-close" onClick={() => setSelected(null)} aria-label="이미지 닫기">×</button><img src={source(selected)} alt={selected.caption} draggable={false} onContextMenu={blockImageAction} onDragStart={blockImageAction} /><p>{selected.caption}</p></div></div>}
  </>;
}
