No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 

712 líneas
28 KiB

  1. 'use client';
  2. import { useState, useEffect, useCallback, useRef } from 'react';
  3. import { Card, MediaItem } from '@/types';
  4. const VIDEO_EXTENSIONS = 'mp4|m4v|webm|mov|qt|mkv|avi|divx|wmv|asf|flv|f4v|3gp|3gpp|3g2|mts|m2ts|ts|mpg|mpeg|vob|mxf|ogv|ogg';
  5. const isVideoUrl = (url: string) => new RegExp(`\\.(${VIDEO_EXTENSIONS})(\\?|$)`, 'i').test(url);
  6. function MediaCarousel({
  7. items,
  8. onMediaClick,
  9. }: {
  10. items: MediaItem[];
  11. onMediaClick?: (index: number) => void;
  12. }) {
  13. const [current, setCurrent] = useState(0);
  14. const [playing, setPlaying] = useState<Set<number>>(new Set());
  15. const touchStartX = useRef<number | null>(null);
  16. const videoRefs = useRef<Record<number, HTMLVideoElement | null>>({});
  17. const markPlaying = (i: number) => setPlaying(p => { const n = new Set(p); n.add(i); return n; });
  18. const markPaused = (i: number) => setPlaying(p => { const n = new Set(p); n.delete(i); return n; });
  19. const applyVolume = (v: HTMLVideoElement, item: MediaItem) => {
  20. v.muted = !!item.muted;
  21. };
  22. const togglePlay = (i: number) => {
  23. const v = videoRefs.current[i];
  24. if (!v) return;
  25. if (v.paused) {
  26. const item = items[i];
  27. if (item) applyVolume(v, item);
  28. v.play().catch(() => {});
  29. } else {
  30. v.pause();
  31. }
  32. };
  33. const prev = useCallback(() => setCurrent(i => (i - 1 + items.length) % items.length), [items.length]);
  34. const next = useCallback(() => setCurrent(i => (i + 1) % items.length), [items.length]);
  35. useEffect(() => {
  36. const onKey = (e: KeyboardEvent) => {
  37. if (e.key === 'ArrowLeft') prev();
  38. if (e.key === 'ArrowRight') next();
  39. };
  40. window.addEventListener('keydown', onKey);
  41. return () => window.removeEventListener('keydown', onKey);
  42. }, [prev, next]);
  43. useEffect(() => { setCurrent(0); }, [items]);
  44. // Pause non-current videos; autoplay current if flagged
  45. useEffect(() => {
  46. Object.entries(videoRefs.current).forEach(([key, vid]) => {
  47. if (!vid) return;
  48. const idx = parseInt(key, 10);
  49. if (idx !== current) { vid.pause(); return; }
  50. const item = items[idx];
  51. if (item && isVideoUrl(item.url) && item.autoplay) {
  52. applyVolume(vid, item);
  53. vid.play().catch(() => {
  54. // Browser blocked unmuted autoplay — fall back to muted.
  55. vid.muted = true;
  56. vid.play().catch(() => {});
  57. });
  58. }
  59. });
  60. }, [current, items]);
  61. const onTouchStart = (e: React.TouchEvent) => { touchStartX.current = e.touches[0].clientX; };
  62. const onTouchEnd = (e: React.TouchEvent) => {
  63. if (touchStartX.current === null) return;
  64. const delta = e.changedTouches[0].clientX - touchStartX.current;
  65. if (Math.abs(delta) > 50) delta < 0 ? next() : prev();
  66. touchStartX.current = null;
  67. };
  68. if (items.length === 0) {
  69. return <div className="h-72 w-full bg-gray-100 flex items-center justify-center text-gray-400 rounded-t-2xl">No Image</div>;
  70. }
  71. return (
  72. <div
  73. className="relative h-72 w-full bg-black overflow-hidden rounded-t-2xl select-none"
  74. onTouchStart={onTouchStart}
  75. onTouchEnd={onTouchEnd}
  76. >
  77. {items.map((item, i) => {
  78. const isActive = i === current;
  79. const video = isVideoUrl(item.url);
  80. return (
  81. <div
  82. key={item.url + i}
  83. className={`absolute inset-0 transition-opacity duration-300 ${isActive ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
  84. >
  85. {video ? (
  86. <div
  87. className="relative w-full h-full cursor-pointer"
  88. onClick={(e) => { e.stopPropagation(); togglePlay(i); }}
  89. >
  90. <video
  91. ref={el => { videoRefs.current[i] = el; }}
  92. src={item.url}
  93. className="w-full h-full object-contain bg-black pointer-events-none"
  94. playsInline
  95. preload="metadata"
  96. onLoadedMetadata={(e) => applyVolume(e.currentTarget, item)}
  97. onPlay={() => markPlaying(i)}
  98. onPause={() => markPaused(i)}
  99. onEnded={() => markPaused(i)}
  100. />
  101. {/* Custom play overlay (shown when paused) */}
  102. {!playing.has(i) && (
  103. <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
  104. <span className="bg-black/60 text-white w-20 h-20 rounded-full flex items-center justify-center text-4xl shadow-2xl pl-1">▶</span>
  105. </div>
  106. )}
  107. {/* Custom expand button */}
  108. <button
  109. onClick={(e) => { e.stopPropagation(); onMediaClick?.(i); }}
  110. className="absolute bottom-3 right-3 bg-black/60 hover:bg-black/80 text-white w-9 h-9 rounded-full flex items-center justify-center transition-colors shadow-lg z-10"
  111. title="Expand fullscreen"
  112. aria-label="Expand fullscreen"
  113. >
  114. <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
  115. <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />
  116. </svg>
  117. </button>
  118. </div>
  119. ) : (
  120. <img
  121. src={item.url}
  122. alt=""
  123. className="w-full h-full object-cover cursor-zoom-in"
  124. onClick={() => onMediaClick?.(i)}
  125. title="Click to view fullscreen"
  126. />
  127. )}
  128. </div>
  129. );
  130. })}
  131. {items.length > 1 && (
  132. <>
  133. <button
  134. onClick={(e) => { e.stopPropagation(); prev(); }}
  135. className="absolute left-3 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/80 text-white w-9 h-9 rounded-full flex items-center justify-center transition-colors shadow-lg z-10"
  136. aria-label="Previous"
  137. >‹</button>
  138. <button
  139. onClick={(e) => { e.stopPropagation(); next(); }}
  140. className="absolute right-3 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/80 text-white w-9 h-9 rounded-full flex items-center justify-center transition-colors shadow-lg z-10"
  141. aria-label="Next"
  142. >›</button>
  143. <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex items-center gap-1.5 z-10">
  144. {items.map((_, i) => (
  145. <button
  146. key={i}
  147. onClick={(e) => { e.stopPropagation(); setCurrent(i); }}
  148. className={`rounded-full transition-all duration-200 ${i === current ? 'w-5 h-2 bg-white' : 'w-2 h-2 bg-white/50 hover:bg-white/80'}`}
  149. aria-label={`Go to slide ${i + 1}`}
  150. />
  151. ))}
  152. </div>
  153. <div className="absolute top-3 left-3 bg-black/60 text-white text-xs font-semibold px-2 py-0.5 rounded-full z-10 flex items-center gap-1">
  154. <span>⊞</span>
  155. <span>{current + 1} / {items.length}</span>
  156. </div>
  157. </>
  158. )}
  159. </div>
  160. );
  161. }
  162. function FullscreenViewer({
  163. items,
  164. startIndex,
  165. onClose,
  166. }: {
  167. items: MediaItem[];
  168. startIndex: number;
  169. onClose: () => void;
  170. }) {
  171. const [current, setCurrent] = useState(startIndex);
  172. const [playing, setPlaying] = useState<Set<number>>(new Set());
  173. const [zoom, setZoom] = useState(1);
  174. const [pan, setPan] = useState({ x: 0, y: 0 });
  175. const touchStartX = useRef<number | null>(null);
  176. const videoRefs = useRef<Record<number, HTMLVideoElement | null>>({});
  177. const containerRef = useRef<HTMLDivElement | null>(null);
  178. const dragRef = useRef<{ sx: number; sy: number; px: number; py: number; moved: boolean } | null>(null);
  179. const markPlaying = (i: number) => setPlaying(p => { const n = new Set(p); n.add(i); return n; });
  180. const markPaused = (i: number) => setPlaying(p => { const n = new Set(p); n.delete(i); return n; });
  181. const applyVolume = (v: HTMLVideoElement, item: MediaItem) => {
  182. v.muted = !!item.muted;
  183. };
  184. const togglePlay = (i: number) => {
  185. const v = videoRefs.current[i];
  186. if (!v) return;
  187. if (v.paused) {
  188. const item = items[i];
  189. if (item) applyVolume(v, item);
  190. v.play().catch(() => {});
  191. } else {
  192. v.pause();
  193. }
  194. };
  195. const onImgClick = (e: React.MouseEvent<HTMLImageElement>) => {
  196. if (dragRef.current?.moved) {
  197. dragRef.current = null;
  198. return;
  199. }
  200. dragRef.current = null;
  201. if (zoom > 1) {
  202. setZoom(1);
  203. setPan({ x: 0, y: 0 });
  204. } else {
  205. const r = e.currentTarget.getBoundingClientRect();
  206. const ox = e.clientX - r.left - r.width / 2;
  207. const oy = e.clientY - r.top - r.height / 2;
  208. setZoom(2);
  209. setPan({ x: -2 * ox, y: -2 * oy });
  210. }
  211. };
  212. const onImgPointerDown = (e: React.PointerEvent<HTMLImageElement>) => {
  213. if (zoom <= 1) return;
  214. dragRef.current = { sx: e.clientX, sy: e.clientY, px: pan.x, py: pan.y, moved: false };
  215. e.currentTarget.setPointerCapture?.(e.pointerId);
  216. };
  217. const onImgPointerMove = (e: React.PointerEvent<HTMLImageElement>) => {
  218. if (!dragRef.current) return;
  219. const dx = e.clientX - dragRef.current.sx;
  220. const dy = e.clientY - dragRef.current.sy;
  221. if (Math.hypot(dx, dy) > 4) dragRef.current.moved = true;
  222. setPan({ x: dragRef.current.px + dx, y: dragRef.current.py + dy });
  223. };
  224. const prev = useCallback(() => setCurrent(i => (i - 1 + items.length) % items.length), [items.length]);
  225. const next = useCallback(() => setCurrent(i => (i + 1) % items.length), [items.length]);
  226. useEffect(() => {
  227. const onKey = (e: KeyboardEvent) => {
  228. if (e.key === 'Escape') onClose();
  229. else if (e.key === 'ArrowLeft') prev();
  230. else if (e.key === 'ArrowRight') next();
  231. };
  232. window.addEventListener('keydown', onKey);
  233. return () => window.removeEventListener('keydown', onKey);
  234. }, [prev, next, onClose]);
  235. // Pause non-current videos in fullscreen
  236. useEffect(() => {
  237. Object.entries(videoRefs.current).forEach(([key, vid]) => {
  238. if (!vid) return;
  239. const idx = parseInt(key, 10);
  240. if (idx !== current) { vid.pause(); return; }
  241. const item = items[idx];
  242. if (item && isVideoUrl(item.url) && item.autoplay) {
  243. applyVolume(vid, item);
  244. vid.play().catch(() => {
  245. vid.muted = true;
  246. vid.play().catch(() => {});
  247. });
  248. }
  249. });
  250. }, [current, items]);
  251. // Reset zoom whenever the active slide changes
  252. useEffect(() => {
  253. setZoom(1);
  254. setPan({ x: 0, y: 0 });
  255. }, [current]);
  256. // Wheel zoom (only on images). preventDefault requires passive: false → manual listener.
  257. useEffect(() => {
  258. const el = containerRef.current;
  259. if (!el) return;
  260. const onWheel = (e: WheelEvent) => {
  261. const item = items[current];
  262. if (!item || isVideoUrl(item.url)) return;
  263. e.preventDefault();
  264. const factor = 1 - e.deltaY * 0.001;
  265. setZoom(prev => {
  266. const next = Math.max(1, Math.min(4, prev * factor));
  267. if (next === 1) setPan({ x: 0, y: 0 });
  268. return next;
  269. });
  270. };
  271. el.addEventListener('wheel', onWheel, { passive: false });
  272. return () => el.removeEventListener('wheel', onWheel);
  273. }, [current, items]);
  274. const onTouchStart = (e: React.TouchEvent) => {
  275. if (zoom > 1) return; // pan via pointer events instead
  276. touchStartX.current = e.touches[0].clientX;
  277. };
  278. const onTouchEnd = (e: React.TouchEvent) => {
  279. if (zoom > 1) return;
  280. if (touchStartX.current === null) return;
  281. const delta = e.changedTouches[0].clientX - touchStartX.current;
  282. if (Math.abs(delta) > 50) delta < 0 ? next() : prev();
  283. touchStartX.current = null;
  284. };
  285. return (
  286. <div
  287. ref={containerRef}
  288. className="fixed inset-0 z-[100] bg-black/95 flex items-center justify-center select-none animate-in fade-in duration-200"
  289. onTouchStart={onTouchStart}
  290. onTouchEnd={onTouchEnd}
  291. >
  292. {/* Media — full resolution, contained */}
  293. {items.map((item, i) => {
  294. const isActive = i === current;
  295. const video = isVideoUrl(item.url);
  296. return (
  297. <div
  298. key={item.url + i}
  299. className={`absolute inset-0 flex items-center justify-center p-4 pb-28 transition-opacity duration-200 ${isActive ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}
  300. >
  301. {video ? (
  302. <div
  303. className="relative w-full h-full flex items-center justify-center cursor-pointer"
  304. onClick={(e) => { e.stopPropagation(); togglePlay(i); }}
  305. >
  306. <video
  307. ref={el => { videoRefs.current[i] = el; }}
  308. src={item.url}
  309. className="max-w-full max-h-full object-contain pointer-events-none"
  310. playsInline
  311. preload="metadata"
  312. onLoadedMetadata={(e) => applyVolume(e.currentTarget, item)}
  313. onPlay={() => markPlaying(i)}
  314. onPause={() => markPaused(i)}
  315. onEnded={() => markPaused(i)}
  316. />
  317. {!playing.has(i) && (
  318. <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
  319. <span className="bg-black/60 text-white w-24 h-24 rounded-full flex items-center justify-center text-5xl shadow-2xl pl-1">▶</span>
  320. </div>
  321. )}
  322. </div>
  323. ) : (
  324. <img
  325. src={item.url}
  326. alt=""
  327. className="max-w-full max-h-full object-contain"
  328. draggable={false}
  329. style={isActive ? {
  330. transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
  331. cursor: zoom > 1 ? 'grab' : 'zoom-in',
  332. transition: dragRef.current ? 'none' : 'transform 0.2s',
  333. touchAction: zoom > 1 ? 'none' : 'auto',
  334. willChange: 'transform',
  335. } : undefined}
  336. onClick={isActive ? onImgClick : undefined}
  337. onPointerDown={isActive ? onImgPointerDown : undefined}
  338. onPointerMove={isActive ? onImgPointerMove : undefined}
  339. />
  340. )}
  341. </div>
  342. );
  343. })}
  344. {/* Counter — top center */}
  345. {items.length > 1 && (
  346. <div className="absolute top-4 left-1/2 -translate-x-1/2 bg-black/60 text-white text-sm font-semibold px-3 py-1 rounded-full z-20">
  347. {current + 1} / {items.length}
  348. </div>
  349. )}
  350. {/* Side arrows */}
  351. {items.length > 1 && (
  352. <>
  353. <button
  354. onClick={(e) => { e.stopPropagation(); prev(); }}
  355. className="absolute left-4 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/80 text-white w-12 h-12 rounded-full flex items-center justify-center text-2xl shadow-lg z-20"
  356. aria-label="Previous"
  357. >‹</button>
  358. <button
  359. onClick={(e) => { e.stopPropagation(); next(); }}
  360. className="absolute right-4 top-1/2 -translate-y-1/2 bg-black/50 hover:bg-black/80 text-white w-12 h-12 rounded-full flex items-center justify-center text-2xl shadow-lg z-20"
  361. aria-label="Next"
  362. >›</button>
  363. </>
  364. )}
  365. {/* Close button — bottom center, ABOVE the dots */}
  366. <button
  367. onClick={onClose}
  368. className="absolute bottom-12 left-1/2 -translate-x-1/2 bg-white/90 hover:bg-white text-black px-6 py-2.5 rounded-full font-semibold shadow-2xl flex items-center gap-2 z-20 transition-transform hover:scale-105"
  369. aria-label="Close fullscreen"
  370. >
  371. <span className="text-lg leading-none">✕</span>
  372. <span>Close</span>
  373. </button>
  374. {/* Dots — at the very bottom */}
  375. {items.length > 1 && (
  376. <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex items-center gap-1.5 z-20">
  377. {items.map((_, i) => (
  378. <button
  379. key={i}
  380. onClick={(e) => { e.stopPropagation(); setCurrent(i); }}
  381. className={`rounded-full transition-all duration-200 ${i === current ? 'w-6 h-2 bg-white' : 'w-2 h-2 bg-white/50 hover:bg-white/80'}`}
  382. aria-label={`Go to slide ${i + 1}`}
  383. />
  384. ))}
  385. </div>
  386. )}
  387. </div>
  388. );
  389. }
  390. function FlipBook({ pages, onClose }: { pages: string[]; onClose: () => void }) {
  391. const containerRef = useRef<HTMLDivElement>(null);
  392. const flipRef = useRef<import('@/lib/page-flip').PageFlip | null>(null);
  393. const [currentPage, setCurrentPage] = useState(0);
  394. const [pageCount, setPageCount] = useState(pages.length);
  395. useEffect(() => {
  396. if (!containerRef.current || pages.length === 0) return;
  397. let cancelled = false;
  398. // page-flip's destroy() removes its own block from the DOM. Give it a child
  399. // div we own so React's managed container stays intact across StrictMode cycles.
  400. const block = document.createElement('div');
  401. block.style.width = '100%';
  402. block.style.height = '100%';
  403. containerRef.current.appendChild(block);
  404. // HTML mode: each page is a div with an <img> using object-fit:contain so
  405. // mixed aspect ratios get letterboxed with white margins (like a real book
  406. // page) instead of being stretched to fill the slot.
  407. const pageElements = pages.map((url) => {
  408. const page = document.createElement('div');
  409. page.style.cssText = 'background:#ffffff;width:100%;height:100%;overflow:hidden;display:flex;align-items:center;justify-content:center;';
  410. const img = document.createElement('img');
  411. img.src = url;
  412. img.draggable = false;
  413. img.style.cssText = 'max-width:100%;max-height:100%;object-fit:contain;display:block;pointer-events:none;user-select:none;';
  414. page.appendChild(img);
  415. return page;
  416. });
  417. import('@/lib/page-flip').then(({ PageFlip }) => {
  418. if (cancelled) return;
  419. const flip = new PageFlip(block, {
  420. width: 550,
  421. height: 733,
  422. size: 'stretch',
  423. minWidth: 315,
  424. maxWidth: 1400,
  425. minHeight: 420,
  426. maxHeight: 900,
  427. drawShadow: true,
  428. flippingTime: 800,
  429. usePortrait: true,
  430. maxShadowOpacity: 0.5,
  431. showCover: true,
  432. mobileScrollSupport: false,
  433. useMouseEvents: true,
  434. swipeDistance: 30,
  435. showPageCorners: true,
  436. disableFlipByClick: false,
  437. });
  438. flip.on('flip', (e) => {
  439. const newPage = typeof e.data === 'number' ? e.data : 0;
  440. setCurrentPage(newPage);
  441. });
  442. flip.on('init', () => {
  443. setPageCount(flip.getPageCount());
  444. });
  445. flip.loadFromHTML(pageElements);
  446. flipRef.current = flip;
  447. }).catch(() => {});
  448. return () => {
  449. cancelled = true;
  450. if (flipRef.current) {
  451. try { flipRef.current.destroy(); } catch {}
  452. flipRef.current = null;
  453. }
  454. try { block.remove(); } catch {}
  455. };
  456. // eslint-disable-next-line react-hooks/exhaustive-deps
  457. }, []);
  458. const goNext = useCallback(() => flipRef.current?.flipNext(), []);
  459. const goPrev = useCallback(() => flipRef.current?.flipPrev(), []);
  460. useEffect(() => {
  461. const onKey = (e: KeyboardEvent) => {
  462. if (e.key === 'Escape') onClose();
  463. else if (e.key === 'ArrowRight') goNext();
  464. else if (e.key === 'ArrowLeft') goPrev();
  465. };
  466. window.addEventListener('keydown', onKey);
  467. return () => window.removeEventListener('keydown', onKey);
  468. }, [onClose, goNext, goPrev]);
  469. return (
  470. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/95 select-none">
  471. <button
  472. onClick={onClose}
  473. className="absolute top-4 right-4 bg-white/10 hover:bg-white/25 text-white w-11 h-11 flex items-center justify-center rounded-full text-xl z-30 transition-colors"
  474. title="Chiudi"
  475. aria-label="Chiudi"
  476. >✕</button>
  477. <div
  478. ref={containerRef}
  479. style={{
  480. width: 'min(95vw, 1400px)',
  481. height: 'min(85vh, 900px)',
  482. }}
  483. />
  484. <button
  485. onClick={goPrev}
  486. className="absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/25 text-white w-14 h-14 flex items-center justify-center rounded-full text-3xl z-30 transition-colors"
  487. title="Pagina precedente"
  488. aria-label="Pagina precedente"
  489. >‹</button>
  490. <button
  491. onClick={goNext}
  492. className="absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/25 text-white w-14 h-14 flex items-center justify-center rounded-full text-3xl z-30 transition-colors"
  493. title="Pagina successiva"
  494. aria-label="Pagina successiva"
  495. >›</button>
  496. <div className="absolute bottom-5 left-1/2 -translate-x-1/2 bg-white/15 text-white px-4 py-1.5 rounded-full text-sm font-medium z-30">
  497. {pageCount === 0 ? 'Nessuna pagina' : `${currentPage + 1} / ${pageCount}`}
  498. </div>
  499. </div>
  500. );
  501. }
  502. export default function PublicGrid({ cards, maxCols = 5 }: { cards: Card[], maxCols?: number }) {
  503. const [activeCard, setActiveCard] = useState<Card | null>(null);
  504. const [fullscreenIndex, setFullscreenIndex] = useState<number | null>(null);
  505. useEffect(() => {
  506. if (activeCard || fullscreenIndex !== null) document.body.style.overflow = 'hidden';
  507. else document.body.style.overflow = 'unset';
  508. return () => { document.body.style.overflow = 'unset'; };
  509. }, [activeCard, fullscreenIndex]);
  510. const gridClasses: Record<number, string> = {
  511. 3: 'xl:grid-cols-3 lg:grid-cols-3 md:grid-cols-2 grid-cols-1',
  512. 4: 'xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2 grid-cols-1',
  513. 5: 'xl:grid-cols-5 lg:grid-cols-4 md:grid-cols-3 grid-cols-1',
  514. 6: 'xl:grid-cols-6 lg:grid-cols-4 md:grid-cols-3 grid-cols-2',
  515. 7: 'xl:grid-cols-7 lg:grid-cols-5 md:grid-cols-4 grid-cols-2',
  516. 8: 'xl:grid-cols-8 lg:grid-cols-6 md:grid-cols-4 grid-cols-2',
  517. };
  518. const activeGridClass = gridClasses[maxCols] || gridClasses[5];
  519. const carouselItems: MediaItem[] = activeCard
  520. ? [
  521. ...(activeCard.imageUrl && !activeCard.skipPreview ? [{ url: activeCard.imageUrl }] : []),
  522. ...(activeCard.extraMedia || []),
  523. ]
  524. : [];
  525. return (
  526. <>
  527. <div className={`grid gap-4 ${activeGridClass}`}>
  528. {cards.map((card) => {
  529. const galleryCount = card.extraMedia?.length || 0;
  530. const isExternalLink = card.cardType === 'EXTERNAL_LINK';
  531. // Fall back to the first gallery item when no explicit cover is set.
  532. const previewUrl = card.imageUrl || card.extraMedia?.[0]?.url || '';
  533. const previewIsVideo = !!previewUrl && isVideoUrl(previewUrl);
  534. return (
  535. <div
  536. key={card.id}
  537. onClick={() => {
  538. // EXTERNAL_LINK + redirectOnClick: salta il modale e apri direttamente l'URL
  539. if (card.cardType === 'EXTERNAL_LINK' && card.redirectOnClick) {
  540. const url = card.actionUrl || card.shortDescription;
  541. if (url) {
  542. window.open(url, '_blank', 'noopener,noreferrer');
  543. return;
  544. }
  545. }
  546. setActiveCard(card);
  547. if (card.cardType !== 'BOOK' && card.autoFullscreen) setFullscreenIndex(0);
  548. }}
  549. className="group relative cursor-pointer overflow-hidden rounded-xl shadow-md aspect-square bg-gray-200 transition-all duration-300 hover:shadow-xl hover:-translate-y-1"
  550. >
  551. {previewUrl ? (
  552. previewIsVideo ? (
  553. <video
  554. src={previewUrl}
  555. className="absolute inset-0 w-full h-full object-cover pointer-events-none"
  556. muted
  557. playsInline
  558. preload="metadata"
  559. />
  560. ) : (
  561. <img src={previewUrl} alt={card.title} className="absolute inset-0 w-full h-full object-cover" />
  562. )
  563. ) : (
  564. <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-blue-100 to-gray-200 text-gray-400">No Image</div>
  565. )}
  566. {isExternalLink ? (
  567. <div
  568. className="absolute top-2 left-2 bg-black/60 text-white text-xs font-bold px-2 py-0.5 rounded-full flex items-center justify-center z-10 leading-none"
  569. title="External Link"
  570. aria-label="External Link"
  571. >
  572. L
  573. </div>
  574. ) : galleryCount > 0 ? (
  575. <div className="absolute top-2 left-2 bg-black/60 text-white text-xs font-semibold px-1.5 py-0.5 rounded-full flex items-center gap-1 z-10">
  576. <span>⊞</span>
  577. <span>{galleryCount}</span>
  578. </div>
  579. ) : null}
  580. <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/30 to-transparent flex flex-col justify-end p-5 text-white">
  581. <h3 className="text-xl font-bold drop-shadow-md">{card.title}</h3>
  582. <p className="text-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300 line-clamp-2 mt-1 text-gray-200 drop-shadow">
  583. {card.shortDescription}
  584. </p>
  585. </div>
  586. </div>
  587. );
  588. })}
  589. </div>
  590. {activeCard && activeCard.cardType === 'BOOK' && (
  591. <FlipBook
  592. pages={(activeCard.extraMedia || []).map(m => m.url)}
  593. onClose={() => setActiveCard(null)}
  594. />
  595. )}
  596. {activeCard && activeCard.cardType !== 'BOOK' && fullscreenIndex === null && (
  597. <div
  598. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-md p-4"
  599. onClick={() => setActiveCard(null)}
  600. >
  601. <div
  602. className="bg-white rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto shadow-2xl animate-in fade-in zoom-in-95 duration-200"
  603. onClick={(e) => e.stopPropagation()}
  604. >
  605. <div className="relative">
  606. <MediaCarousel
  607. items={carouselItems}
  608. onMediaClick={(i) => setFullscreenIndex(i)}
  609. />
  610. <button
  611. onClick={() => setActiveCard(null)}
  612. className="absolute top-4 right-4 bg-black/60 text-white w-10 h-10 flex items-center justify-center rounded-full hover:bg-black hover:scale-110 transition-all shadow-lg z-20"
  613. title="Close"
  614. >✕</button>
  615. </div>
  616. {(activeCard.title || activeCard.shortDescription || activeCard.fullContent || activeCard.actionUrl) && (
  617. <div className="p-8">
  618. {activeCard.title && (
  619. <h2 className={`text-3xl font-bold text-gray-900 ${(activeCard.shortDescription || activeCard.fullContent || activeCard.actionUrl) ? 'mb-4' : ''}`}>
  620. {activeCard.title}
  621. </h2>
  622. )}
  623. {activeCard.cardType === 'EXTERNAL_LINK' && (activeCard.actionUrl || activeCard.shortDescription) ? (
  624. <a
  625. href={activeCard.actionUrl || activeCard.shortDescription}
  626. target="_blank"
  627. rel="noopener noreferrer"
  628. className="inline-flex items-center gap-2 text-blue-600 hover:text-blue-800 underline break-all text-lg font-medium"
  629. >
  630. <span>{activeCard.shortDescription || activeCard.actionUrl}</span>
  631. <span aria-hidden>↗</span>
  632. </a>
  633. ) : activeCard.fullContent ? (
  634. <div className="prose max-w-none text-gray-700" dangerouslySetInnerHTML={{ __html: activeCard.fullContent }} />
  635. ) : activeCard.shortDescription ? (
  636. <p className="text-gray-500 italic text-lg">{activeCard.shortDescription}</p>
  637. ) : null}
  638. </div>
  639. )}
  640. </div>
  641. </div>
  642. )}
  643. {fullscreenIndex !== null && activeCard && (
  644. <FullscreenViewer
  645. items={carouselItems}
  646. startIndex={fullscreenIndex}
  647. onClose={() => {
  648. setFullscreenIndex(null);
  649. setActiveCard(null);
  650. }}
  651. />
  652. )}
  653. </>
  654. );
  655. }