You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

750 rivejä
31 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 [spread, setSpread] = useState(0);
  392. const [flipping, setFlipping] = useState<'forward' | 'backward' | null>(null);
  393. const dragStartX = useRef<number | null>(null);
  394. const totalSpreads = Math.max(1, Math.ceil(pages.length / 2));
  395. const getPage = (i: number) => (i >= 0 && i < pages.length ? pages[i] : '');
  396. const leftIdx = spread * 2;
  397. const rightIdx = spread * 2 + 1;
  398. const nextLeftIdx = (spread + 1) * 2;
  399. const nextRightIdx = (spread + 1) * 2 + 1;
  400. const prevLeftIdx = (spread - 1) * 2;
  401. const prevRightIdx = (spread - 1) * 2 + 1;
  402. const goNext = useCallback(() => {
  403. if (flipping !== null || spread >= totalSpreads - 1) return;
  404. setFlipping('forward');
  405. window.setTimeout(() => { setSpread(s => s + 1); setFlipping(null); }, 700);
  406. }, [flipping, spread, totalSpreads]);
  407. const goPrev = useCallback(() => {
  408. if (flipping !== null || spread <= 0) return;
  409. setFlipping('backward');
  410. window.setTimeout(() => { setSpread(s => s - 1); setFlipping(null); }, 700);
  411. }, [flipping, spread]);
  412. useEffect(() => {
  413. const onKey = (e: KeyboardEvent) => {
  414. if (e.key === 'Escape') onClose();
  415. else if (e.key === 'ArrowRight') goNext();
  416. else if (e.key === 'ArrowLeft') goPrev();
  417. };
  418. window.addEventListener('keydown', onKey);
  419. return () => window.removeEventListener('keydown', onKey);
  420. }, [onClose, goNext, goPrev]);
  421. const onPointerDown = (e: React.PointerEvent) => { dragStartX.current = e.clientX; };
  422. const onPointerUp = (e: React.PointerEvent) => {
  423. if (dragStartX.current === null) return;
  424. const dx = e.clientX - dragStartX.current;
  425. if (Math.abs(dx) > 50) (dx < 0 ? goNext() : goPrev());
  426. dragStartX.current = null;
  427. };
  428. const onPointerCancel = () => { dragStartX.current = null; };
  429. const visibleLeft = flipping === 'backward' ? getPage(prevLeftIdx) : getPage(leftIdx);
  430. const visibleRight = flipping === 'forward' ? getPage(nextRightIdx) : getPage(rightIdx);
  431. const currentPageNum = Math.min(leftIdx + 1, pages.length);
  432. const lastPageNum = Math.min(rightIdx + 1, pages.length);
  433. const indicatorLabel = currentPageNum === lastPageNum
  434. ? `${currentPageNum} / ${pages.length}`
  435. : `${currentPageNum}-${lastPageNum} / ${pages.length}`;
  436. const pageImgClass = 'w-full h-full object-contain';
  437. return (
  438. <div
  439. className="fixed inset-0 z-50 flex items-center justify-center bg-black/95 select-none"
  440. onPointerDown={onPointerDown}
  441. onPointerUp={onPointerUp}
  442. onPointerCancel={onPointerCancel}
  443. style={{ perspective: '2500px', touchAction: 'pan-y' }}
  444. >
  445. <style dangerouslySetInnerHTML={{ __html: `
  446. @keyframes flipBookForward { from { transform: rotateY(0deg); } to { transform: rotateY(-180deg); } }
  447. @keyframes flipBookBackward { from { transform: rotateY(0deg); } to { transform: rotateY(180deg); } }
  448. `}} />
  449. <button
  450. onClick={onClose}
  451. 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"
  452. title="Chiudi"
  453. aria-label="Chiudi"
  454. >✕</button>
  455. <div
  456. className="relative shadow-2xl"
  457. style={{
  458. // Two A4 pages side-by-side: aspect ratio ≈ 1.41:1 (2 × 0.707).
  459. // Cap by 95vw and 90vh so the book never overflows.
  460. width: 'min(95vw, calc(90vh * 1.41))',
  461. aspectRatio: '1.41 / 1',
  462. maxHeight: '90vh',
  463. transformStyle: 'preserve-3d',
  464. }}
  465. >
  466. {/* Static left page */}
  467. {visibleLeft && (
  468. <div className="absolute left-0 top-0 w-1/2 h-full bg-white overflow-hidden flex items-center justify-center">
  469. <img src={visibleLeft} className={pageImgClass} alt="" draggable={false} />
  470. </div>
  471. )}
  472. {/* Static right page */}
  473. {visibleRight && (
  474. <div className="absolute right-0 top-0 w-1/2 h-full bg-white overflow-hidden flex items-center justify-center">
  475. <img src={visibleRight} className={pageImgClass} alt="" draggable={false} />
  476. </div>
  477. )}
  478. {/* Flipping overlay — forward (right page rotates left) */}
  479. {flipping === 'forward' && (
  480. <div
  481. className="absolute right-0 top-0 w-1/2 h-full"
  482. style={{
  483. transformOrigin: 'left center',
  484. transformStyle: 'preserve-3d',
  485. animation: 'flipBookForward 700ms ease-in-out forwards',
  486. zIndex: 20,
  487. }}
  488. >
  489. <div className="absolute inset-0 bg-white overflow-hidden flex items-center justify-center" style={{ backfaceVisibility: 'hidden' }}>
  490. {getPage(rightIdx) && <img src={getPage(rightIdx)} className={pageImgClass} alt="" draggable={false} />}
  491. </div>
  492. <div className="absolute inset-0 bg-white overflow-hidden flex items-center justify-center" style={{ backfaceVisibility: 'hidden', transform: 'rotateY(180deg)' }}>
  493. {getPage(nextLeftIdx) && <img src={getPage(nextLeftIdx)} className={pageImgClass} alt="" draggable={false} />}
  494. </div>
  495. </div>
  496. )}
  497. {/* Flipping overlay — backward (left page rotates right) */}
  498. {flipping === 'backward' && (
  499. <div
  500. className="absolute left-0 top-0 w-1/2 h-full"
  501. style={{
  502. transformOrigin: 'right center',
  503. transformStyle: 'preserve-3d',
  504. animation: 'flipBookBackward 700ms ease-in-out forwards',
  505. zIndex: 20,
  506. }}
  507. >
  508. <div className="absolute inset-0 bg-white overflow-hidden flex items-center justify-center" style={{ backfaceVisibility: 'hidden' }}>
  509. {getPage(leftIdx) && <img src={getPage(leftIdx)} className={pageImgClass} alt="" draggable={false} />}
  510. </div>
  511. <div className="absolute inset-0 bg-white overflow-hidden flex items-center justify-center" style={{ backfaceVisibility: 'hidden', transform: 'rotateY(180deg)' }}>
  512. {getPage(prevRightIdx) && <img src={getPage(prevRightIdx)} className={pageImgClass} alt="" draggable={false} />}
  513. </div>
  514. </div>
  515. )}
  516. </div>
  517. <button
  518. onClick={goPrev}
  519. disabled={spread === 0 || flipping !== null}
  520. className="absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/25 disabled:opacity-25 disabled:cursor-not-allowed text-white w-14 h-14 flex items-center justify-center rounded-full text-3xl z-30 transition-colors"
  521. title="Pagina precedente"
  522. aria-label="Pagina precedente"
  523. >‹</button>
  524. <button
  525. onClick={goNext}
  526. disabled={spread >= totalSpreads - 1 || flipping !== null}
  527. className="absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 hover:bg-white/25 disabled:opacity-25 disabled:cursor-not-allowed text-white w-14 h-14 flex items-center justify-center rounded-full text-3xl z-30 transition-colors"
  528. title="Pagina successiva"
  529. aria-label="Pagina successiva"
  530. >›</button>
  531. <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">
  532. {pages.length === 0 ? 'Nessuna pagina' : indicatorLabel}
  533. </div>
  534. </div>
  535. );
  536. }
  537. export default function PublicGrid({ cards, maxCols = 5 }: { cards: Card[], maxCols?: number }) {
  538. const [activeCard, setActiveCard] = useState<Card | null>(null);
  539. const [fullscreenIndex, setFullscreenIndex] = useState<number | null>(null);
  540. useEffect(() => {
  541. if (activeCard || fullscreenIndex !== null) document.body.style.overflow = 'hidden';
  542. else document.body.style.overflow = 'unset';
  543. return () => { document.body.style.overflow = 'unset'; };
  544. }, [activeCard, fullscreenIndex]);
  545. const gridClasses: Record<number, string> = {
  546. 3: 'xl:grid-cols-3 lg:grid-cols-3 md:grid-cols-2 grid-cols-1',
  547. 4: 'xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2 grid-cols-1',
  548. 5: 'xl:grid-cols-5 lg:grid-cols-4 md:grid-cols-3 grid-cols-1',
  549. 6: 'xl:grid-cols-6 lg:grid-cols-4 md:grid-cols-3 grid-cols-2',
  550. 7: 'xl:grid-cols-7 lg:grid-cols-5 md:grid-cols-4 grid-cols-2',
  551. 8: 'xl:grid-cols-8 lg:grid-cols-6 md:grid-cols-4 grid-cols-2',
  552. };
  553. const activeGridClass = gridClasses[maxCols] || gridClasses[5];
  554. const carouselItems: MediaItem[] = activeCard
  555. ? [
  556. ...(activeCard.imageUrl && !activeCard.skipPreview ? [{ url: activeCard.imageUrl }] : []),
  557. ...(activeCard.extraMedia || []),
  558. ]
  559. : [];
  560. return (
  561. <>
  562. <div className={`grid gap-4 ${activeGridClass}`}>
  563. {cards.map((card) => {
  564. const galleryCount = card.extraMedia?.length || 0;
  565. const isExternalLink = card.cardType === 'EXTERNAL_LINK';
  566. // Fall back to the first gallery item when no explicit cover is set.
  567. const previewUrl = card.imageUrl || card.extraMedia?.[0]?.url || '';
  568. const previewIsVideo = !!previewUrl && isVideoUrl(previewUrl);
  569. return (
  570. <div
  571. key={card.id}
  572. onClick={() => {
  573. // EXTERNAL_LINK + redirectOnClick: salta il modale e apri direttamente l'URL
  574. if (card.cardType === 'EXTERNAL_LINK' && card.redirectOnClick) {
  575. const url = card.actionUrl || card.shortDescription;
  576. if (url) {
  577. window.open(url, '_blank', 'noopener,noreferrer');
  578. return;
  579. }
  580. }
  581. setActiveCard(card);
  582. if (card.cardType !== 'BOOK' && card.autoFullscreen) setFullscreenIndex(0);
  583. }}
  584. 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"
  585. >
  586. {previewUrl ? (
  587. previewIsVideo ? (
  588. <video
  589. src={previewUrl}
  590. className="absolute inset-0 w-full h-full object-cover pointer-events-none"
  591. muted
  592. playsInline
  593. preload="metadata"
  594. />
  595. ) : (
  596. <img src={previewUrl} alt={card.title} className="absolute inset-0 w-full h-full object-cover" />
  597. )
  598. ) : (
  599. <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>
  600. )}
  601. {isExternalLink ? (
  602. <div
  603. 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"
  604. title="External Link"
  605. aria-label="External Link"
  606. >
  607. L
  608. </div>
  609. ) : galleryCount > 0 ? (
  610. <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">
  611. <span>⊞</span>
  612. <span>{galleryCount}</span>
  613. </div>
  614. ) : null}
  615. <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">
  616. <h3 className="text-xl font-bold drop-shadow-md">{card.title}</h3>
  617. <p className="text-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300 line-clamp-2 mt-1 text-gray-200 drop-shadow">
  618. {card.shortDescription}
  619. </p>
  620. </div>
  621. </div>
  622. );
  623. })}
  624. </div>
  625. {activeCard && activeCard.cardType === 'BOOK' && (
  626. <FlipBook
  627. pages={(activeCard.extraMedia || []).map(m => m.url)}
  628. onClose={() => setActiveCard(null)}
  629. />
  630. )}
  631. {activeCard && activeCard.cardType !== 'BOOK' && fullscreenIndex === null && (
  632. <div
  633. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-md p-4"
  634. onClick={() => setActiveCard(null)}
  635. >
  636. <div
  637. 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"
  638. onClick={(e) => e.stopPropagation()}
  639. >
  640. <div className="relative">
  641. <MediaCarousel
  642. items={carouselItems}
  643. onMediaClick={(i) => setFullscreenIndex(i)}
  644. />
  645. <button
  646. onClick={() => setActiveCard(null)}
  647. 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"
  648. title="Close"
  649. >✕</button>
  650. </div>
  651. {(activeCard.title || activeCard.shortDescription || activeCard.fullContent || activeCard.actionUrl) && (
  652. <div className="p-8">
  653. {activeCard.title && (
  654. <h2 className={`text-3xl font-bold text-gray-900 ${(activeCard.shortDescription || activeCard.fullContent || activeCard.actionUrl) ? 'mb-4' : ''}`}>
  655. {activeCard.title}
  656. </h2>
  657. )}
  658. {activeCard.cardType === 'EXTERNAL_LINK' && (activeCard.actionUrl || activeCard.shortDescription) ? (
  659. <a
  660. href={activeCard.actionUrl || activeCard.shortDescription}
  661. target="_blank"
  662. rel="noopener noreferrer"
  663. className="inline-flex items-center gap-2 text-blue-600 hover:text-blue-800 underline break-all text-lg font-medium"
  664. >
  665. <span>{activeCard.shortDescription || activeCard.actionUrl}</span>
  666. <span aria-hidden>↗</span>
  667. </a>
  668. ) : activeCard.fullContent ? (
  669. <div className="prose max-w-none text-gray-700" dangerouslySetInnerHTML={{ __html: activeCard.fullContent }} />
  670. ) : activeCard.shortDescription ? (
  671. <p className="text-gray-500 italic text-lg">{activeCard.shortDescription}</p>
  672. ) : null}
  673. </div>
  674. )}
  675. </div>
  676. </div>
  677. )}
  678. {fullscreenIndex !== null && activeCard && (
  679. <FullscreenViewer
  680. items={carouselItems}
  681. startIndex={fullscreenIndex}
  682. onClose={() => {
  683. setFullscreenIndex(null);
  684. setActiveCard(null);
  685. }}
  686. />
  687. )}
  688. </>
  689. );
  690. }