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.
 
 

1378 líneas
69 KiB

  1. 'use client';
  2. import { useState, useEffect, useRef } from 'react';
  3. import { Card, Portal, MediaItem, CardType } from '@/types';
  4. import { EXTERNAL_LINK_ENABLED as EXTERNAL_LINK_DEFAULT, FACTORY_PRESET_SAVE_ENABLED, UPLOAD_LIMITS } from '@/lib/config';
  5. import { CARD_LIMITS, PORTAL_LIMITS } from '@/lib/validation';
  6. import { withBasePath } from '@/lib/url';
  7. type CharCounterProps = { value: string | undefined; limit: number };
  8. function CharCounter({ value, limit }: CharCounterProps) {
  9. const len = (value ?? '').length;
  10. const remaining = limit - len;
  11. const overflow = len > limit;
  12. const near = !overflow && len >= limit * 0.8;
  13. const color = overflow ? 'text-red-600 font-semibold' : near ? 'text-amber-600' : 'text-gray-400';
  14. return (
  15. <p className={`text-xs mt-1 text-right ${color}`}>
  16. {len} / {limit} · {remaining < 0 ? `${Math.abs(remaining)} over limit` : `${remaining} remaining`}
  17. </p>
  18. );
  19. }
  20. function stripTags(html: string): string {
  21. if (typeof window === 'undefined' || !html) return '';
  22. return new DOMParser().parseFromString(html, 'text/html').body.textContent ?? '';
  23. }
  24. type RichTextMiniProps = {
  25. value: string;
  26. onChange: (html: string) => void;
  27. limit: number;
  28. className?: string;
  29. };
  30. function RichTextMini({ value, onChange, limit, className }: RichTextMiniProps) {
  31. const ref = useRef<HTMLDivElement>(null);
  32. // Sync iniziale soltanto. Aggiornare innerHTML durante l'editing perderebbe la
  33. // posizione del cursore, quindi confidiamo che onInput tenga value e DOM allineati.
  34. useEffect(() => {
  35. if (ref.current && ref.current.innerHTML !== value) {
  36. ref.current.innerHTML = value || '';
  37. }
  38. // eslint-disable-next-line react-hooks/exhaustive-deps
  39. }, []);
  40. const exec = (cmd: 'bold' | 'italic') => {
  41. ref.current?.focus();
  42. document.execCommand(cmd);
  43. onChange(ref.current?.innerHTML || '');
  44. };
  45. return (
  46. <div>
  47. <div className="flex gap-1 mb-1">
  48. <button
  49. type="button"
  50. onClick={() => exec('bold')}
  51. className="font-bold w-8 h-8 border border-gray-300 rounded hover:bg-gray-100"
  52. title="Bold"
  53. >B</button>
  54. <button
  55. type="button"
  56. onClick={() => exec('italic')}
  57. className="italic w-8 h-8 border border-gray-300 rounded hover:bg-gray-100"
  58. title="Italic"
  59. >I</button>
  60. </div>
  61. <div
  62. ref={ref}
  63. contentEditable
  64. suppressContentEditableWarning
  65. onInput={(e) => onChange((e.target as HTMLDivElement).innerHTML)}
  66. className={className ?? 'w-full border border-gray-300 rounded-lg p-2.5 min-h-[8rem] bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-blue-500'}
  67. />
  68. <CharCounter value={stripTags(value)} limit={limit} />
  69. </div>
  70. );
  71. }
  72. function StyledSelect<T extends string>({
  73. value,
  74. onChange,
  75. options,
  76. }: {
  77. value: T;
  78. onChange: (v: T) => void;
  79. options: { value: T; label: string; style?: React.CSSProperties }[];
  80. }) {
  81. const [open, setOpen] = useState(false);
  82. const ref = useRef<HTMLDivElement>(null);
  83. useEffect(() => {
  84. if (!open) return;
  85. const onClick = (e: MouseEvent) => {
  86. if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
  87. };
  88. const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
  89. document.addEventListener('mousedown', onClick);
  90. document.addEventListener('keydown', onKey);
  91. return () => {
  92. document.removeEventListener('mousedown', onClick);
  93. document.removeEventListener('keydown', onKey);
  94. };
  95. }, [open]);
  96. const current = options.find(o => o.value === value);
  97. // Fallback: se il value non matcha nessuna opzione (es. tipo disattivato dalla flag), mostra il valore raw prettificato
  98. const displayLabel = current?.label
  99. ?? (typeof value === 'string' && value.length > 0
  100. ? value.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, c => c.toUpperCase())
  101. : '');
  102. const inputBase = "w-full border border-gray-300 p-2.5 rounded-lg outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900";
  103. return (
  104. <div ref={ref} className="relative">
  105. <button
  106. type="button"
  107. onClick={() => setOpen(o => !o)}
  108. className={`${inputBase} text-left flex items-center justify-between cursor-pointer`}
  109. >
  110. <span className={displayLabel ? '' : 'text-gray-400'} style={current?.style}>{displayLabel || 'Select…'}</span>
  111. <span className={`text-gray-500 transition-transform ${open ? 'rotate-180' : ''}`}>▾</span>
  112. </button>
  113. {open && (
  114. <div className="absolute left-0 right-0 top-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-30 overflow-hidden">
  115. {options.map(o => (
  116. <button
  117. key={o.value}
  118. type="button"
  119. onClick={() => { onChange(o.value); setOpen(false); }}
  120. className={`w-full text-left px-3 py-2.5 hover:bg-blue-50 transition-colors ${o.value === value ? 'bg-blue-100 font-semibold text-blue-700' : 'text-gray-800'}`}
  121. style={o.style}
  122. >
  123. {o.label}
  124. </button>
  125. ))}
  126. </div>
  127. )}
  128. </div>
  129. );
  130. }
  131. 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';
  132. // Sottoinsieme di formati video davvero riproducibili dai browser moderni
  133. const PLAYBACK_SUPPORTED_VIDEO = 'mp4|m4v|webm|mov|qt|ogv|ogg';
  134. const PLAYBACK_SUPPORTED_LABEL = 'MP4, M4V, WebM, MOV, OGV';
  135. const isVideoUrl = (url: string) => new RegExp(`\\.(${VIDEO_EXTENSIONS})(\\?|$)`, 'i').test(url);
  136. const isPdfFile = (file: File) =>
  137. file.type === 'application/pdf' || /\.pdf$/i.test(file.name);
  138. const isVideoFile = (file: File) =>
  139. file.type.startsWith('video/') || new RegExp(`\\.(${VIDEO_EXTENSIONS})$`, 'i').test(file.name);
  140. const isPlayableVideoFile = (file: File) =>
  141. new RegExp(`\\.(${PLAYBACK_SUPPORTED_VIDEO})$`, 'i').test(file.name);
  142. const previewFontFamily = (filename: string): string =>
  143. `PortalPreview-${filename.replace(/[^A-Za-z0-9]/g, '_')}`;
  144. const fontFormatFromName = (filename: string): string => {
  145. const ext = filename.match(/\.([^.]+)$/)?.[1].toLowerCase() ?? 'woff2';
  146. return ({ woff2: 'woff2', woff: 'woff', ttf: 'truetype', otf: 'opentype' } as Record<string, string>)[ext] ?? 'woff2';
  147. };
  148. const extractFileName = (url: string): string => {
  149. const match = url.match(/[?&]name=([^&]+)/);
  150. if (match) return decodeURIComponent(match[1]);
  151. const seg = url.split('/').pop() || 'download';
  152. return seg.split('?')[0];
  153. };
  154. async function uploadBlobAsImage(blob: Blob, name: string): Promise<string | null> {
  155. const formData = new FormData();
  156. formData.append('file', new File([blob], name, { type: blob.type || 'image/png' }));
  157. const res = await fetch(withBasePath('/api/upload'), { method: 'POST', body: formData });
  158. const data = await res.json();
  159. return data.url || null;
  160. }
  161. async function extractVideoFrame(file: File): Promise<Blob | null> {
  162. const url = URL.createObjectURL(file);
  163. try {
  164. const video = document.createElement('video');
  165. video.muted = true;
  166. video.playsInline = true;
  167. video.preload = 'metadata';
  168. video.src = url;
  169. await new Promise<void>((resolve, reject) => {
  170. video.addEventListener('loadedmetadata', () => resolve(), { once: true });
  171. video.addEventListener('error', () => reject(new Error('video load error')), { once: true });
  172. });
  173. // Seek slightly past 0 — at exactly 0 some codecs return a black frame
  174. video.currentTime = Math.min(0.1, Math.max(0, video.duration / 10));
  175. await new Promise<void>((resolve, reject) => {
  176. video.addEventListener('seeked', () => resolve(), { once: true });
  177. video.addEventListener('error', () => reject(new Error('video seek error')), { once: true });
  178. });
  179. const canvas = document.createElement('canvas');
  180. canvas.width = video.videoWidth;
  181. canvas.height = video.videoHeight;
  182. const ctx = canvas.getContext('2d');
  183. if (!ctx) return null;
  184. ctx.drawImage(video, 0, 0);
  185. return await new Promise<Blob | null>((resolve) =>
  186. canvas.toBlob((b) => resolve(b), 'image/jpeg', 0.85)
  187. );
  188. } finally {
  189. URL.revokeObjectURL(url);
  190. }
  191. }
  192. async function pdfToImageItems(
  193. file: File,
  194. onProgress: (page: number, total: number) => void
  195. ): Promise<MediaItem[]> {
  196. const pdfjs = await import('pdfjs-dist');
  197. // Worker file is copied to /public via the postinstall script
  198. pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs';
  199. const arrayBuffer = await file.arrayBuffer();
  200. const pdf = await pdfjs.getDocument({ data: arrayBuffer }).promise;
  201. const baseName = file.name.replace(/\.pdf$/i, '').replace(/[^a-zA-Z0-9-_]/g, '_');
  202. const items: MediaItem[] = [];
  203. for (let i = 1; i <= pdf.numPages; i++) {
  204. onProgress(i, pdf.numPages);
  205. const page = await pdf.getPage(i);
  206. const viewport = page.getViewport({ scale: 1.5 });
  207. const canvas = document.createElement('canvas');
  208. canvas.width = viewport.width;
  209. canvas.height = viewport.height;
  210. const ctx = canvas.getContext('2d');
  211. if (!ctx) continue;
  212. await page.render({ canvasContext: ctx, viewport }).promise;
  213. const blob: Blob = await new Promise((resolve, reject) => {
  214. canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/png');
  215. });
  216. const url = await uploadBlobAsImage(blob, `${baseName}-page${i}.png`);
  217. if (url) items.push({ url });
  218. }
  219. return items;
  220. }
  221. export default function AdminDashboard() {
  222. const [activeTab, setActiveTab] = useState<'cards' | 'settings'>('cards');
  223. // Card State
  224. const [cards, setCards] = useState<Card[]>([]);
  225. const [isEditing, setIsEditing] = useState<Partial<Card> | null>(null);
  226. // Portal State
  227. const [portal, setPortal] = useState<Partial<Portal>>({});
  228. const [savingPortal, setSavingPortal] = useState(false);
  229. const [uploading, setUploading] = useState<{ [key: string]: boolean }>({});
  230. // NEW UI STATES: Toast and Confirm Dialog
  231. const [toast, setToast] = useState<{ message: string; type: 'success' | 'error' } | null>(null);
  232. const [confirmDialog, setConfirmDialog] = useState<{ message: string, onConfirm: () => void } | null>(null);
  233. const [pdfProgress, setPdfProgress] = useState<{ name: string; page: number; total: number } | null>(null);
  234. const [availableFonts, setAvailableFonts] = useState<string[]>([]);
  235. // Map: expected URL of the future-transcoded file → job state.
  236. // We key by URL (not jobId) so the rendering layer can look it up cheaply.
  237. const [transcodeJobs, setTranscodeJobs] = useState<Record<string, { jobId: string; status: string; progress: number }>>({});
  238. // External Link feature flag: priorità al setting del portale, fallback alla costante in lib/config.
  239. const externalLinksOn = portal.externalLinkEnabled ?? EXTERNAL_LINK_DEFAULT;
  240. // Helper to show auto-dismissing toast
  241. const showToast = (message: string, type: 'success' | 'error' = 'success') => {
  242. setToast({ message, type });
  243. setTimeout(() => setToast(null), type === 'error' ? 6000 : 3000);
  244. };
  245. const refreshFonts = async () => {
  246. try {
  247. const res = await fetch(withBasePath('/api/fonts'));
  248. if (res.ok) setAvailableFonts(await res.json());
  249. } catch { setAvailableFonts([]); }
  250. };
  251. useEffect(() => {
  252. fetch(withBasePath('/api/cards')).then(res => res.json()).then(setCards);
  253. fetch(withBasePath('/api/portals')).then(res => res.json()).then(data => data && setPortal(data));
  254. void refreshFonts();
  255. }, []);
  256. const [uploadingFont, setUploadingFont] = useState(false);
  257. const handleFontUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  258. const file = e.target.files?.[0];
  259. e.target.value = '';
  260. if (!file) return;
  261. setUploadingFont(true);
  262. try {
  263. const fd = new FormData();
  264. fd.append('file', file);
  265. const res = await fetch(withBasePath('/api/admin/fonts'), { method: 'POST', body: fd });
  266. const data = await res.json().catch(() => ({}));
  267. if (!res.ok) {
  268. showToast(data?.error || `Upload error (${res.status})`, 'error');
  269. return;
  270. }
  271. showToast(`Font uploaded: ${data.name}`);
  272. await refreshFonts();
  273. // Auto-seleziona il font appena caricato
  274. if (data.name) setPortal(p => ({ ...p, fontFamily: data.name }));
  275. } catch (err) {
  276. showToast(`Network error: ${(err as Error).message}`, 'error');
  277. } finally {
  278. setUploadingFont(false);
  279. }
  280. };
  281. const handleFontDelete = async (name: string) => {
  282. if (!window.confirm(`Delete font "${name}"? Portals using this font will fall back to the system font.`)) return;
  283. try {
  284. const res = await fetch(withBasePath(`/api/admin/fonts?name=${encodeURIComponent(name)}`), { method: 'DELETE' });
  285. const data = await res.json().catch(() => ({}));
  286. if (!res.ok) {
  287. showToast(data?.error || `Delete error (${res.status})`, 'error');
  288. return;
  289. }
  290. showToast('Font deleted.');
  291. await refreshFonts();
  292. if (portal.fontFamily === name) setPortal(p => ({ ...p, fontFamily: '' }));
  293. } catch (err) {
  294. showToast(`Network error: ${(err as Error).message}`, 'error');
  295. }
  296. };
  297. // Poll pending transcode jobs every 2s. On 'done' we drop the entry from the
  298. // map; on 'failed' we additionally pull the media URL out of the editor so the
  299. // admin doesn't try to save a broken reference.
  300. useEffect(() => {
  301. const pendingEntries = Object.entries(transcodeJobs).filter(
  302. ([, j]) => j.status === 'queued' || j.status === 'running'
  303. );
  304. if (pendingEntries.length === 0) return;
  305. let cancelled = false;
  306. const tick = async () => {
  307. for (const [url, j] of pendingEntries) {
  308. if (cancelled) return;
  309. try {
  310. const res = await fetch(withBasePath(`/api/transcode/${j.jobId}`));
  311. if (!res.ok) continue;
  312. const data = await res.json();
  313. if (cancelled) return;
  314. if (data.status === 'done') {
  315. setTranscodeJobs(prev => {
  316. const next = { ...prev };
  317. delete next[url];
  318. return next;
  319. });
  320. } else if (data.status === 'failed' || data.status === 'cancelled') {
  321. setTranscodeJobs(prev => {
  322. const next = { ...prev };
  323. delete next[url];
  324. return next;
  325. });
  326. setIsEditing(prev => prev ? {
  327. ...prev,
  328. extraMedia: (prev.extraMedia || []).filter(m => m.url !== url),
  329. imageUrl: prev.imageUrl === url ? '' : prev.imageUrl,
  330. } : prev);
  331. const msg = data.status === 'failed'
  332. ? `Transcoding failed${data.error ? `: ${String(data.error).split('\n')[0]}` : ''}`
  333. : 'Trascodifica annullata';
  334. showToast(msg, 'error');
  335. } else {
  336. setTranscodeJobs(prev => prev[url] ? ({ ...prev, [url]: { ...prev[url], status: data.status, progress: data.progress ?? 0 } }) : prev);
  337. }
  338. } catch {
  339. // ignore network glitches; will retry next tick
  340. }
  341. }
  342. };
  343. void tick();
  344. const id = window.setInterval(() => { void tick(); }, 2000);
  345. return () => { cancelled = true; window.clearInterval(id); };
  346. // eslint-disable-next-line react-hooks/exhaustive-deps
  347. }, [Object.keys(transcodeJobs).join('|')]);
  348. const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>, field: string, isPortal = false) => {
  349. if (!e.target.files?.[0]) return;
  350. setUploading(prev => ({ ...prev, [field]: true }));
  351. const formData = new FormData();
  352. formData.append('file', e.target.files[0]);
  353. // Il logo è l'unico upload che ammette SVG (sanitizzato lato server).
  354. const endpoint = field === 'logoUrl' ? '/api/upload?context=logo' : '/api/upload';
  355. const res = await fetch(withBasePath(endpoint), { method: 'POST', body: formData });
  356. const data = await res.json();
  357. if (data.url) {
  358. if (isPortal) {
  359. setPortal(prev => ({ ...prev, [field]: data.url }));
  360. } else {
  361. setIsEditing(prev => ({ ...prev, [field]: data.url }));
  362. }
  363. }
  364. setUploading(prev => ({ ...prev, [field]: false }));
  365. };
  366. const handleUploadExtraMedia = async (e: React.ChangeEvent<HTMLInputElement>) => {
  367. const files = e.target.files;
  368. if (!files || files.length === 0) return;
  369. setUploading(prev => ({ ...prev, extraMedia: true }));
  370. const startedWithoutCover = !isEditing?.imageUrl;
  371. let pendingCover: string | null = null;
  372. const canPromote = () => startedWithoutCover && !pendingCover;
  373. // Pre-filtro: scarta video con formati non riproducibili nei browser
  374. const rejected: string[] = [];
  375. const acceptedFiles: File[] = [];
  376. for (const file of Array.from(files)) {
  377. if (isVideoFile(file) && !isPlayableVideoFile(file)) {
  378. rejected.push(file.name);
  379. } else {
  380. acceptedFiles.push(file);
  381. }
  382. }
  383. if (rejected.length > 0) {
  384. const list = rejected.length <= 3
  385. ? rejected.join(', ')
  386. : `${rejected.slice(0, 3).join(', ')} and ${rejected.length - 3} more`;
  387. showToast(
  388. `Unsupported format! Supported formats: ${PLAYBACK_SUPPORTED_LABEL}. Skipped files: ${list}`,
  389. 'error'
  390. );
  391. }
  392. if (acceptedFiles.length === 0) {
  393. setUploading(prev => ({ ...prev, extraMedia: false }));
  394. e.target.value = '';
  395. return;
  396. }
  397. const uploaded: MediaItem[] = [];
  398. for (const file of acceptedFiles) {
  399. try {
  400. if (isPdfFile(file)) {
  401. const items = await pdfToImageItems(file, (page, total) =>
  402. setPdfProgress({ name: file.name, page, total })
  403. );
  404. setPdfProgress(null);
  405. if (items.length > 0 && canPromote()) {
  406. // Promote the first PDF page to cover; skip it from the gallery to avoid duplication.
  407. pendingCover = items[0].url;
  408. uploaded.push(...items.slice(1));
  409. } else {
  410. uploaded.push(...items);
  411. }
  412. } else {
  413. const formData = new FormData();
  414. formData.append('file', file);
  415. const res = await fetch(withBasePath('/api/upload'), { method: 'POST', body: formData });
  416. const data = await res.json();
  417. if (!data.url) continue;
  418. if (data?.transcoding?.jobId) {
  419. const { jobId, status } = data.transcoding;
  420. setTranscodeJobs(prev => ({ ...prev, [data.url]: { jobId, status, progress: 0 } }));
  421. }
  422. if (isVideoFile(file)) {
  423. // Video always goes to the gallery so users can play it.
  424. uploaded.push({ url: data.url });
  425. // If no cover yet, extract the first frame and use it as the cover.
  426. if (canPromote()) {
  427. try {
  428. const blob = await extractVideoFrame(file);
  429. if (blob) {
  430. const baseName = file.name.replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9-_]/g, '_');
  431. const posterUrl = await uploadBlobAsImage(blob, `${baseName}-poster.jpg`);
  432. if (posterUrl) pendingCover = posterUrl;
  433. }
  434. } catch (err) {
  435. console.warn('Could not extract video poster for', file.name, err);
  436. }
  437. }
  438. } else {
  439. // Plain image
  440. if (canPromote()) {
  441. // Promote to cover; skip the gallery to avoid duplication.
  442. pendingCover = data.url;
  443. } else {
  444. uploaded.push({ url: data.url });
  445. }
  446. }
  447. }
  448. } catch (err) {
  449. console.error('Upload failed for', file.name, err);
  450. showToast(`Failed to process "${file.name}".`);
  451. setPdfProgress(null);
  452. }
  453. }
  454. setIsEditing(prev => ({
  455. ...prev,
  456. imageUrl: (startedWithoutCover && pendingCover) ? pendingCover : (prev?.imageUrl || ''),
  457. extraMedia: [...(prev?.extraMedia || []), ...uploaded],
  458. }));
  459. setUploading(prev => ({ ...prev, extraMedia: false }));
  460. e.target.value = '';
  461. };
  462. const removeExtraMedia = (index: number) => {
  463. setIsEditing(prev => ({
  464. ...prev,
  465. extraMedia: (prev?.extraMedia || []).filter((_, i) => i !== index),
  466. }));
  467. };
  468. const moveExtraMedia = (index: number, direction: 'up' | 'down') => {
  469. setIsEditing(prev => {
  470. const items = [...(prev?.extraMedia || [])];
  471. if (direction === 'up' && index > 0) {
  472. [items[index - 1], items[index]] = [items[index], items[index - 1]];
  473. } else if (direction === 'down' && index < items.length - 1) {
  474. [items[index + 1], items[index]] = [items[index], items[index + 1]];
  475. } else {
  476. return prev;
  477. }
  478. return { ...prev, extraMedia: items };
  479. });
  480. };
  481. const toggleAutoplay = (index: number) => {
  482. setIsEditing(prev => ({
  483. ...prev,
  484. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  485. i === index ? { ...m, autoplay: !m.autoplay } : m
  486. ),
  487. }));
  488. };
  489. const toggleMuted = (index: number) => {
  490. setIsEditing(prev => ({
  491. ...prev,
  492. extraMedia: (prev?.extraMedia || []).map((m, i) =>
  493. i === index ? { ...m, muted: !m.muted } : m
  494. ),
  495. }));
  496. };
  497. const handleSaveCard = async () => {
  498. if (!isEditing) return;
  499. // External Link: URL obbligatorio (feedback immediato, ribadito anche lato server)
  500. if (isEditing.cardType === 'EXTERNAL_LINK' && !isEditing.actionUrl?.trim()) {
  501. showToast('URL is required for External Link cards', 'error');
  502. return;
  503. }
  504. const generateSafeId = () => 'card-' + Date.now().toString(36) + Math.random().toString(36).substring(2);
  505. const newCard = { ...isEditing, id: isEditing.id || generateSafeId() } as Card;
  506. const res = await fetch(withBasePath('/api/cards'), {
  507. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newCard)
  508. });
  509. if (!res.ok) {
  510. let message = 'Save error';
  511. try {
  512. const body = await res.json();
  513. if (res.status === 400 && Array.isArray(body?.errors) && body.errors.length > 0) {
  514. const first = body.errors[0];
  515. message = first.limit != null
  516. ? `${first.field}: ${first.message} (${first.actual} / ${first.limit})`
  517. : `${first.field}: ${first.message}`;
  518. } else if (body?.error) {
  519. message = body.error;
  520. }
  521. } catch {}
  522. showToast(message, 'error');
  523. return; // keep the editor open so the admin can fix
  524. }
  525. setCards(prev => {
  526. const exists = prev.find(c => c.id === newCard.id);
  527. return exists ? prev.map(c => c.id === newCard.id ? newCard : c) : [...prev, newCard];
  528. });
  529. setIsEditing(null);
  530. };
  531. const handleDeleteCard = (id: string) => {
  532. // Replace window.confirm with our custom dialog
  533. setConfirmDialog({
  534. message: 'Are you sure you want to delete this card? This action cannot be undone.',
  535. onConfirm: async () => {
  536. await fetch(withBasePath(`/api/cards?id=${id}`), { method: 'DELETE' });
  537. setCards(prev => prev.filter(c => c.id !== id));
  538. setConfirmDialog(null);
  539. showToast('Card successfully deleted.');
  540. }
  541. });
  542. };
  543. const moveCard = async (index: number, direction: 'up' | 'down') => {
  544. const newCards = [...cards];
  545. if (direction === 'up' && index > 0) {
  546. [newCards[index - 1], newCards[index]] = [newCards[index], newCards[index - 1]];
  547. } else if (direction === 'down' && index < newCards.length - 1) {
  548. [newCards[index + 1], newCards[index]] = [newCards[index], newCards[index + 1]];
  549. } else {
  550. return; // Do nothing if trying to move out of bounds
  551. }
  552. // Recalculate displayOrder for the whole array
  553. const updatedCards = newCards.map((c, i) => ({ ...c, displayOrder: i }));
  554. // Optimistically update the UI
  555. setCards(updatedCards);
  556. // Persist the new order to the backend
  557. await fetch(withBasePath('/api/cards'), {
  558. method: 'PUT',
  559. headers: { 'Content-Type': 'application/json' },
  560. body: JSON.stringify(updatedCards)
  561. });
  562. };
  563. const handleSavePortal = async () => {
  564. setSavingPortal(true);
  565. await fetch(withBasePath('/api/portals'), {
  566. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(portal)
  567. });
  568. setSavingPortal(false);
  569. showToast('Portal settings saved successfully!'); // Replaced window.alert
  570. };
  571. const handleBackupDownload = () => {
  572. window.location.href = withBasePath('/api/admin/backup');
  573. };
  574. const [restoring, setRestoring] = useState(false);
  575. const handleRestoreUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  576. const file = e.target.files?.[0];
  577. e.target.value = '';
  578. if (!file) return;
  579. if (!window.confirm('Restore will overwrite all current data (cards, portal, media, fonts). Continue?')) return;
  580. setRestoring(true);
  581. try {
  582. const fd = new FormData();
  583. fd.append('file', file);
  584. const res = await fetch(withBasePath('/api/admin/restore'), { method: 'POST', body: fd });
  585. const data = await res.json().catch(() => ({}));
  586. if (!res.ok) {
  587. showToast(data?.error || `Restore error (${res.status})`, 'error');
  588. return;
  589. }
  590. showToast(`Restore completed: ${data.restored?.cards ?? 0} cards, ${data.restored?.portals ?? 0} portals. Reloading…`);
  591. setTimeout(() => window.location.reload(), 1200);
  592. } catch (err) {
  593. showToast(`Network error: ${(err as Error).message}`, 'error');
  594. } finally {
  595. setRestoring(false);
  596. }
  597. };
  598. // Factory preset: la sezione è sempre visibile (per chi accede a /admin); solo
  599. // il bottone "Salva come preset" è gated da FACTORY_PRESET_SAVE_ENABLED.
  600. const [factoryPreset, setFactoryPreset] = useState<{ exists: boolean; sizeBytes?: number; modifiedAt?: string } | null>(null);
  601. const [savingPreset, setSavingPreset] = useState(false);
  602. const [factoryResetting, setFactoryResetting] = useState(false);
  603. const refreshFactoryPreset = async () => {
  604. try {
  605. const res = await fetch(withBasePath('/api/admin/factory-preset'));
  606. if (res.ok) setFactoryPreset(await res.json());
  607. } catch { /* ignore */ }
  608. };
  609. useEffect(() => {
  610. void refreshFactoryPreset();
  611. }, []);
  612. const handleSaveFactoryPreset = async () => {
  613. const msg = factoryPreset?.exists
  614. ? 'Overwrite the existing factory preset with the current state?'
  615. : 'Save the current state as factory preset?';
  616. if (!window.confirm(msg)) return;
  617. setSavingPreset(true);
  618. try {
  619. const res = await fetch(withBasePath('/api/admin/factory-preset'), { method: 'POST' });
  620. const data = await res.json().catch(() => ({}));
  621. if (!res.ok) {
  622. showToast(data?.error || `Error (${res.status})`, 'error');
  623. return;
  624. }
  625. showToast('Factory preset updated.');
  626. await refreshFactoryPreset();
  627. } catch (err) {
  628. showToast(`Network error: ${(err as Error).message}`, 'error');
  629. } finally {
  630. setSavingPreset(false);
  631. }
  632. };
  633. const handleFactoryReset = async () => {
  634. if (!window.confirm('FACTORY RESET — all current data will be replaced with the factory preset. Continue?')) return;
  635. setFactoryResetting(true);
  636. try {
  637. const res = await fetch(withBasePath('/api/admin/factory-reset'), { method: 'POST' });
  638. const data = await res.json().catch(() => ({}));
  639. if (!res.ok) {
  640. showToast(data?.error || `Error (${res.status})`, 'error');
  641. return;
  642. }
  643. showToast(`Factory reset completed: ${data.restored?.cards ?? 0} cards, ${data.restored?.portals ?? 0} portals. Reloading…`);
  644. setTimeout(() => window.location.reload(), 1200);
  645. } catch (err) {
  646. showToast(`Network error: ${(err as Error).message}`, 'error');
  647. } finally {
  648. setFactoryResetting(false);
  649. }
  650. };
  651. // Shared Input Classes for high contrast
  652. const inputClasses = "w-full border border-gray-300 p-2.5 rounded-lg outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900 placeholder-gray-400";
  653. return (
  654. <div className="min-h-screen bg-gray-50 font-sans pb-12">
  655. {/* Top Header */}
  656. <div className="bg-blue-900 text-white shadow-md py-6 px-4">
  657. <div className="max-w-5xl mx-auto flex justify-between items-center">
  658. <div>
  659. <h1 className="text-2xl font-bold">Captive Portal CMS</h1>
  660. <p className="text-sm text-blue-200">Local Administration</p>
  661. </div>
  662. <a href={withBasePath('/')} target="_blank" className="bg-blue-800 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm transition-colors">
  663. View Live Portal ↗
  664. </a>
  665. </div>
  666. </div>
  667. <div className="max-w-5xl mx-auto mt-8 px-4">
  668. {/* Tab Navigation */}
  669. <div className="flex space-x-2 mb-6">
  670. <button onClick={() => setActiveTab('cards')} className={`px-6 py-3 rounded-t-lg font-bold transition-colors ${activeTab === 'cards' ? 'bg-white text-blue-700 border-t-4 border-blue-600 shadow-sm' : 'bg-gray-200 text-gray-600 hover:bg-gray-300'}`}>
  671. Manage Cards
  672. </button>
  673. <button onClick={() => setActiveTab('settings')} className={`px-6 py-3 rounded-t-lg font-bold transition-colors ${activeTab === 'settings' ? 'bg-white text-blue-700 border-t-4 border-blue-600 shadow-sm' : 'bg-gray-200 text-gray-600 hover:bg-gray-300'}`}>
  674. Portal Settings
  675. </button>
  676. </div>
  677. <div className="bg-white rounded-b-xl rounded-tr-xl shadow-sm border border-gray-200 overflow-hidden min-h-[500px]">
  678. {/* TAB: CARDS */}
  679. {activeTab === 'cards' && (
  680. <div className="p-6 md:p-8">
  681. <div className="flex justify-between items-center mb-8 border-b pb-4">
  682. <h2 className="text-xl font-bold text-gray-800">Card Grid</h2>
  683. <button onClick={() => setIsEditing({ title: '', cardType: 'INFO_PAGE', displayOrder: cards.length })} className="bg-blue-600 text-white px-5 py-2.5 rounded-lg shadow-sm hover:bg-blue-700 font-medium">
  684. + Add New Card
  685. </button>
  686. </div>
  687. <div className="space-y-3 mb-8">
  688. {cards.length === 0 && <p className="text-gray-500 italic text-center py-8">No cards available. Create one to get started.</p>}
  689. {cards.map((card, idx) => (
  690. // CHANGED: flex-col on mobile, flex-row on sm+, added gap-4 for mobile spacing
  691. <div key={card.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 border rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors gap-4">
  692. <div className="flex items-center gap-4">
  693. {(() => {
  694. const previewUrl = card.imageUrl || card.extraMedia?.[0]?.url || '';
  695. if (!previewUrl) {
  696. return <div className="w-16 h-16 bg-gray-200 rounded-md shadow-sm flex items-center justify-center text-gray-400 text-xs shrink-0">No Image</div>;
  697. }
  698. return isVideoUrl(previewUrl)
  699. ? <video src={withBasePath(previewUrl)} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" muted playsInline preload="metadata" />
  700. : <img src={withBasePath(previewUrl)} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" alt="" />;
  701. })()}
  702. <div>
  703. <span className="font-semibold text-gray-800 block">{card.title}</span>
  704. <span className="text-xs text-gray-500 uppercase tracking-wider">
  705. {card.cardType}
  706. {card.extraMedia && card.extraMedia.length > 0 && (
  707. <span className="text-gray-400 normal-case tracking-normal ml-2">[{card.extraMedia.length}]</span>
  708. )}
  709. {card.cardType === 'FULLSCREEN_LOCK' && (
  710. <span className="ml-2 bg-red-100 text-red-700 px-2 py-0.5 rounded font-bold text-[10px] tracking-wider">LOCK ACTIVE</span>
  711. )}
  712. </span>
  713. </div>
  714. </div>
  715. {/* CHANGED: flex-wrap to ensure buttons don't overflow on small screens, w-full on mobile */}
  716. <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto justify-end">
  717. <button onClick={() => moveCard(idx, 'up')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Up">↑</button>
  718. <button onClick={() => moveCard(idx, 'down')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Down">↓</button>
  719. <div className="w-px h-6 bg-gray-300 mx-1 hidden sm:block"></div>
  720. <button onClick={() => setIsEditing(card)} className="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded font-medium">Edit</button>
  721. <button onClick={() => handleDeleteCard(card.id)} className="px-4 py-2 text-red-600 hover:bg-red-50 rounded font-medium">Delete</button>
  722. </div>
  723. </div>
  724. ))}
  725. </div>
  726. </div>
  727. )}
  728. {/* TAB: SETTINGS */}
  729. {activeTab === 'settings' && (
  730. <div className="p-6 md:p-8">
  731. <h2 className="text-xl font-bold text-gray-800 mb-8 border-b pb-4">Global Portal Settings</h2>
  732. <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
  733. <div className="space-y-6">
  734. <div>
  735. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal Title</label>
  736. <input type="text" maxLength={PORTAL_LIMITS.title} value={portal.title || ''} onChange={e => setPortal({...portal, title: e.target.value})} className={inputClasses} />
  737. <CharCounter value={portal.title} limit={PORTAL_LIMITS.title} />
  738. </div>
  739. <div>
  740. <label className="block text-sm font-semibold text-gray-700 mb-1">Welcome Text</label>
  741. <RichTextMini
  742. value={portal.welcomeText || ''}
  743. onChange={html => setPortal({ ...portal, welcomeText: html })}
  744. limit={PORTAL_LIMITS.welcomeText}
  745. />
  746. </div>
  747. <div className="flex gap-8">
  748. <div>
  749. <label className="block text-sm font-semibold text-gray-700 mb-1">Theme Color</label>
  750. <div className="flex items-center gap-4">
  751. <input type="color" value={portal.themeColor || '#1e3a8a'} onChange={e => setPortal({...portal, themeColor: e.target.value})} className="h-12 w-12 rounded cursor-pointer border-0 p-0" />
  752. <span className="text-gray-900 font-mono font-medium">{portal.themeColor || '#1e3a8a'}</span>
  753. </div>
  754. </div>
  755. {/* NEW: Max Columns Setting updated for 3 */}
  756. <div className="flex-1">
  757. <label className="block text-sm font-semibold text-gray-700 mb-1">Grid Max Columns: {portal.maxGridColumns || 5}</label>
  758. <input
  759. type="range"
  760. min="3"
  761. max="8"
  762. value={portal.maxGridColumns || 5}
  763. onChange={e => setPortal({...portal, maxGridColumns: parseInt(e.target.value)})}
  764. className="w-full mt-3 accent-blue-600"
  765. />
  766. <div className="flex justify-between text-xs text-gray-400 mt-1">
  767. <span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>
  768. </div>
  769. </div>
  770. </div>
  771. <div>
  772. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal font</label>
  773. <style dangerouslySetInnerHTML={{ __html: availableFonts.map(f => `
  774. @font-face {
  775. font-family: '${previewFontFamily(f)}';
  776. src: url('${withBasePath('/api/fonts?name=' + encodeURIComponent(f))}') format('${fontFormatFromName(f)}');
  777. font-display: swap;
  778. }`).join('') }} />
  779. <StyledSelect<string>
  780. value={portal.fontFamily ?? ''}
  781. onChange={(v) => setPortal({ ...portal, fontFamily: v })}
  782. options={[
  783. { value: '', label: 'System (Arial)' },
  784. ...availableFonts.map(f => ({
  785. value: f,
  786. label: f.replace(/\.(woff2?|ttf|otf)$/i, ''),
  787. style: { fontFamily: `'${previewFontFamily(f)}', Arial, Helvetica, sans-serif` },
  788. })),
  789. ]}
  790. />
  791. <div className="flex items-center gap-3 flex-wrap mt-2">
  792. <label className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-gray-800 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  793. <input
  794. type="file"
  795. accept=".woff2,.woff,.ttf,.otf,font/woff2,font/woff,font/ttf,font/otf"
  796. onChange={handleFontUpload}
  797. disabled={uploadingFont}
  798. hidden
  799. />
  800. {uploadingFont ? 'Uploading…' : 'Upload font…'}
  801. </label>
  802. {portal.fontFamily && availableFonts.includes(portal.fontFamily) && (
  803. <button
  804. type="button"
  805. onClick={() => handleFontDelete(portal.fontFamily!)}
  806. className="text-xs text-red-600 hover:text-red-700 underline"
  807. title={`Delete font "${portal.fontFamily}"`}
  808. >
  809. Delete selected font
  810. </button>
  811. )}
  812. </div>
  813. <p className="text-xs text-gray-500 mt-1">Supported: <code>.woff2</code>, <code>.woff</code>, <code>.ttf</code>, <code>.otf</code> · max {(UPLOAD_LIMITS.font / (1024 * 1024)).toFixed(0)} MB</p>
  814. </div>
  815. </div>
  816. <div className="space-y-6">
  817. {/* Logo Upload with Remove Button */}
  818. <div>
  819. <label className="block text-sm font-semibold text-gray-700 mb-1">Logo Image</label>
  820. <div className="flex items-center gap-3 flex-wrap">
  821. <label className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-gray-800 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  822. <input type="file" accept="image/*,.svg,image/svg+xml" onChange={e => handleUpload(e, 'logoUrl', true)} hidden />
  823. Choose image…
  824. </label>
  825. {uploading['logoUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  826. </div>
  827. {portal.logoUrl && (
  828. <div className="mt-2 bg-gray-100 p-4 rounded inline-block relative border">
  829. <img src={withBasePath(portal.logoUrl)} className="h-16 object-contain" alt="Logo Preview" />
  830. <a href={withBasePath(portal.logoUrl)} download={extractFileName(portal.logoUrl)} className="absolute -top-2 right-6 bg-gray-700 hover:bg-gray-800 text-white w-6 h-6 rounded-full text-xs font-bold shadow flex items-center justify-center" title="Download" aria-label="Download logo">⬇</a>
  831. <button onClick={() => setPortal({...portal, logoUrl: ''})} className="absolute -top-2 -right-2 bg-red-500 text-white w-6 h-6 rounded-full text-xs font-bold hover:bg-red-600 shadow">✕</button>
  832. </div>
  833. )}
  834. </div>
  835. {/* Hero Upload with Remove Button */}
  836. <div>
  837. <label className="block text-sm font-semibold text-gray-700 mb-1">Background Image</label>
  838. <div className="flex items-center gap-3 flex-wrap">
  839. <label className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-gray-800 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  840. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'heroImageUrl', true)} hidden />
  841. Choose image…
  842. </label>
  843. {uploading['heroImageUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  844. </div>
  845. {portal.heroImageUrl && (
  846. <div className="mt-2 relative rounded shadow border inline-block w-full">
  847. <img src={withBasePath(portal.heroImageUrl)} className="h-32 w-full object-cover rounded" alt="Background preview" />
  848. <a href={withBasePath(portal.heroImageUrl)} download={extractFileName(portal.heroImageUrl)} className="absolute top-2 right-12 bg-gray-700 hover:bg-gray-800 text-white w-8 h-8 flex items-center justify-center rounded-full text-sm font-bold shadow-lg" title="Download" aria-label="Download background">⬇</a>
  849. <button onClick={() => setPortal({...portal, heroImageUrl: ''})} className="absolute top-2 right-2 bg-red-500 text-white w-8 h-8 flex items-center justify-center rounded-full text-sm font-bold hover:bg-red-600 shadow-lg">✕</button>
  850. </div>
  851. )}
  852. </div>
  853. <div className="bg-gray-50 p-4 rounded-lg border border-gray-200 space-y-3">
  854. <label className="flex items-center gap-3 cursor-pointer">
  855. <input type="checkbox" checked={!!portal.fadeHeroImage} onChange={e => setPortal({...portal, fadeHeroImage: e.target.checked})} className="w-5 h-5 text-blue-600 rounded" />
  856. <div>
  857. <span className="block text-sm font-semibold text-gray-900">Fade Image into Background Color</span>
  858. <span className="block text-xs text-gray-600">Creates a smooth gradient from the top of the image into the solid theme color at the bottom.</span>
  859. </div>
  860. </label>
  861. <label className="flex items-center gap-3 cursor-pointer">
  862. <input
  863. type="checkbox"
  864. checked={portal.externalLinkEnabled ?? EXTERNAL_LINK_DEFAULT}
  865. onChange={e => setPortal({...portal, externalLinkEnabled: e.target.checked})}
  866. className="w-5 h-5 text-blue-600 rounded"
  867. />
  868. <div>
  869. <span className="block text-sm font-semibold text-gray-900">Enable &ldquo;External Link&rdquo; type in the dropdown menu.</span>
  870. <span className="block text-xs text-gray-600">Existing cards of this type will still remain visible and clickable, even if you disable the &ldquo;External Link&rdquo; type.</span>
  871. </div>
  872. </label>
  873. </div>
  874. </div>
  875. </div>
  876. <div className="mt-10 pt-6 border-t border-gray-200">
  877. <h3 className="text-sm font-bold uppercase tracking-wider text-gray-600 mb-3">Backup &amp; Restore</h3>
  878. <p className="text-xs text-gray-500 mb-4">
  879. The backup contains cards, portal configuration, media (images, videos, PDFs), and uploaded fonts. Restoring overwrites the current state. Clicking the &ldquo;Save backup (ZIP)&rdquo; button saves the Cards structure as <code>interceptor-backup-YYYYMMDD-hhmmss.zip</code>.
  880. </p>
  881. <div className="flex flex-wrap gap-3">
  882. <button
  883. type="button"
  884. onClick={handleBackupDownload}
  885. className="bg-gray-800 text-white px-5 py-2.5 rounded-lg hover:bg-gray-900 font-medium shadow-sm"
  886. >
  887. ⬇ Save backup (ZIP)
  888. </button>
  889. <label className={`cursor-pointer inline-flex items-center bg-amber-600 text-white px-5 py-2.5 rounded-lg hover:bg-amber-700 font-medium shadow-sm ${restoring ? 'opacity-60 cursor-not-allowed' : ''}`}>
  890. <input
  891. type="file"
  892. accept=".zip,application/zip,application/x-zip-compressed"
  893. onChange={handleRestoreUpload}
  894. disabled={restoring}
  895. hidden
  896. />
  897. {restoring ? 'Restoring…' : '⤴ Restore from ZIP'}
  898. </label>
  899. </div>
  900. </div>
  901. <div className="mt-8 pt-6 border-t border-gray-200">
  902. <h3 className="text-sm font-bold uppercase tracking-wider text-gray-600 mb-3">Factory Preset</h3>
  903. <p className="text-xs text-gray-500 mb-2">
  904. &ldquo;Factory&rdquo; state restorable with one click. The preset (<code>factory/preset.zip</code>) is prepared on the development machine and distributed to MajorNet machines.
  905. </p>
  906. <p className="text-xs text-gray-700 mb-4">
  907. Current preset: {factoryPreset === null ? '…'
  908. : factoryPreset.exists
  909. ? <span className="text-green-700 font-medium">present · {((factoryPreset.sizeBytes ?? 0) / (1024 * 1024)).toFixed(1)} MB · {factoryPreset.modifiedAt ? new Date(factoryPreset.modifiedAt).toLocaleString('en-GB') : '?'}</span>
  910. : <span className="text-gray-400 italic">no preset configured</span>}
  911. </p>
  912. <div className="flex flex-wrap gap-3">
  913. <button
  914. type="button"
  915. onClick={handleFactoryReset}
  916. disabled={factoryResetting || !factoryPreset?.exists}
  917. title={factoryPreset?.exists ? undefined : 'No preset configured'}
  918. className="bg-red-700 text-white px-5 py-2.5 rounded-lg hover:bg-red-800 font-medium shadow-sm disabled:opacity-60 disabled:cursor-not-allowed"
  919. >
  920. {factoryResetting ? 'Reset in progress…' : 'Factory Reset'}
  921. </button>
  922. {FACTORY_PRESET_SAVE_ENABLED && (
  923. <button
  924. type="button"
  925. onClick={handleSaveFactoryPreset}
  926. disabled={savingPreset}
  927. title="Developer function: save the current state as a new factory preset"
  928. className="bg-emerald-700 text-white px-5 py-2.5 rounded-lg hover:bg-emerald-800 font-medium shadow-sm disabled:opacity-60"
  929. >
  930. {savingPreset ? 'Saving…' : 'Save as Factory Preset (dev)'}
  931. </button>
  932. )}
  933. </div>
  934. </div>
  935. <div className="mt-10 pt-6 border-t border-gray-200 flex justify-end">
  936. <button onClick={handleSavePortal} disabled={savingPortal} className="bg-blue-600 text-white px-10 py-3 rounded-lg hover:bg-blue-700 font-bold shadow disabled:opacity-50 transition-colors">
  937. {savingPortal ? 'Saving...' : 'Save Portal Settings'}
  938. </button>
  939. </div>
  940. </div>
  941. )}
  942. </div>
  943. </div>
  944. {/* MODAL FOR EDITING/CREATING CARDS */}
  945. {isEditing && (
  946. <div
  947. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 transition-opacity"
  948. onClick={() => setIsEditing(null)} // Click outside to close
  949. >
  950. <div
  951. className="bg-white rounded-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto shadow-2xl p-6 md:p-8 relative animate-in fade-in zoom-in-95 duration-200"
  952. onClick={(e) => e.stopPropagation()} // Prevent inside clicks from closing
  953. >
  954. <button
  955. onClick={() => setIsEditing(null)}
  956. className="absolute top-6 right-6 text-gray-400 hover:text-gray-900 bg-gray-100 hover:bg-gray-200 rounded-full w-8 h-8 flex items-center justify-center transition-colors"
  957. >
  958. </button>
  959. <h3 className="text-2xl font-bold mb-6 text-gray-900 border-b pb-4">
  960. {isEditing.id ? 'Edit Card' : 'Create New Card'}
  961. </h3>
  962. <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
  963. <div className="space-y-5">
  964. <div>
  965. <label className="block text-sm font-semibold text-gray-800 mb-1">Title</label>
  966. <input type="text" maxLength={CARD_LIMITS.title} value={isEditing.title || ''} onChange={e => setIsEditing({...isEditing, title: e.target.value})} className={inputClasses} placeholder="e.g., Local History" />
  967. <CharCounter value={isEditing.title} limit={CARD_LIMITS.title} />
  968. </div>
  969. <div>
  970. <label className="block text-sm font-semibold text-gray-800 mb-1">Card Type</label>
  971. <StyledSelect<CardType>
  972. value={(isEditing.cardType || 'INFO_PAGE') as CardType}
  973. onChange={(v) => setIsEditing({ ...isEditing, cardType: v })}
  974. options={[
  975. { value: 'INFO_PAGE', label: 'Info Page' },
  976. { value: 'IMAGE_GALLERY', label: 'Image Gallery' },
  977. { value: 'BOOK', label: 'Flip-Book' },
  978. { value: 'FULLSCREEN_LOCK', label: 'Fullscreen Lock (kiosk)' },
  979. ...(externalLinksOn ? [{ value: 'EXTERNAL_LINK' as CardType, label: 'External Link' }] : []),
  980. ]}
  981. />
  982. </div>
  983. {isEditing.cardType === 'FULLSCREEN_LOCK' && (
  984. <div className="bg-red-50 border border-red-200 rounded-lg p-4">
  985. <p className="text-sm font-semibold text-red-800">⚠ Kiosk Lock Mode</p>
  986. <p className="text-xs text-red-700 mt-1">
  987. This card will take full control of the public portal. All other cards will be hidden until you remove this one.
  988. Upload an image or video as &quot;Full-screen content&quot; in the section on the right.
  989. </p>
  990. </div>
  991. )}
  992. {isEditing.cardType !== 'FULLSCREEN_LOCK' && (isEditing.cardType === 'EXTERNAL_LINK' ? (
  993. <>
  994. <div>
  995. <label className="block text-sm font-semibold text-gray-800 mb-1">URL <span className="text-red-600">*</span></label>
  996. <input
  997. type="url"
  998. maxLength={CARD_LIMITS.actionUrl}
  999. value={isEditing.actionUrl || ''}
  1000. onChange={e => setIsEditing({ ...isEditing, actionUrl: e.target.value })}
  1001. className={inputClasses}
  1002. placeholder="https://example.com/page"
  1003. />
  1004. <CharCounter value={isEditing.actionUrl} limit={CARD_LIMITS.actionUrl} />
  1005. </div>
  1006. <div>
  1007. <label className="block text-sm font-semibold text-gray-800 mb-1">Link text</label>
  1008. <input
  1009. type="text"
  1010. maxLength={CARD_LIMITS.shortDescription}
  1011. value={isEditing.shortDescription || ''}
  1012. onChange={e => setIsEditing({ ...isEditing, shortDescription: e.target.value })}
  1013. className={inputClasses}
  1014. placeholder="e.g. Visit the official site"
  1015. />
  1016. <CharCounter value={isEditing.shortDescription} limit={CARD_LIMITS.shortDescription} />
  1017. <p className="text-xs text-gray-500 mt-1">Text displayed as a clickable link in the modal. If empty, the URL itself is shown.</p>
  1018. </div>
  1019. <div className="bg-gray-50 p-3 rounded-lg border border-gray-200">
  1020. <label className="flex items-start gap-3 cursor-pointer">
  1021. <input
  1022. type="checkbox"
  1023. checked={!!isEditing.redirectOnClick}
  1024. onChange={e => setIsEditing({ ...isEditing, redirectOnClick: e.target.checked })}
  1025. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  1026. />
  1027. <div>
  1028. <span className="block text-sm font-semibold text-gray-900">Redirect on click</span>
  1029. <span className="block text-xs text-gray-600">Cliccando la card sul portale pubblico, il browser apre direttamente l&rsquo;URL senza mostrare il modale.</span>
  1030. </div>
  1031. </label>
  1032. </div>
  1033. </>
  1034. ) : (
  1035. <div>
  1036. <label className="block text-sm font-semibold text-gray-800 mb-1">Short Description</label>
  1037. <textarea maxLength={CARD_LIMITS.shortDescription} value={isEditing.shortDescription || ''} onChange={e => setIsEditing({ ...isEditing, shortDescription: e.target.value })} className={`${inputClasses} h-24 resize-none`} placeholder="Brief summary..." />
  1038. <CharCounter value={isEditing.shortDescription} limit={CARD_LIMITS.shortDescription} />
  1039. </div>
  1040. ))}
  1041. {isEditing.cardType !== 'BOOK' && isEditing.cardType !== 'FULLSCREEN_LOCK' && (
  1042. <div className="bg-gray-50 p-3 rounded-lg border border-gray-200 space-y-3">
  1043. <label className="flex items-start gap-3 cursor-pointer">
  1044. <input
  1045. type="checkbox"
  1046. checked={!!isEditing.autoFullscreen}
  1047. onChange={e => setIsEditing({ ...isEditing, autoFullscreen: e.target.checked })}
  1048. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  1049. />
  1050. <div>
  1051. <span className="block text-sm font-semibold text-gray-900">Auto fullscreen</span>
  1052. <span className="block text-xs text-gray-600">Open the gallery in fullscreen immediately when the user clicks this card.</span>
  1053. </div>
  1054. </label>
  1055. <label className="flex items-start gap-3 cursor-pointer">
  1056. <input
  1057. type="checkbox"
  1058. checked={!!isEditing.skipPreview}
  1059. onChange={e => setIsEditing({ ...isEditing, skipPreview: e.target.checked })}
  1060. className="w-5 h-5 text-blue-600 rounded mt-0.5"
  1061. />
  1062. <div>
  1063. <span className="block text-sm font-semibold text-gray-900">Cover not in the gallery</span>
  1064. <span className="block text-xs text-gray-600">The cover stays as the card thumbnail only. Combine with &ldquo;Auto fullscreen&rdquo; to jump straight into the gallery items.</span>
  1065. </div>
  1066. </label>
  1067. </div>
  1068. )}
  1069. </div>
  1070. <div className="space-y-5">
  1071. {/* Cover Image — per FULLSCREEN_LOCK è il contenuto kiosk a tutto schermo e accetta anche video */}
  1072. <div>
  1073. <label className="block text-sm font-semibold text-gray-800 mb-1">
  1074. {isEditing.cardType === 'FULLSCREEN_LOCK'
  1075. ? <>Full-screen content <span className="text-gray-400 font-normal text-xs">(image or video)</span></>
  1076. : <>Cover Image <span className="text-gray-400 font-normal text-xs">(shown in grid)</span></>}
  1077. </label>
  1078. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  1079. <label className="inline-block cursor-pointer bg-blue-50 hover:bg-blue-100 text-blue-700 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  1080. <input
  1081. type="file"
  1082. accept={isEditing.cardType === 'FULLSCREEN_LOCK' ? 'image/*,video/mp4,video/webm,.mp4,.webm,.mov,.m4v' : 'image/*'}
  1083. onChange={e => handleUpload(e, 'imageUrl')}
  1084. hidden
  1085. />
  1086. {isEditing.cardType === 'FULLSCREEN_LOCK' ? 'Choose image or video…' : 'Choose image…'}
  1087. </label>
  1088. {uploading['imageUrl'] && <p className="mt-2 text-sm text-blue-600 font-medium">Uploading...</p>}
  1089. </div>
  1090. {isEditing.imageUrl && (
  1091. <div className="mt-3 relative rounded-lg overflow-hidden border border-gray-200 group">
  1092. {isVideoUrl(isEditing.imageUrl) ? (
  1093. <video src={withBasePath(isEditing.imageUrl)} className="w-full h-32 object-cover" muted playsInline />
  1094. ) : (
  1095. <img src={withBasePath(isEditing.imageUrl)} className="w-full h-32 object-cover" alt="Cover preview" />
  1096. )}
  1097. <a
  1098. href={withBasePath(isEditing.imageUrl)}
  1099. download={extractFileName(isEditing.imageUrl)}
  1100. className="absolute top-2 right-12 bg-gray-700 hover:bg-gray-800 text-white w-8 h-8 rounded-full text-sm font-bold shadow opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"
  1101. title="Download"
  1102. aria-label="Download cover"
  1103. >⬇</a>
  1104. <button
  1105. onClick={() => setIsEditing({...isEditing, imageUrl: ''})}
  1106. className="absolute top-2 right-2 bg-red-500 text-white w-8 h-8 rounded-full text-sm font-bold shadow opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600"
  1107. title="Remove cover image"
  1108. >✕</button>
  1109. </div>
  1110. )}
  1111. </div>
  1112. {/* Gallery Media (images + videos + PDFs) — nascosta per INFO_PAGE (solo cover ammessa) e FULLSCREEN_LOCK (solo contenuto kiosk) */}
  1113. {isEditing.cardType !== 'INFO_PAGE' && isEditing.cardType !== 'FULLSCREEN_LOCK' && (
  1114. <div>
  1115. <label className="block text-sm font-semibold text-gray-800 mb-1">
  1116. Gallery Media <span className="text-gray-400 font-normal text-xs">(images, videos or PDFs — PDF pages become images)</span>
  1117. </label>
  1118. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  1119. <label className="inline-block cursor-pointer bg-purple-50 hover:bg-purple-100 text-purple-700 font-semibold text-sm px-4 py-2 rounded-full transition-colors">
  1120. <input
  1121. type="file"
  1122. accept="image/*,video/*,application/pdf,.pdf,.mov,.qt,.mkv,.avi,.divx,.wmv,.asf,.flv,.f4v,.3gp,.3gpp,.3g2,.mts,.m2ts,.ts,.mpg,.mpeg,.vob,.mxf,.ogv,.ogg"
  1123. multiple
  1124. onChange={handleUploadExtraMedia}
  1125. hidden
  1126. />
  1127. Choose files…
  1128. </label>
  1129. {uploading['extraMedia'] && !pdfProgress && <p className="mt-2 text-sm text-purple-600 font-medium">Uploading...</p>}
  1130. {pdfProgress && (
  1131. <p className="mt-2 text-sm text-purple-600 font-medium">
  1132. Processing &ldquo;{pdfProgress.name}&rdquo;: page {pdfProgress.page} of {pdfProgress.total}
  1133. </p>
  1134. )}
  1135. </div>
  1136. {(isEditing.extraMedia || []).length > 0 && (
  1137. <div className="mt-3 space-y-2">
  1138. {(isEditing.extraMedia || []).map((item, i) => {
  1139. const video = isVideoUrl(item.url);
  1140. const tc = transcodeJobs[item.url];
  1141. const isTranscoding = !!tc && (tc.status === 'queued' || tc.status === 'running');
  1142. return (
  1143. <div key={item.url + i} className="flex items-center gap-3 p-2 bg-gray-50 border border-gray-200 rounded-lg">
  1144. <div className="relative w-16 h-16 rounded-md overflow-hidden bg-black shrink-0">
  1145. {video ? (
  1146. <>
  1147. <video src={withBasePath(item.url)} className="w-full h-full object-cover" muted preload="metadata" />
  1148. <div className="absolute inset-0 flex items-center justify-center bg-black/30 text-white text-xl">▶</div>
  1149. </>
  1150. ) : (
  1151. <img src={withBasePath(item.url)} className="w-full h-full object-cover" alt="" />
  1152. )}
  1153. {isTranscoding && (
  1154. <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/75 text-white text-[10px] font-semibold leading-tight gap-0.5">
  1155. <span>Transcoding</span>
  1156. <span>{Math.round((tc.progress || 0) * 100)}%</span>
  1157. </div>
  1158. )}
  1159. <span className="absolute bottom-0 left-0 right-0 text-center text-white text-[10px] bg-black/60">{i + 1}</span>
  1160. </div>
  1161. <div className="flex-1 min-w-0">
  1162. <div className="text-xs font-semibold text-gray-700 uppercase tracking-wider">
  1163. {video ? 'Video' : 'Image'}
  1164. </div>
  1165. {video && (
  1166. <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
  1167. <label className="flex items-center gap-2 cursor-pointer">
  1168. <input
  1169. type="checkbox"
  1170. checked={!!item.autoplay}
  1171. onChange={() => toggleAutoplay(i)}
  1172. className="w-4 h-4 text-blue-600 rounded"
  1173. />
  1174. <span className="text-sm text-gray-700">Autoplay</span>
  1175. </label>
  1176. <label className="flex items-center gap-2 cursor-pointer">
  1177. <input
  1178. type="checkbox"
  1179. checked={!!item.muted}
  1180. onChange={() => toggleMuted(i)}
  1181. className="w-4 h-4 text-blue-600 rounded"
  1182. />
  1183. <span className="text-sm text-gray-700">Muted</span>
  1184. </label>
  1185. </div>
  1186. )}
  1187. </div>
  1188. <button
  1189. onClick={() => moveExtraMedia(i, 'up')}
  1190. className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:outline-none"
  1191. title="Move up"
  1192. aria-label="Move up"
  1193. disabled={i === 0}
  1194. >↑</button>
  1195. <button
  1196. onClick={() => moveExtraMedia(i, 'down')}
  1197. className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:outline-none"
  1198. title="Move down"
  1199. aria-label="Move down"
  1200. disabled={i === (isEditing.extraMedia || []).length - 1}
  1201. >↓</button>
  1202. <a
  1203. href={withBasePath(item.url)}
  1204. download={extractFileName(item.url)}
  1205. className="bg-gray-500 hover:bg-gray-600 text-white w-8 h-8 rounded-full text-sm font-bold shrink-0 flex items-center justify-center"
  1206. title="Download"
  1207. aria-label="Download"
  1208. >⬇</a>
  1209. <button
  1210. onClick={() => removeExtraMedia(i)}
  1211. className="bg-red-500 hover:bg-red-600 text-white w-8 h-8 rounded-full text-sm font-bold shrink-0"
  1212. title="Remove"
  1213. >✕</button>
  1214. </div>
  1215. );
  1216. })}
  1217. </div>
  1218. )}
  1219. </div>
  1220. )}
  1221. </div>
  1222. </div>
  1223. <div className="flex gap-3 pt-8 mt-6 border-t border-gray-200 justify-end">
  1224. <button onClick={() => setIsEditing(null)} className="px-5 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors">
  1225. Cancel
  1226. </button>
  1227. <button onClick={handleSaveCard} className="bg-green-600 text-white px-8 py-2.5 rounded-lg hover:bg-green-700 font-medium shadow-sm transition-colors">
  1228. Save Card
  1229. </button>
  1230. </div>
  1231. </div>
  1232. </div>
  1233. )}
  1234. {/* CUSTOM CONFIRM DIALOG */}
  1235. {confirmDialog && (
  1236. <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200">
  1237. <div className="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full animate-in zoom-in-95">
  1238. <h3 className="text-xl font-bold text-gray-900 mb-2">Confirm Action</h3>
  1239. <p className="text-gray-600 mb-6 leading-relaxed">{confirmDialog.message}</p>
  1240. <div className="flex justify-end gap-3">
  1241. <button
  1242. onClick={() => setConfirmDialog(null)}
  1243. className="px-4 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors"
  1244. >
  1245. Cancel
  1246. </button>
  1247. <button
  1248. onClick={confirmDialog.onConfirm}
  1249. className="px-6 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium transition-colors shadow-sm"
  1250. >
  1251. Delete
  1252. </button>
  1253. </div>
  1254. </div>
  1255. </div>
  1256. )}
  1257. {/* CUSTOM TOAST NOTIFICATION */}
  1258. {toast && (
  1259. <div className={`fixed bottom-6 right-6 z-[70] text-white px-6 py-4 rounded-lg shadow-2xl flex items-start gap-3 animate-in slide-in-from-bottom-5 fade-in duration-300 max-w-md ${
  1260. toast.type === 'error' ? 'bg-red-700' : 'bg-gray-900'
  1261. }`}>
  1262. <div className={`w-6 h-6 rounded-full flex items-center justify-center font-bold text-sm shrink-0 mt-0.5 ${
  1263. toast.type === 'error' ? 'bg-white text-red-700' : 'bg-green-500 text-gray-900'
  1264. }`}>
  1265. {toast.type === 'error' ? '!' : '✓'}
  1266. </div>
  1267. <span className="font-medium leading-snug">{toast.message}</span>
  1268. </div>
  1269. )}
  1270. </div>
  1271. );
  1272. }