merge new_starr_app@qas history into apps/web

git-subtree-dir: apps/web
git-subtree-mainline: eaa6d2276a
git-subtree-split: 459af9d46a
This commit is contained in:
2026-08-24 12:21:16 +08:00
699 changed files with 103969 additions and 0 deletions
@@ -0,0 +1,404 @@
import { useRef, useState, useEffect, useCallback } from "react";
import {
Music2,
RotateCcw,
RotateCw,
Play,
Pause,
VolumeOff,
Volume2,
} from "lucide-react";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { AssetPickerSheet } from "../../AssetPickerSheet";
import api from "@/utils/api.util";
import { MediaFallback } from "@/components/generic/MediaFallback";
import { Spinner } from "@/components/ui/spinner";
import { formatPlayerTime as fmtTime } from "@/utils/format.util";
const API_BASE = (import.meta.env.VITE_API_URL ?? "http://localhost:3024").replace(/\/$/, "");
const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2];
// ─── AudioBlock (Admin) ───────────────────────────────────────────────────────
export function AudioBlock({ content, onUpdate, readOnly = false }) {
const [pickerOpen, setPickerOpen] = useState(false);
// ── S3 token state — fetched when storage_provider is "s3" ───────────────
const [streamSrc, setStreamSrc] = useState(null);
const [streamThumb, setStreamThumb] = useState(null);
const [tokenLoading, setTokenLoading] = useState(false);
const audioRef = useRef(null);
const [playing, setPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [buffered, setBuffered] = useState(0);
const [duration, setDuration] = useState(0);
const [volume, setVolume] = useState(1);
const [muted, setMuted] = useState(false);
const [speedIdx, setSpeedIdx] = useState(2); // 1×
// True from the moment `src` is set until the browser has actually
// buffered enough to play (or stalls mid-playback) — same gap VideoBlock
// closes, so a slow-loading audio file doesn't just sit there silently.
const [mediaLoading, setMediaLoading] = useState(true);
const assetId = content.asset_id ?? null;
const storageProvider = content.storage_provider ?? null;
const isS3 = storageProvider === "s3";
// For S3 assets, use the stream URL fetched via admin token.
// For all other providers, use the raw url/src from block content.
const src = isS3 ? (streamSrc ?? "") : (content.url ?? content.src ?? "");
const title = content.title ?? "Audio";
const artist = content.artist ?? "";
const tag = content.tag ?? "";
const thumbnail = isS3 ? (streamThumb ?? content.thumbnail ?? null) : (content.thumbnail ?? null);
// ── Fetch admin token for S3 assets ───────────────────────────────────────
useEffect(() => {
if (!assetId || !isS3) {
setStreamSrc(null);
setStreamThumb(null);
return;
}
let cancelled = false;
setTokenLoading(true);
api.post("/admin/media/token", { asset_id: assetId })
.then(({ data }) => {
if (cancelled) return;
const { token, thumbnail_url } = data?.data ?? {};
if (token) setStreamSrc(`${API_BASE}/client/media/stream/${token}`);
if (thumbnail_url) setStreamThumb(thumbnail_url);
})
.catch(() => { /* non-fatal — player shows nothing */ })
.finally(() => { if (!cancelled) setTokenLoading(false); });
return () => { cancelled = true; };
}, [assetId, isS3]);
// Reset the loading spinner whenever the src actually changes (new
// asset picked, or the S3 token above just resolved).
useEffect(() => { setMediaLoading(true); }, [src]);
// ── Audio events ──────────────────────────────────────────────────────────
const onTimeUpdate = useCallback(() => setCurrentTime(audioRef.current?.currentTime ?? 0), []);
const onLoadedMeta = useCallback(() => setDuration(audioRef.current?.duration ?? 0), []);
const onEnded = useCallback(() => setPlaying(false), []);
const onProgress = useCallback(() => {
const el = audioRef.current;
if (el?.buffered.length && el.duration) {
setBuffered((el.buffered.end(el.buffered.length - 1) / el.duration) * 100);
}
}, []);
const onLoadedData = useCallback(() => setMediaLoading(false), []);
const onCanPlay = useCallback(() => setMediaLoading(false), []);
const onWaiting = useCallback(() => setMediaLoading(true), []);
const onPlaying = useCallback(() => setMediaLoading(false), []);
// ── Controls ──────────────────────────────────────────────────────────────
const togglePlay = () => {
const el = audioRef.current;
if (!el) return;
if (playing) { el.pause(); setPlaying(false); }
else { el.play(); setPlaying(true); }
};
const seek = (e) => {
const el = audioRef.current;
const bar = e.currentTarget;
const pct = (e.clientX - bar.getBoundingClientRect().left) / bar.offsetWidth;
el.currentTime = pct * duration;
};
const skip = (secs) => {
const el = audioRef.current;
if (!el) return;
el.currentTime = Math.min(Math.max(0, el.currentTime + secs), duration);
};
const handleVolume = (e) => {
const v = parseFloat(e.target.value);
setVolume(v);
if (audioRef.current) audioRef.current.volume = v;
setMuted(v === 0);
};
const toggleMute = () => {
const el = audioRef.current;
if (!el) return;
el.muted = !muted;
setMuted(!muted);
};
const cycleSpeed = () => {
const next = (speedIdx + 1) % SPEEDS.length;
setSpeedIdx(next);
if (audioRef.current) audioRef.current.playbackRate = SPEEDS[next];
};
const progress = duration > 0 ? (currentTime / duration) * 100 : 0;
// ── Asset picker handler ──────────────────────────────────────────────────
//
// Stores all metadata needed by the client AudioBlock at render time so
// the client never needs a separate API call to fetch asset details.
//
// Fields saved to block content:
// asset_id — used by client for the secure token flow
// url — used by admin player (direct src); ignored by client for S3
// title — display name (kept if already customised, else asset name)
// artist — cleared on new pick so stale artist doesn't carry over
// thumbnail — cover art from asset.thumbnail_url
// tag — file extension badge e.g. "MP3"
// duration_seconds — probed media length, read by duration.util.js on save
//
const handleSelect = (asset) => {
onUpdate({
asset_id: asset.asset_id,
// url is null for S3 (redacted server-side); Chibisafe/CDN keeps its raw URL
url: asset.file_url ?? null,
storage_provider: asset.storage_provider ?? null,
title: asset.display_name,
artist: "",
thumbnail: asset.thumbnail_url ?? null,
tag: asset.extension?.toUpperCase() ?? "",
duration_seconds: Number(asset.duration) || 0,
});
setPlaying(false);
setCurrentTime(0);
setDuration(0);
setBuffered(0);
setStreamSrc(null);
setStreamThumb(null);
};
// ─────────────────────────────────────────────────────────────────────────
return (
<div className="space-y-3">
{!readOnly && <Label>Audio</Label>}
{isS3 && tokenLoading ? (
<MediaFallback className="w-full h-28 rounded-xl border border-border" />
) : src ? (
<div className="w-full rounded-xl overflow-hidden border border-border bg-card text-card-foreground shadow-sm">
<audio
ref={audioRef}
src={src}
onTimeUpdate={onTimeUpdate}
onLoadedMetadata={onLoadedMeta}
onEnded={onEnded}
onProgress={onProgress}
onLoadedData={onLoadedData}
onCanPlay={onCanPlay}
onWaiting={onWaiting}
onPlaying={onPlaying}
preload="metadata"
/>
{/* ── Header ── */}
<div className="relative overflow-hidden">
{thumbnail ? (
<div
className="absolute inset-0 scale-110"
style={{
backgroundImage: `url(${thumbnail})`,
backgroundSize: "cover",
backgroundPosition: "center",
filter: "blur(24px) brightness(0.35)",
}}
/>
) : (
<div className="absolute inset-0 bg-primary" />
)}
<div className="relative z-10 flex items-center gap-4 p-4 text-white">
<div className="shrink-0 w-20 h-20 rounded-md overflow-hidden bg-black/25 flex items-center justify-center">
{mediaLoading ? (
<Spinner className="size-6 text-white" />
) : thumbnail ? (
<img src={thumbnail} alt={title} className="w-full h-full object-cover" />
) : (
<Music2 className="w-7 h-7 text-white/30" />
)}
</div>
<div className="flex flex-col gap-1 flex-1 min-w-0">
{tag && (
<div className="text-xs font-semibold rounded-full uppercase px-2 py-0.5 bg-card text-card-foreground border w-fit">
{tag}
</div>
)}
<p className="text-sm font-semibold leading-snug line-clamp-3">{title}</p>
{artist && <p className="text-xs text-white/60 line-clamp-2">{artist}</p>}
</div>
</div>
</div>
{/* ── Controls ── */}
<div className="px-4 pb-4 pt-3 space-y-3">
{/* Progress bar */}
<div className="flex items-center gap-2.5">
<span className="text-xs tabular-nums text-muted-foreground w-8 shrink-0">
{fmtTime(currentTime)}
</span>
<div
className="flex-1 h-1.5 rounded-full bg-muted cursor-pointer relative group"
onClick={seek}
role="slider"
aria-label="Seek"
aria-valuenow={Math.round(progress)}
aria-valuemin={0}
aria-valuemax={100}
>
<div
className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/25 transition-[width] duration-300"
style={{ width: `${buffered}%` }}
/>
<div
className="h-full rounded-full bg-primary transition-all relative"
style={{ width: `${progress}%` }}
/>
<div
className="absolute top-1/2 w-3 h-3 rounded-full bg-primary opacity-0 group-hover:opacity-100 transition-opacity"
style={{ left: `${progress}%`, transform: "translate(-50%, -50%)" }}
/>
</div>
<span className="text-xs tabular-nums text-muted-foreground w-8 shrink-0 text-right">
{fmtTime(duration)}
</span>
</div>
{/* Button row */}
<div className="grid grid-cols-3 items-center">
{/* Volume */}
<div className="flex items-center gap-1.5">
<button
onClick={toggleMute}
aria-label={muted ? "Unmute" : "Mute"}
className="w-7 h-7 flex items-center justify-center rounded-full text-foreground hover:bg-muted transition-colors"
>
{muted || volume === 0
? <VolumeOff className="size-4" />
: <Volume2 className="size-4" />
}
</button>
<input
type="range" min="0" max="1" step="0.05"
value={muted ? 0 : volume}
onChange={handleVolume}
aria-label="Volume"
className="w-16 h-1.5 accent-primary cursor-pointer
[&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:size-3 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-webkit-slider-thumb]:cursor-pointer
[&::-moz-range-thumb]:appearance-none [&::-moz-range-thumb]:size-3 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:cursor-pointer"
/>
</div>
{/* Play controls */}
<div className="flex items-center justify-center gap-2">
<button
onClick={() => skip(-10)}
aria-label="Rewind 10s"
className="p-2 flex items-center justify-center rounded-full text-foreground hover:bg-muted transition-colors"
>
<RotateCcw className="size-4" />
</button>
<button
onClick={togglePlay}
aria-label={playing ? "Pause" : "Play"}
className="p-3 rounded-full flex items-center justify-center bg-primary text-primary-foreground hover:opacity-80 transition-opacity active:scale-95 shadow-md"
>
{playing
? <Pause className="size-4" />
: <Play className="size-4" />
}
</button>
<button
onClick={() => skip(10)}
aria-label="Forward 10s"
className="p-2 flex items-center justify-center rounded-full text-foreground hover:bg-muted transition-colors"
>
<RotateCw className="size-4" />
</button>
</div>
{/* Speed */}
<div className="flex items-center justify-end">
<button
onClick={cycleSpeed}
aria-label={`Speed ${SPEEDS[speedIdx]}x`}
className="h-7 px-2 rounded text-sm font-medium text-foreground hover:bg-muted transition-colors tabular-nums"
>
{SPEEDS[speedIdx]}x
</button>
</div>
</div>
</div>
{/* ── Change audio (admin only) ── */}
{!readOnly && (
<div className="px-4 pb-4">
<button
type="button"
onClick={() => setPickerOpen(true)}
className="w-full text-sm text-muted-foreground border rounded-md py-1.5 hover:bg-muted transition-colors"
>
Change audio
</button>
</div>
)}
</div>
) : (
<button
type="button"
onClick={() => !readOnly && setPickerOpen(true)}
className="w-full py-12 rounded-lg border-2 border-dashed border-muted-foreground/30 hover:border-primary/50 hover:bg-muted/20 transition-colors flex flex-col items-center justify-center gap-2"
>
<Music2 className="h-8 w-8 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">Click to select an audio file</p>
</button>
)}
{/* ── Metadata fields (admin only) ─────────────────────────────────
These fields are saved into block content and rendered directly
by the client AudioBlock — no extra API call needed at runtime. */}
{!readOnly && src && (
<div className="space-y-3 pt-1">
<div className="space-y-1.5">
<Label htmlFor="audio-title">Title</Label>
<Textarea
id="audio-title"
rows={2}
value={content.title ?? ""}
onChange={(e) => onUpdate({ ...content, title: e.target.value })}
placeholder="Track title"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="audio-artist">Artist / Subtitle</Label>
<Textarea
id="audio-artist"
rows={2}
value={content.artist ?? ""}
onChange={(e) => onUpdate({ ...content, artist: e.target.value })}
placeholder="Artist name or subtitle"
/>
</div>
</div>
)}
{/* ── Asset picker ── */}
{!readOnly && (
<AssetPickerSheet
open={pickerOpen}
onOpenChange={setPickerOpen}
fileType="audio"
onSelect={handleSelect}
/>
)}
</div>
);
}
@@ -0,0 +1,48 @@
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
const LANGUAGES = [
{ value: "html", label: "HTML" },
{ value: "css", label: "CSS" },
{ value: "javascript", label: "JavaScript" },
{ value: "typescript", label: "TypeScript" },
{ value: "jsx", label: "JSX / TSX" },
{ value: "python", label: "Python" },
{ value: "sql", label: "SQL" },
{ value: "bash", label: "Shell / Bash" },
{ value: "json", label: "JSON" },
{ value: "text", label: "Plain Text" },
];
export function CodeBlock({ content, onUpdate }) {
return (
<div className="space-y-3">
<div className="flex items-center gap-3">
<Label>Language</Label>
<select
value={content.language ?? "javascript"}
onChange={(e) => onUpdate({ ...content, language: e.target.value })}
className="h-7 text-xs border rounded px-2 bg-background cursor-pointer"
>
{LANGUAGES.map((l) => (
<option key={l.value} value={l.value}>{l.label}</option>
))}
</select>
</div>
<div className="space-y-1.5">
<Label>Code</Label>
<Textarea
value={content.code ?? ""}
onChange={(e) => onUpdate({ ...content, code: e.target.value })}
placeholder="// Write or paste your code here..."
className="font-mono text-sm min-h-[180px] resize-y leading-relaxed"
spellCheck={false}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
/>
</div>
</div>
);
}
@@ -0,0 +1,86 @@
import { useState } from "react";
import { ImageIcon } from "lucide-react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { AssetPickerSheet } from "../../AssetPickerSheet";
import { useAssetPreviewSrc } from "@/hooks/useAssetPreviewSrc";
import { MediaFallback } from "@/components/generic/MediaFallback";
function MediaPlaceholder({ onClick }) {
return (
<button
type="button"
onClick={onClick}
className="w-full aspect-video rounded-lg border-2 border-dashed border-muted-foreground/30 hover:border-primary/50 hover:bg-muted/20 transition-colors flex flex-col items-center justify-center gap-2"
>
<ImageIcon className="h-8 w-8 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">
Click to select an image
</p>
</button>
);
}
export function ImageBlock({ content, onUpdate, readOnly = false }) {
const [pickerOpen, setPickerOpen] = useState(false);
// content.url is redacted (null) server-side for S3 assets — see
// redactS3Url() in controllers/admin/assets.controller.js. Re-resolve
// through media.util.js instead of trusting the persisted url/thumbnail.
const { src, loading } = useAssetPreviewSrc(
{ asset_id: content?.asset_id, storage_provider: content?.storage_provider, file_url: content?.url, thumbnail_url: content?.url },
{ scope: "admin" },
);
return (
<div className="space-y-3">
<Label>Image</Label>
{loading ? (
<MediaFallback className="w-full aspect-video rounded-lg" />
) : src ? (
<div
className="relative rounded-lg overflow-hidden cursor-pointer group"
onClick={() => setPickerOpen(true)}
>
<img
src={src}
alt={content.alt ?? ""}
className="w-full aspect-video object-cover"
/>
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
<p className="text-white text-sm font-medium">Change Image</p>
</div>
</div>
) : (
<MediaPlaceholder onClick={() => setPickerOpen(true)} />
)}
{content.asset_id && (
<div className="space-y-1.5">
<Label>Alt Text</Label>
<Input
placeholder="Describe the image..."
value={content.alt ?? ""}
onChange={(e) => onUpdate({ ...content, alt: e.target.value })}
/>
</div>
)}
{!readOnly && (
<AssetPickerSheet
open={pickerOpen}
onOpenChange={setPickerOpen}
fileType="image"
onSelect={(asset) => onUpdate({
...content,
asset_id: asset.asset_id,
storage_provider: asset.storage_provider ?? null,
url: asset.file_url,
})}
/>
)}
</div>
);
}
@@ -0,0 +1,157 @@
import { useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import {
Bold, Italic, Heading2, Code, Code2,
Link2, List, ListOrdered, Quote, Minus, Eye, Pencil,
} from "lucide-react";
// ─── Toolbar button ───────────────────────────────────────────────────────────
function ToolbarBtn({ title, onClick, children, active }) {
return (
<button
type="button"
title={title}
onMouseDown={(e) => { e.preventDefault(); onClick(); }}
className={cn(
"h-7 w-7 flex items-center justify-center rounded text-muted-foreground shrink-0",
"hover:bg-accent hover:text-accent-foreground transition-colors",
active && "bg-accent text-accent-foreground"
)}
>
{children}
</button>
);
}
function Divider() {
return <span className="w-px h-4 bg-border mx-0.5 shrink-0" />;
}
// ─── MarkdownBlock ────────────────────────────────────────────────────────────
export function MarkdownBlock({ content, onUpdate }) {
const [preview, setPreview] = useState(false);
const textareaRef = useRef(null);
const body = content.body ?? "";
// Insert markdown syntax at cursor, wrapping selection when applicable
const insert = (before, after = "", placeholder = "") => {
const el = textareaRef.current;
if (!el) return;
el.focus();
const start = el.selectionStart;
const end = el.selectionEnd;
const selected = body.slice(start, end) || placeholder;
const next = body.slice(0, start) + before + selected + after + body.slice(end);
onUpdate({ ...content, body: next });
// Restore cursor after React re-render
requestAnimationFrame(() => {
el.focus();
const cursor = start + before.length + selected.length + after.length;
el.setSelectionRange(cursor, cursor);
});
};
const insertLine = (prefix) => {
const el = textareaRef.current;
if (!el) return;
el.focus();
const start = el.selectionStart;
const lineStart = body.lastIndexOf("\n", start - 1) + 1;
const next = body.slice(0, lineStart) + prefix + body.slice(lineStart);
onUpdate({ ...content, body: next });
requestAnimationFrame(() => {
el.focus();
el.setSelectionRange(start + prefix.length, start + prefix.length);
});
};
return (
<div className="space-y-1.5">
<Label>Markdown Content</Label>
<div className="border rounded-md overflow-hidden focus-within:ring-2 focus-within:ring-ring">
{/* ── Toolbar ── */}
<div className="flex flex-wrap items-center gap-0.5 px-2 py-1.5 border-b bg-muted/40">
<ToolbarBtn title="Bold" onClick={() => insert("**", "**", "bold text")}>
<Bold className="h-3.5 w-3.5" />
</ToolbarBtn>
<ToolbarBtn title="Italic" onClick={() => insert("*", "*", "italic text")}>
<Italic className="h-3.5 w-3.5" />
</ToolbarBtn>
<Divider />
<ToolbarBtn title="Heading 2" onClick={() => insertLine("## ")}>
<Heading2 className="h-3.5 w-3.5" />
</ToolbarBtn>
<Divider />
<ToolbarBtn title="Inline code" onClick={() => insert("`", "`", "code")}>
<Code className="h-3.5 w-3.5" />
</ToolbarBtn>
<ToolbarBtn title="Code block" onClick={() => insert("```\n", "\n```", "your code here")}>
<Code2 className="h-3.5 w-3.5" />
</ToolbarBtn>
<Divider />
<ToolbarBtn title="Link" onClick={() => insert("[", "](url)", "link text")}>
<Link2 className="h-3.5 w-3.5" />
</ToolbarBtn>
<Divider />
<ToolbarBtn title="Bullet list" onClick={() => insertLine("- ")}>
<List className="h-3.5 w-3.5" />
</ToolbarBtn>
<ToolbarBtn title="Numbered list" onClick={() => insertLine("1. ")}>
<ListOrdered className="h-3.5 w-3.5" />
</ToolbarBtn>
<ToolbarBtn title="Blockquote" onClick={() => insertLine("> ")}>
<Quote className="h-3.5 w-3.5" />
</ToolbarBtn>
<ToolbarBtn title="Horizontal rule" onClick={() => insert("\n---\n", "", "")}>
<Minus className="h-3.5 w-3.5" />
</ToolbarBtn>
{/* Spacer */}
<div className="flex-1" />
{/* Preview toggle */}
<Divider />
<ToolbarBtn
title={preview ? "Edit" : "Preview"}
active={preview}
onClick={() => setPreview((p) => !p)}
>
{preview ? <Pencil className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
</ToolbarBtn>
</div>
{/* ── Edit / Preview ── */}
{preview ? (
<div className="min-h-[180px] px-3 py-3">
{body.trim() ? (
<div className="typeset text-sm">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{body}</ReactMarkdown>
</div>
) : (
<p className="text-xs text-muted-foreground italic">Nothing to preview yet.</p>
)}
</div>
) : (
<textarea
ref={textareaRef}
value={body}
onChange={(e) => onUpdate({ ...content, body: e.target.value })}
placeholder={"# Heading\n\nWrite **markdown** here...\n\n- List item\n- Another item\n\n```js\nconsole.log('hello')\n```"}
className="w-full min-h-[180px] resize-y px-3 py-2 text-sm font-mono focus:outline-none bg-background"
spellCheck={false}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
/>
)}
</div>
</div>
);
}
@@ -0,0 +1,425 @@
// components/generic/CMS/Blocks/TextBlock.jsx
import { useEffect, useRef, useState } from "react";
import {
Bold, Italic, Underline,
AlignLeft, AlignCenter, AlignRight, AlignJustify,
List, ListOrdered, Indent, Outdent,
Link2, FileText, Table, Code, Code2,
} from "lucide-react";
import { Label } from "@/components/ui/label";
import { AssetPickerSheet } from "../../AssetPickerSheet";
import { cn } from "@/lib/utils";
// ─── Toolbar button ───────────────────────────────────────────────────────────
function ToolbarBtn({ title, onMouseDown, active, children }) {
return (
<button
type="button"
title={title}
onMouseDown={onMouseDown}
className={cn(
"h-7 w-7 flex items-center justify-center rounded text-muted-foreground",
"hover:bg-accent hover:text-accent-foreground transition-colors shrink-0",
active && "bg-accent text-accent-foreground"
)}
>
{children}
</button>
);
}
// ─── Toolbar divider ──────────────────────────────────────────────────────────
function Divider() {
return <span className="w-px h-4 bg-border mx-0.5 shrink-0" />;
}
// ─── Format options ───────────────────────────────────────────────────────────
const FORMAT_OPTIONS = [
{ label: "Paragraph", val: "p" },
{ label: "Heading 1", val: "h1" },
{ label: "Heading 2", val: "h2" },
{ label: "Heading 3", val: "h3" },
];
// ─── Table picker popover ─────────────────────────────────────────────────────
// A small grid that lets the user hover to choose rows × columns (up to 8×8),
// then click to confirm. Rendered inline in the toolbar.
const MAX_ROWS = 8;
const MAX_COLS = 8;
function TablePicker({ onInsert, onClose }) {
const [hovered, setHovered] = useState({ r: 0, c: 0 });
return (
// Overlay — clicking outside closes the picker without inserting
<div className="fixed inset-0 z-50" onMouseDown={onClose}>
<div
className="absolute z-50 bg-popover border rounded-lg shadow-lg p-3 flex flex-col gap-2"
style={{ top: "var(--table-picker-y, 40px)", left: "var(--table-picker-x, 0px)" }}
onMouseDown={(e) => e.stopPropagation()}
>
{/* Label */}
<p className="text-xs text-muted-foreground select-none">
{hovered.r > 0 && hovered.c > 0
? `${hovered.r} × ${hovered.c} table`
: "Hover to select size"}
</p>
{/* Grid */}
<div
className="grid gap-0.5"
style={{ gridTemplateColumns: `repeat(${MAX_COLS}, 1.25rem)` }}
>
{Array.from({ length: MAX_ROWS }, (_, r) =>
Array.from({ length: MAX_COLS }, (_, c) => (
<div
key={`${r}-${c}`}
onMouseEnter={() => setHovered({ r: r + 1, c: c + 1 })}
onClick={() => {
onInsert(hovered.r, hovered.c);
onClose();
}}
className={cn(
"h-5 w-5 rounded-sm border cursor-pointer transition-colors",
r < hovered.r && c < hovered.c
? "bg-primary/20 border-primary/50"
: "bg-muted border-border"
)}
/>
))
)}
</div>
</div>
</div>
);
}
// ─── RichTextEditor ───────────────────────────────────────────────────────────
export function RichTextEditor({ blockId, value, onChange, readOnly = false }) {
const editorRef = useRef(null);
const initializedFor = useRef(null);
const savedRange = useRef(null);
const tableButtonRef = useRef(null);
const [docPickerOpen, setDocPickerOpen] = useState(false);
const [tablePickerOpen, setTablePickerOpen] = useState(false);
// ── Seed innerHTML exactly once per blockId ────────────────────────────────
useEffect(() => {
if (!editorRef.current) return;
if (initializedFor.current === blockId) return;
editorRef.current.innerHTML = value ?? "";
initializedFor.current = blockId;
}, [blockId, value]);
// ── Position the table picker below its toolbar button ────────────────────
useEffect(() => {
if (!tablePickerOpen || !tableButtonRef.current) return;
const rect = tableButtonRef.current.getBoundingClientRect();
document.documentElement.style.setProperty("--table-picker-y", `${rect.bottom + 6}px`);
document.documentElement.style.setProperty("--table-picker-x", `${rect.left}px`);
}, [tablePickerOpen]);
// ── execCommand helpers ────────────────────────────────────────────────────
const exec = (cmd, val = null) => {
editorRef.current?.focus();
document.execCommand(cmd, false, val);
};
const applyFormat = (val) => {
editorRef.current?.focus();
document.execCommand("formatBlock", false, `<${val}>`);
};
const isActive = (cmd) => {
try { return document.queryCommandState(cmd); } catch { return false; }
};
// ── URL link ──────────────────────────────────────────────────────────────
const insertUrlLink = () => {
const url = window.prompt("Enter URL:", "https://");
if (url) exec("createLink", url);
};
// ── Document link ─────────────────────────────────────────────────────────
const openDocPicker = () => {
const sel = window.getSelection();
if (sel && sel.rangeCount > 0) {
savedRange.current = sel.getRangeAt(0).cloneRange();
}
setDocPickerOpen(true);
};
const handleDocSelect = (asset) => {
setDocPickerOpen(false);
const url = asset.file_url;
const label = asset.display_name ?? "Document";
editorRef.current?.focus();
const sel = window.getSelection();
if (savedRange.current && sel) {
sel.removeAllRanges();
sel.addRange(savedRange.current);
}
const html = `<a href="${url}" class="doc-link" target="_blank" rel="noopener noreferrer">${label}</a>`;
document.execCommand("insertHTML", false, html);
onChange(editorRef.current.innerHTML);
savedRange.current = null;
};
// ── Inline code toggle ────────────────────────────────────────────────────
// Wraps the selected text in <code>. If the cursor is already inside a
// <code> element, unwraps it instead.
const toggleInlineCode = () => {
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0) return;
const range = sel.getRangeAt(0);
const ancestor = range.commonAncestorContainer;
const codeParent = (ancestor.nodeType === 3 ? ancestor.parentElement : ancestor)?.closest("code");
if (codeParent) {
const text = document.createTextNode(codeParent.textContent ?? "");
codeParent.replaceWith(text);
onChange(editorRef.current.innerHTML);
} else {
const text = sel.toString();
if (!text) return;
exec("insertHTML", `<code>${text}</code>`);
onChange(editorRef.current.innerHTML);
}
};
// ── Code block insertion ───────────────────────────────────────────────────
const insertCodeBlock = () => {
editorRef.current?.focus();
const sel = window.getSelection();
const selectedText = sel?.toString() || "// your code here";
exec("insertHTML", `<pre><code>${selectedText}</code></pre><p><br></p>`);
onChange(editorRef.current.innerHTML);
};
// ── Table insertion ────────────────────────────────────────────────────────
// Builds a <table> with a header row (th) + (rows-1) data rows.
// Each cell is contenteditable (inherited from the editor).
// A paragraph after the table lets the user continue typing below it.
const insertTable = (rows, cols) => {
if (rows < 1 || cols < 1) return;
// Save cursor before opening picker collapses it
editorRef.current?.focus();
const sel = window.getSelection();
if (savedRange.current && sel) {
sel.removeAllRanges();
sel.addRange(savedRange.current);
}
// Build header row
const headerCells = Array.from({ length: cols })
.map((_, i) => `<th>Column ${i + 1}</th>`)
.join("");
// Build body rows
const bodyRows = Array.from({ length: rows - 1 })
.map(() =>
`<tr>${Array.from({ length: cols }).map(() => "<td><br></td>").join("")}</tr>`
)
.join("");
const tableHTML = `
<table>
<thead><tr>${headerCells}</tr></thead>
<tbody>${bodyRows}</tbody>
</table>
<p><br></p>
`;
document.execCommand("insertHTML", false, tableHTML);
onChange(editorRef.current.innerHTML);
savedRange.current = null;
};
const openTablePicker = () => {
// Save current cursor so we can restore it after the picker closes
const sel = window.getSelection();
if (sel && sel.rangeCount > 0) {
savedRange.current = sel.getRangeAt(0).cloneRange();
}
setTablePickerOpen(true);
};
// ── Toolbar groups ─────────────────────────────────────────────────────────
const GROUPS = [
[
{ cmd: "bold", Icon: Bold, title: "Bold" },
{ cmd: "italic", Icon: Italic, title: "Italic" },
{ cmd: "underline", Icon: Underline, title: "Underline" },
],
[
{ cmd: "justifyLeft", Icon: AlignLeft, title: "Align left" },
{ cmd: "justifyCenter", Icon: AlignCenter, title: "Align center" },
{ cmd: "justifyRight", Icon: AlignRight, title: "Align right" },
{ cmd: "justifyFull", Icon: AlignJustify, title: "Justify" },
],
[
{ cmd: "insertUnorderedList", Icon: List, title: "Bullet list" },
{ cmd: "insertOrderedList", Icon: ListOrdered, title: "Numbered list" },
{ cmd: "indent", Icon: Indent, title: "Indent" },
{ cmd: "outdent", Icon: Outdent, title: "Outdent" },
],
];
return (
<>
<div className="border rounded-md overflow-hidden focus-within:ring-2 focus-within:ring-ring">
{/* ── Toolbar ── */}
<div className="flex flex-wrap items-center gap-0.5 px-2 py-1.5 border-b bg-muted/40">
{/* Block format select */}
<select
className="h-7 text-xs border rounded px-1 mr-0.5 bg-background cursor-pointer shrink-0"
defaultValue="p"
onChange={(e) => applyFormat(e.target.value)}
>
{FORMAT_OPTIONS.map((o) => (
<option key={o.val} value={o.val}>{o.label}</option>
))}
</select>
<Divider />
{/* Formatting groups */}
{GROUPS.map((group, gi) => (
<div key={gi} className="flex items-center gap-0.5">
{group.map(({ cmd, Icon, title }) => (
<ToolbarBtn
key={cmd}
title={title}
active={isActive(cmd)}
onMouseDown={(e) => { e.preventDefault(); exec(cmd); }}
>
<Icon className="h-3.5 w-3.5" />
</ToolbarBtn>
))}
<Divider />
</div>
))}
{/* URL link */}
<ToolbarBtn
title="Insert URL link"
onMouseDown={(e) => { e.preventDefault(); insertUrlLink(); }}
>
<Link2 className="h-3.5 w-3.5" />
</ToolbarBtn>
{/* Document link */}
<ToolbarBtn
title="Embed document link"
onMouseDown={(e) => { e.preventDefault(); openDocPicker(); }}
>
<FileText className="h-3.5 w-3.5" />
</ToolbarBtn>
<Divider />
{/* Insert table */}
<ToolbarBtn
title="Insert table"
active={tablePickerOpen}
onMouseDown={(e) => {
e.preventDefault();
tablePickerOpen ? setTablePickerOpen(false) : openTablePicker();
}}
>
<span ref={tableButtonRef} className="flex items-center justify-center">
<Table className="h-3.5 w-3.5" />
</span>
</ToolbarBtn>
<Divider />
{/* Inline code */}
<ToolbarBtn
title="Inline code"
onMouseDown={(e) => { e.preventDefault(); toggleInlineCode(); }}
>
<Code className="h-3.5 w-3.5" />
</ToolbarBtn>
{/* Code block */}
<ToolbarBtn
title="Code block"
onMouseDown={(e) => { e.preventDefault(); insertCodeBlock(); }}
>
<Code2 className="h-3.5 w-3.5" />
</ToolbarBtn>
</div>
{/* ── Editable area ── */}
<div
ref={editorRef}
contentEditable
suppressContentEditableWarning
onInput={() => onChange(editorRef.current.innerHTML)}
className="typeset min-h-[120px] px-3 m-0 py-0 text-sm focus:outline-none"
/>
</div>
{/* Table size picker */}
{tablePickerOpen && (
<TablePicker
onInsert={insertTable}
onClose={() => setTablePickerOpen(false)}
/>
)}
{/* Document asset picker */}
{!readOnly && (
<AssetPickerSheet
open={docPickerOpen}
onOpenChange={setDocPickerOpen}
fileType="document"
onSelect={handleDocSelect}
/>
)}
</>
);
}
// ─── TextBlock ────────────────────────────────────────────────────────────────
export function TextBlock({ content, onUpdate, blockId, readOnly = false }) {
if (readOnly) {
return (
<div
className="typeset text-sm"
dangerouslySetInnerHTML={{ __html: content.body ?? "" }}
/>
);
}
return (
<div className="space-y-1.5">
<Label>Content</Label>
<RichTextEditor
blockId={blockId}
value={content.body ?? ""}
onChange={(html) => onUpdate({ ...content, body: html })}
/>
</div>
);
}
@@ -0,0 +1,121 @@
// components/generic/CMS/Blocks/TextImageBlock.jsx
import { useState } from "react";
import { ImageIcon } from "lucide-react";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { RichTextEditor } from "./TextBlock"; // reuse the shared editor
import { AssetPickerSheet } from "../../AssetPickerSheet";
import { useAssetPreviewSrc } from "@/hooks/useAssetPreviewSrc";
import { MediaFallback } from "@/components/generic/MediaFallback";
export function TextImageBlock({ content, onUpdate, blockId, readOnly = false }) {
const [pickerOpen, setPickerOpen] = useState(false);
// content.url is redacted (null) server-side for S3 assets — re-resolve
// through media.util.js instead of trusting the persisted url/thumbnail.
const { src, loading } = useAssetPreviewSrc(
{ asset_id: content?.asset_id, storage_provider: content?.storage_provider, file_url: content?.url, thumbnail_url: content?.url },
{ scope: "admin" },
);
return (
<div className="space-y-4">
{/* ── Image position ── */}
<div className="space-y-1.5 max-w-[200px]">
<Label>Image Position</Label>
<Select
value={content.image_position ?? "right"}
onValueChange={(v) => onUpdate({ ...content, image_position: v })}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* ── Text side — WYSIWYG ── */}
<div className="space-y-1.5">
<Label>Content</Label>
<RichTextEditor
blockId={`${blockId}_text`}
value={content.body ?? ""}
onChange={(html) => onUpdate({ ...content, body: html })}
/>
</div>
{/* ── Image side ── */}
<div className={[
"space-y-1.5",
content.image_position === "left" ? "md:order-first" : "",
].join(" ")}>
<Label>Image</Label>
{loading ? (
<MediaFallback className="w-full aspect-video rounded-lg" />
) : src ? (
<div
className="relative rounded-lg overflow-hidden cursor-pointer group"
onClick={() => setPickerOpen(true)}
>
<img
src={src}
alt={content.alt ?? ""}
className="w-full aspect-video object-cover"
/>
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
<p className="text-white text-sm font-medium">Change Image</p>
</div>
</div>
) : (
<button
type="button"
onClick={() => setPickerOpen(true)}
className="w-full aspect-video rounded-lg border-2 border-dashed border-muted-foreground/30 hover:border-primary/50 hover:bg-muted/20 transition-colors flex flex-col items-center justify-center gap-2"
>
<ImageIcon className="h-8 w-8 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">Click to select an image</p>
</button>
)}
{content.asset_id && (
<div className="space-y-1.5">
<Label>Alt Text</Label>
<Input
placeholder="Describe the image..."
value={content.alt ?? ""}
onChange={(e) => onUpdate({ ...content, alt: e.target.value })}
/>
</div>
)}
</div>
</div>
{!readOnly && (
<AssetPickerSheet
open={pickerOpen}
onOpenChange={setPickerOpen}
fileType="image"
onSelect={(asset) => onUpdate({
...content,
asset_id: asset.asset_id,
storage_provider: asset.storage_provider ?? null,
url: asset.file_url,
})}
/>
)}
</div>
);
}
@@ -0,0 +1,124 @@
// components/generic/CMS/Blocks/TextVideoBlock.jsx
import { useState } from "react";
import { VideoIcon } from "lucide-react";
import { Label } from "@/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { RichTextEditor } from "./TextBlock"; // reuse the shared editor
import { AssetPickerSheet } from "../../AssetPickerSheet";
import { useAssetPreviewSrc } from "@/hooks/useAssetPreviewSrc";
import { MediaFallback } from "@/components/generic/MediaFallback";
export function TextVideoBlock({ content, onUpdate, blockId, readOnly = false }) {
const [pickerOpen, setPickerOpen] = useState(false);
// content.thumbnail_url is a presigned S3 URL captured at pick time for
// S3 assets — it expires. Re-resolve through media.util.js instead of
// trusting the persisted value, mirroring VideoBlock.jsx.
const { thumbnailUrl, loading } = useAssetPreviewSrc(
{ asset_id: content?.asset_id, storage_provider: content?.storage_provider, file_url: content?.url, thumbnail_url: content?.thumbnail_url },
{ scope: "admin" },
);
const thumb = thumbnailUrl ?? content.thumbnail_url ?? null;
return (
<div className="space-y-4">
{/* ── Video position ── */}
<div className="space-y-1.5 max-w-[200px]">
<Label>Video Position</Label>
<Select
value={content.video_position ?? "right"}
onValueChange={(v) => onUpdate({ ...content, video_position: v })}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="left">Left</SelectItem>
<SelectItem value="right">Right</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* ── Text side — WYSIWYG ── */}
<div className="space-y-1.5">
<Label>Content</Label>
<RichTextEditor
blockId={`${blockId}_text`}
value={content.body ?? ""}
onChange={(html) => onUpdate({ ...content, body: html })}
/>
</div>
{/* ── Video side ── */}
<div className={[
"space-y-1.5",
content.video_position === "left" ? "md:order-first" : "",
].join(" ")}>
<Label>Video</Label>
{loading ? (
<MediaFallback className="w-full aspect-video rounded-lg" />
) : content.asset_id ? (
<div
className="relative rounded-lg overflow-hidden cursor-pointer group"
onClick={() => setPickerOpen(true)}
>
{thumb ? (
<img
src={thumb}
alt="Video thumbnail"
className="w-full aspect-video object-cover"
/>
) : (
<div className="w-full aspect-video bg-muted flex items-center justify-center">
<VideoIcon className="h-10 w-10 text-muted-foreground/50" />
</div>
)}
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
<p className="text-white text-sm font-medium">Change Video</p>
</div>
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="h-12 w-12 rounded-full bg-black/50 flex items-center justify-center">
<VideoIcon className="h-5 w-5 text-white" />
</div>
</div>
</div>
) : (
<button
type="button"
onClick={() => setPickerOpen(true)}
className="w-full aspect-video rounded-lg border-2 border-dashed border-muted-foreground/30 hover:border-primary/50 hover:bg-muted/20 transition-colors flex flex-col items-center justify-center gap-2"
>
<VideoIcon className="h-8 w-8 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">Click to select a video</p>
</button>
)}
</div>
</div>
{!readOnly && (
<AssetPickerSheet
open={pickerOpen}
onOpenChange={setPickerOpen}
fileType="video"
onSelect={(asset) => onUpdate({
...content,
asset_id: asset.asset_id,
storage_provider: asset.storage_provider ?? null,
url: asset.file_url,
thumbnail_url: asset.thumbnail_url ?? null,
duration_seconds: Number(asset.duration) || 0,
})}
/>
)}
</div>
);
}
@@ -0,0 +1,502 @@
import { useRef, useState, useEffect, useCallback } from "react";
import {
Play,
Pause,
SkipBack,
Volume2,
VolumeX,
Maximize2,
Minimize2,
VideoIcon,
} from "lucide-react";
import { Label } from "@/components/ui/label";
import { AssetPickerSheet } from "../../AssetPickerSheet";
import { useAssetPreviewSrc } from "@/hooks/useAssetPreviewSrc";
import { MediaFallback } from "@/components/generic/MediaFallback";
import { Spinner } from "@/components/ui/spinner";
import { formatPlayerTime as fmtTime } from "@/utils/format.util";
// ─── VideoBlock (Admin) ───────────────────────────────────────────────────────
export function VideoBlock({ content, onUpdate, readOnly = false }) {
const [pickerOpen, setPickerOpen] = useState(false);
// content.url is redacted (null) server-side for S3 assets — see
// redactS3Url() in controllers/admin/assets.controller.js. Re-resolve
// through media.util.js instead of trusting the persisted url/thumbnail.
//
// thumbnail_url is intentionally NOT passed here: resolveAssetSrc()'s fast
// path falls back to thumbnail_url when there's no stream_token, which for
// a video asset with a redacted (null) file_url meant `src` resolved to
// the poster JPEG instead of the video file, and the browser then refused
// to play it ("media resource ... was not suitable"). Omitting it forces
// the async mint-token path, which resolves the real video stream src.
const { src, loading } = useAssetPreviewSrc(
{ asset_id: content?.asset_id, storage_provider: content?.storage_provider, file_url: content?.url },
{ scope: "admin" },
);
const poster = content?.thumbnail_url ?? undefined;
const vidRef = useRef(null);
const wrapRef = useRef(null);
const [playing, setPlaying] = useState(false);
const [progress, setProgress] = useState(0);
const [currentTime, setCurrentTime] = useState(0);
const [totalDuration, setTotalDuration] = useState(0);
const [muted, setMuted] = useState(false);
const [volume, setVolume] = useState(1);
const [overlayVisible,setOverlayVisible]= useState(true);
// Native Fullscreen API works on desktop (all browsers) and Android Chrome.
// iOS Safari doesn't support Fullscreen API on arbitrary elements at all, so
// pseudoFullscreen is a CSS-only (fixed inset-0) fallback that keeps our
// custom controls instead of falling back to native <video> fullscreen.
const [nativeFullscreen, setNativeFullscreen] = useState(false);
const [pseudoFullscreen, setPseudoFullscreen] = useState(false);
const isFullscreen = nativeFullscreen || pseudoFullscreen;
// True from the moment `src` is set until the browser has actually
// buffered enough to render a frame (or stalls mid-playback) — closes the
// gap between "token resolved" (the `loading` from useAssetPreviewSrc
// above) and "video is actually watchable", which used to render as a
// blank black box with no indication anything was happening, especially
// on large/slow-loading files.
const [mediaLoading, setMediaLoading] = useState(true);
const [hoverProgress, setHoverProgress] = useState(null); // { x, time }
const previewVidRef = useRef(null);
// Fullscreen-only auto-hide for the controls bar, mirroring the client
// player: idle 3s while playing fades the bar out, any mouse movement (or
// a pause) brings it back. Outside fullscreen the bar stays put — it's a
// normal in-flow row there, not an overlay, so hiding it would just leave
// a blank gap.
const [controlsVisible, setControlsVisible] = useState(true);
const hideTimer = useRef(null);
// Reset player when video changes
useEffect(() => {
setPlaying(false);
setProgress(0);
setCurrentTime(0);
setTotalDuration(0);
setOverlayVisible(true);
setMediaLoading(true);
}, [src]);
// ── Video event listeners ─────────────────────────────────────────────────
useEffect(() => {
const v = vidRef.current;
if (!v) return;
const onTimeUpdate = () => {
setCurrentTime(v.currentTime);
if (v.duration) setProgress((v.currentTime / v.duration) * 100);
};
const onLoaded = () => setTotalDuration(v.duration);
const onEnded = () => { setPlaying(false); setOverlayVisible(true); };
const onLoadedData = () => setMediaLoading(false);
const onCanPlay = () => setMediaLoading(false);
const onWaiting = () => setMediaLoading(true);
const onPlaying = () => setMediaLoading(false);
v.addEventListener("timeupdate", onTimeUpdate);
v.addEventListener("loadedmetadata", onLoaded);
v.addEventListener("ended", onEnded);
v.addEventListener("loadeddata", onLoadedData);
v.addEventListener("canplay", onCanPlay);
v.addEventListener("waiting", onWaiting);
v.addEventListener("playing", onPlaying);
return () => {
v.removeEventListener("timeupdate", onTimeUpdate);
v.removeEventListener("loadedmetadata", onLoaded);
v.removeEventListener("ended", onEnded);
v.removeEventListener("loadeddata", onLoadedData);
v.removeEventListener("canplay", onCanPlay);
v.removeEventListener("waiting", onWaiting);
v.removeEventListener("playing", onPlaying);
};
}, [src]);
// ── Controls ──────────────────────────────────────────────────────────────
const resetHideTimer = useCallback(() => {
setControlsVisible(true);
clearTimeout(hideTimer.current);
if (playing && isFullscreen) {
hideTimer.current = setTimeout(() => setControlsVisible(false), 3000);
}
}, [playing, isFullscreen]);
useEffect(() => {
resetHideTimer();
return () => clearTimeout(hideTimer.current);
}, [playing, isFullscreen, resetHideTimer]);
const togglePlay = useCallback(() => {
const v = vidRef.current;
if (!v) return;
if (v.paused) { v.play(); setPlaying(true); setOverlayVisible(false); }
else { v.pause(); setPlaying(false); setOverlayVisible(true); }
}, []);
// Safari doesn't focus a <div tabIndex> on click, which silently kills
// keyboard shortcuts afterwards — force it explicitly.
const handleAreaClick = useCallback(() => {
wrapRef.current?.focus({ preventScroll: true });
togglePlay();
resetHideTimer();
}, [togglePlay, resetHideTimer]);
const restart = () => {
const v = vidRef.current;
if (!v) return;
v.currentTime = 0;
v.pause();
setPlaying(false);
setOverlayVisible(true);
};
const handleSeek = (e) => {
const v = vidRef.current;
if (!v || !v.duration) return;
v.currentTime = (parseFloat(e.target.value) / 100) * v.duration;
};
const handleVolumeChange = (e) => {
const val = parseFloat(e.target.value);
setVolume(val);
if (vidRef.current) { vidRef.current.volume = val; vidRef.current.muted = val === 0; }
setMuted(val === 0);
};
const toggleMute = () => {
const v = vidRef.current;
if (!v) return;
v.muted = !v.muted;
setMuted(v.muted);
};
const toggleFullscreen = () => {
// Uses wrapRef instead of getElementById so this works correctly even if
// an admin page ever renders more than one VideoBlock at once (an id
// lookup would always grab the first match, toggling the wrong player).
const el = wrapRef.current;
if (!el) return;
if (isFullscreen) {
if (document.fullscreenElement) document.exitFullscreen();
else if (document.webkitFullscreenElement) document.webkitExitFullscreen();
else setPseudoFullscreen(false);
} else if (el.requestFullscreen) {
el.requestFullscreen();
} else if (el.webkitRequestFullscreen) {
// Desktop Safari — supports element fullscreen via the prefixed API.
el.webkitRequestFullscreen();
} else {
// iOS Safari has no element-level Fullscreen API at all.
setPseudoFullscreen(true);
}
};
// Ignore keystrokes aimed at the seek/volume range inputs so arrow keys
// there keep their native behavior instead of double-seeking.
const handleKeyDown = useCallback((e) => {
if (e.target.tagName === "INPUT") return;
const v = vidRef.current;
// Fold single-char keys to lowercase so Shift/Caps-Lock doesn't break
// letter shortcuts (e.g. Shift+F reporting as "F", not "f").
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
switch (key) {
case " ":
e.preventDefault();
togglePlay();
break;
case "ArrowRight":
e.preventDefault();
if (v && v.duration) v.currentTime = Math.min(v.currentTime + 5, v.duration);
break;
case "ArrowLeft":
e.preventDefault();
if (v) v.currentTime = Math.max(v.currentTime - 5, 0);
break;
case "m":
e.preventDefault();
toggleMute();
break;
case "f":
e.preventDefault();
toggleFullscreen();
break;
case "Escape":
if (isFullscreen) {
e.preventDefault();
toggleFullscreen();
}
break;
default: break;
}
}, [togglePlay, toggleMute, toggleFullscreen, isFullscreen]);
// #video-block-wrap now wraps both the video area and the controls bar
// below it (previously just the video), so fullscreen no longer drops the
// seek bar / volume / fullscreen button. isFullscreen also relaxes the
// 16/9 + max-height constraints so the video fills the screen properly.
useEffect(() => {
// Safari (incl. desktop) still fires the prefixed webkitfullscreenchange
// event for element-level fullscreen, so both are listened for.
const onChange = () => {
const active = !!(document.fullscreenElement || document.webkitFullscreenElement);
setNativeFullscreen(active);
// Safari doesn't focus a <div tabIndex> on click, so keyboard
// shortcuts silently stop working after entering fullscreen unless we
// explicitly refocus the wrapper here.
if (active) wrapRef.current?.focus({ preventScroll: true });
};
document.addEventListener("fullscreenchange", onChange);
document.addEventListener("webkitfullscreenchange", onChange);
return () => {
document.removeEventListener("fullscreenchange", onChange);
document.removeEventListener("webkitfullscreenchange", onChange);
};
}, []);
// CSS pseudo-fullscreen fallback (iOS Safari) — lock page scroll and
// reclaim keyboard focus while it's active, restore on exit/unmount.
useEffect(() => {
if (!pseudoFullscreen) return;
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
wrapRef.current?.focus({ preventScroll: true });
return () => { document.body.style.overflow = prevOverflow; };
}, [pseudoFullscreen]);
// ── Asset picker handler ──────────────────────────────────────────────────
//
// Saves all metadata needed by the client VideoBlock at render time.
// Clean object — no ...content spread so stale data never carries over.
//
// Fields saved:
// asset_id — used by client for the secure token flow
// url — used by admin player (direct src); ignored by client for S3
// thumbnail_url — poster image for the video player
// title — display name (shown in any title-aware blocks)
// tag — file extension badge e.g. "MP4"
// duration_seconds — probed media length, read by duration.util.js on save
//
const handleSelect = (asset) => {
onUpdate({
asset_id: asset.asset_id,
storage_provider: asset.storage_provider ?? null,
url: asset.file_url,
thumbnail_url: asset.thumbnail_url ?? null,
title: asset.display_name,
tag: asset.extension?.toUpperCase() ?? "",
duration_seconds: Number(asset.duration) || 0,
});
setPlaying(false);
setProgress(0);
setCurrentTime(0);
setTotalDuration(0);
setOverlayVisible(true);
};
// ─────────────────────────────────────────────────────────────────────────
return (
<div className="space-y-3">
{!readOnly && <Label>Video</Label>}
{loading ? (
<MediaFallback className="w-full aspect-video rounded-lg" />
) : src ? (
<div
id="video-block-wrap"
ref={wrapRef}
tabIndex={0}
onKeyDown={handleKeyDown}
onMouseMove={isFullscreen ? resetHideTimer : undefined}
className={`overflow-hidden bg-card outline-none focus-visible:ring-2 focus-visible:ring-ring ${isFullscreen ? "fixed inset-0 z-[100] flex flex-col" : "rounded-lg border"}`}
>
{/* ── Video area ── */}
<div
className={`relative w-full bg-black cursor-pointer group ${isFullscreen ? "flex-1 min-h-0" : ""}`}
style={isFullscreen ? undefined : { aspectRatio: "16/9", maxHeight: "calc(100vh - 260px)" }}
onClick={handleAreaClick}
>
<video
ref={vidRef}
src={src}
poster={poster}
preload="metadata"
playsInline
className="w-full h-full object-cover"
/>
{/* Loading spinner — covers the gap between src resolving and the
browser actually having a frame to show */}
{mediaLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 pointer-events-none">
<Spinner className="size-8 text-white" />
</div>
)}
{/* Play/pause overlay */}
{!mediaLoading && (
<div
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-200 ${overlayVisible ? "opacity-100" : "opacity-0 pointer-events-none"}`}
style={{ background: "rgba(0,0,0,0.3)" }}
>
<button
aria-label={playing ? "Pause" : "Play"}
onClick={(e) => { e.stopPropagation(); togglePlay(); }}
className="w-12 h-12 rounded-full bg-white/90 hover:bg-white flex items-center justify-center transition-transform hover:scale-105"
>
{playing
? <Pause className="size-4 text-black" />
: <Play className="size-4 text-black ml-0.5" />
}
</button>
</div>
)}
{/* Change video hover hint */}
{!readOnly && (
<div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
<button
className="text-xs bg-black/60 hover:bg-black/80 text-white px-2.5 py-1 rounded-md transition-colors"
onClick={(e) => { e.stopPropagation(); setPickerOpen(true); }}
>
Change
</button>
</div>
)}
</div>
{/* ── Player controls ──
Fullscreen: absolutely positioned over the bottom of the video
(wrap is `fixed inset-0` there, so it's the containing block)
and fades per controlsVisible. Non-fullscreen: normal in-flow
row below the video, always visible. */}
<div className={
isFullscreen
? `absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/40 to-transparent px-4 pt-8 pb-4 flex flex-col gap-2 transition-opacity duration-300 ${controlsVisible ? "opacity-100" : "opacity-0 pointer-events-none"}`
: "px-3 pt-2.5 pb-3 flex flex-col gap-2"
}>
{/* Progress bar */}
<div
className={`relative h-1 rounded-full cursor-pointer ${isFullscreen ? "bg-white/30" : "bg-border"}`}
onMouseMove={(e) => {
const rect = e.currentTarget.getBoundingClientRect();
const pct = Math.min(Math.max((e.clientX - rect.left) / rect.width, 0), 1);
const time = pct * (vidRef.current?.duration ?? 0);
setHoverProgress({ x: e.clientX - rect.left, time });
if (previewVidRef.current && isFinite(time) && time >= 0) {
previewVidRef.current.currentTime = time;
}
}}
onMouseLeave={() => setHoverProgress(null)}
>
<div
className={`h-full rounded-full transition-[width] duration-100 ${isFullscreen ? "bg-white" : "bg-foreground"}`}
style={{ width: `${progress}%` }}
/>
<input
type="range" min="0" max="100" step="0.1"
value={progress}
onChange={handleSeek}
aria-label="Seek"
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
/>
{/* Scrub preview — hidden video seeked to hover position, no canvas/sprite needed */}
{hoverProgress && (
<div
className="absolute bottom-3 flex flex-col items-center pointer-events-none z-30"
style={{ left: `${hoverProgress.x}px`, transform: "translateX(-50%)" }}
>
<div className="rounded-md overflow-hidden border border-white/20 shadow-xl bg-black" style={{ width: 160, height: 90 }}>
<video
ref={previewVidRef}
src={src}
preload="auto"
muted
playsInline
disablePictureInPicture
disableRemotePlayback
onContextMenu={(e) => e.preventDefault()}
className="w-full h-full object-cover"
/>
</div>
<span className="text-white text-xs mt-1 font-medium tabular-nums drop-shadow bg-black/70 px-1.5 py-0.5 rounded">
{fmtTime(hoverProgress.time)}
</span>
</div>
)}
</div>
{/* Button row */}
<div className="flex items-center gap-2">
<button onClick={togglePlay} aria-label={playing ? "Pause" : "Play"} className={`transition-colors ${isFullscreen ? "text-white/80 hover:text-white" : "text-muted-foreground hover:text-foreground"}`}>
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
</button>
<button onClick={restart} aria-label="Restart" className={`transition-colors ${isFullscreen ? "text-white/80 hover:text-white" : "text-muted-foreground hover:text-foreground"}`}>
<SkipBack className="size-4" />
</button>
<span className={`text-xs tabular-nums ${isFullscreen ? "text-white/70" : "text-muted-foreground"}`}>
{fmtTime(currentTime)} / {fmtTime(totalDuration)}
</span>
<div className="flex items-center gap-1.5 ml-auto">
<button onClick={toggleMute} aria-label="Toggle mute" className={`transition-colors ${isFullscreen ? "text-white/80 hover:text-white" : "text-muted-foreground hover:text-foreground"}`}>
{muted ? <VolumeX className="size-4" /> : <Volume2 className="size-4" />}
</button>
<input
type="range" min="0" max="1" step="0.05"
value={muted ? 0 : volume}
onChange={handleVolumeChange}
aria-label="Volume"
className={`w-16 ${isFullscreen ? "accent-white" : "accent-foreground"}`}
/>
</div>
<button onClick={toggleFullscreen} aria-label={isFullscreen ? "Exit fullscreen" : "Fullscreen"} className={`transition-colors ml-1 ${isFullscreen ? "text-white/80 hover:text-white" : "text-muted-foreground hover:text-foreground"}`}>
{isFullscreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
</button>
</div>
</div>
{/* ── Change video footer (admin only) ── */}
{!readOnly && (
<div className="px-3 pb-3">
<button
type="button"
onClick={() => setPickerOpen(true)}
className="w-full text-sm text-muted-foreground border rounded-md py-1.5 hover:bg-muted transition-colors"
>
Change video
</button>
</div>
)}
</div>
) : (
<button
type="button"
onClick={() => setPickerOpen(true)}
className="w-full aspect-video rounded-lg border-2 border-dashed border-muted-foreground/30 hover:border-primary/50 hover:bg-muted/20 transition-colors flex flex-col items-center justify-center gap-2"
>
<VideoIcon className="h-8 w-8 text-muted-foreground/50" />
<p className="text-sm text-muted-foreground">Click to select a video</p>
</button>
)}
{!readOnly && (
<AssetPickerSheet
open={pickerOpen}
onOpenChange={setPickerOpen}
fileType="video"
onSelect={handleSelect}
/>
)}
</div>
);
}
@@ -0,0 +1,224 @@
// components/blocks/Banner.jsx
import { useEffect, useState } from "react";
import { Megaphone } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext } from "@/components/ui/carousel";
import { Progress } from "@/components/ui/progress";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { resolveAssetSrc } from "@/utils/media.util";
// An ad only ever has an internally-authored landing page when it has no
// redirect_link (see applyAdvertisementFields on the backend, which clears
// whichever one the admin didn't choose) — so its presence alone is enough
// to tell whether there's Page Builder content worth surfacing.
function hasLandingPage(ad) {
const page = ad?.landing_page;
if (!page) return false;
return Boolean(page.title || page.description || page.body || page.links?.length);
}
// ── Banner ───────────────────────────────────────────────────────────────────
/**
* Banner advertisement carousel — same carousel shell as Hero, so a placement
* with several live ads (e.g. tier_plans.banner) rotates through all of them
* instead of only ever showing the single highest-priority one.
* Every current-shape ad (content_mode "content") always shows its image with
* badge/headline/description layered on top, same as Hero — the whole slide
* is clickable through to the ad's redirect_link/landing page whenever it has
* no CTA buttons of its own. content_mode "image" is legacy-only (pre-dates
* the mandatory badge/headline/description/image/link shape) and keeps
* rendering as a bare clickable image with no text overlay.
*
* Props:
* ads — array of advertisement objects { content_mode, badge_labels, headline, description, ctas, redirect_link, image, image_url, advertisement_id }
* onCtaClick — (ad, cta) => void. cta is undefined for the whole-slide click.
*/
export function Banner({ ads, onCtaClick }) {
const [api, setApi] = useState();
const [current, setCurrent] = useState(0);
const [count, setCount] = useState(0);
const [viewAd, setViewAd] = useState(null); // ad whose Page Builder content is open in the Dialog
useEffect(() => {
if (!api) return;
setCount(api.scrollSnapList().length);
setCurrent(api.selectedScrollSnap() + 1);
api.on("select", () => {
setCurrent(api.selectedScrollSnap() + 1);
});
}, [api]);
if (!ads?.length) return null;
const progressValue = count ? (current / count) * 100 : 0;
return (
<div className="w-full">
<Carousel setApi={setApi} className="w-full">
<CarouselContent>
{ads.map((ad) => {
const imageSrc = resolveAssetSrc(ad.image) || ad.image_url || null;
const ctas = Array.isArray(ad.ctas) ? ad.ctas : [];
const badgeLabels = Array.isArray(ad.badge_labels) ? ad.badge_labels : [];
// Whole-slide click-through only makes sense when there's no CTA
// row of its own to carry that responsibility instead — a landing
// page (Page Builder content) always wins over the plain redirect.
const clickable = ctas.length === 0 && (hasLandingPage(ad) || ad.redirect_link);
const handleSlideClick = () => (hasLandingPage(ad) ? setViewAd(ad) : onCtaClick?.(ad, undefined));
return (
<CarouselItem key={ad.advertisement_id}>
{ad.content_mode !== "content" ? (
// ── Full Image (legacy Image Only ads with no badge/headline/description) ──
<button
type="button"
onClick={() => (hasLandingPage(ad) ? setViewAd(ad) : onCtaClick?.(ad, ctas[0]))}
className="relative w-full rounded-xl overflow-hidden bg-muted flex items-center justify-center text-left h-[clamp(180px,22vw,320px)] border"
>
{imageSrc ? (
<img
src={imageSrc}
alt={ad.headline || "Advertisement"}
className="w-full h-full object-cover pointer-events-none select-none"
/>
) : (
<Megaphone className="size-6 text-muted-foreground pointer-events-none select-none" />
)}
</button>
) : (
// ── Image + Content overlay ──
<div
role={clickable ? "button" : undefined}
tabIndex={clickable ? 0 : undefined}
onClick={clickable ? handleSlideClick : undefined}
onKeyDown={clickable ? (e) => { if (e.key === "Enter" || e.key === " ") handleSlideClick(); } : undefined}
className={"relative w-full rounded-xl overflow-hidden border text-left h-[clamp(180px,22vw,320px)]" + (clickable ? " cursor-pointer" : "")}
>
{imageSrc ? (
<img
src={imageSrc}
alt={ad.headline || "Advertisement"}
className="absolute inset-0 w-full h-full object-cover pointer-events-none select-none"
/>
) : (
<div className="absolute inset-0 bg-muted flex items-center justify-center">
<Megaphone className="size-6 text-muted-foreground" />
</div>
)}
<div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-transparent" />
<div className="relative h-full w-full flex items-center xs:p-5 sm:p-4 lg:p-10 text-white overflow-hidden">
<div className="md:w-2xl space-y-4 xs:p-1.5 lg:p-0">
{badgeLabels.length > 0 && (
<div className="flex items-center gap-1.5 flex-wrap">
{badgeLabels.map((label, i) => (
<Badge key={i} variant="outline" className="pointer-events-none select-none border-white/50 bg-white/10 text-white">
{label}
</Badge>
))}
</div>
)}
{ad.headline && <div className="pointer-events-none select-none lg:text-5xl xs:text-4xl font-geist font-bold lg:leading-16">{ad.headline}</div>}
{ad.description && <p className="pointer-events-none select-none leading-relaxed text-lg line-clamp-2">{ad.description}</p>}
{ctas.length > 0 && (
<div className="flex gap-3 items-center">
{ctas.map((cta, i) => (
<Button
key={i}
variant={cta.variant === "outline" ? "outline" : "secondary"}
onClick={() => onCtaClick?.(ad, cta)}
>
{cta.label}
</Button>
))}
</div>
)}
</div>
</div>
</div>
)}
</CarouselItem>
);
})}
</CarouselContent>
{/* Navigation and Progress — only meaningful with more than one slide */}
{ads.length > 1 && (
<div className="flex items-center justify-between mt-4">
<div className="flex items-center gap-2">
<CarouselPrevious className="static translate-y-0 size-8 rounded-lg" />
<CarouselNext className="static translate-y-0 size-8 rounded-lg" />
</div>
<div className="flex-1 max-w-24 ml-4">
<Progress value={progressValue} className="h-2" />
</div>
</div>
)}
</Carousel>
{/* ── Page Builder content Dialog ─────────────────────────────────── */}
<Dialog open={!!viewAd} onOpenChange={(open) => !open && setViewAd(null)}>
<DialogContent className="sm:max-w-lg max-h-[80vh] overflow-y-auto">
{viewAd && (() => {
const page = viewAd.landing_page ?? {};
const imageSrc = resolveAssetSrc(viewAd.image) || viewAd.image_url || null;
const links = Array.isArray(page.links) ? page.links : [];
return (
<>
<DialogHeader>
<DialogTitle>{page.title || viewAd.headline || "Advertisement"}</DialogTitle>
{page.description && <DialogDescription>{page.description}</DialogDescription>}
</DialogHeader>
{imageSrc && (
<div className="rounded-lg overflow-hidden border h-48">
<img
src={imageSrc}
alt={page.title || viewAd.headline || "Advertisement"}
className="w-full h-full object-cover"
/>
</div>
)}
{page.body && (
<div className="prose prose-sm dark:prose-invert max-w-none whitespace-pre-wrap">
{page.body}
</div>
)}
{links.length > 0 && (
<div className="flex flex-wrap gap-2 pt-2">
{links.map((l, i) => (
<Button
key={i}
variant={i === 0 ? "default" : "outline"}
onClick={() => { onCtaClick?.(viewAd, l); setViewAd(null); }}
>
{l.label || l.link}
</Button>
))}
</div>
)}
</>
);
})()}
</DialogContent>
</Dialog>
</div>
);
}
// ── BannerSkeleton ───────────────────────────────────────────────────────────
export function BannerSkeleton() {
return <Skeleton className="w-full rounded-xl h-[220px]" />;
}
@@ -0,0 +1,240 @@
// components/blocks/Hero.jsx
import { useEffect, useState } from "react";
import { Megaphone } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent } from "@/components/ui/card";
import { Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext } from "@/components/ui/carousel";
import { Progress } from "@/components/ui/progress";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { resolveAssetSrc } from "@/utils/media.util";
// An ad only ever has an internally-authored landing page when it has no
// redirect_link (see applyAdvertisementFields on the backend, which clears
// whichever one the admin didn't choose) — so its presence alone is enough
// to tell whether there's Page Builder content worth surfacing.
function hasLandingPage(ad) {
const page = ad?.landing_page;
if (!page) return false;
return Boolean(page.title || page.description || page.body || page.links?.length);
}
// ── Hero ─────────────────────────────────────────────────────────────────────
/**
* Hero advertisement carousel.
* Each slide is a full-bleed background image with a bottom gradient overlay,
* badge/headline/description/CTAs anchored bottom-left. The whole slide is
* clickable through to the ad's redirect_link/landing page whenever it has no
* CTA buttons of its own. Renders null when no ads are given — callers should
* not fall back to placeholder copy.
*
* Props:
* ads — array of advertisement objects { badge_labels, headline, description, ctas, redirect_link, image, image_url, advertisement_id }
* onCtaClick — (ad, cta) => void. cta is undefined for the whole-slide click.
*/
export function Hero({ ads, onCtaClick }) {
const [api, setApi] = useState();
const [current, setCurrent] = useState(0);
const [count, setCount] = useState(0);
const [viewAd, setViewAd] = useState(null); // ad whose Page Builder content is open in the Dialog
useEffect(() => {
if (!api) return;
setCount(api.scrollSnapList().length);
setCurrent(api.selectedScrollSnap() + 1);
api.on("select", () => {
setCurrent(api.selectedScrollSnap() + 1);
});
}, [api]);
if (!ads?.length) return null;
const progressValue = count ? (current / count) * 100 : 0;
return (
<div className="w-full">
<Carousel setApi={setApi} className="w-full">
<CarouselContent>
{ads.map((ad) => {
const imageSrc = resolveAssetSrc(ad.image) || ad.image_url || null;
const ctas = Array.isArray(ad.ctas) ? ad.ctas : [];
const badgeLabels = Array.isArray(ad.badge_labels) ? ad.badge_labels : [];
// Whole-slide click-through only makes sense when there's no CTA
// row of its own to carry that responsibility instead — a landing
// page (Page Builder content) always wins over the plain redirect.
const clickable = ctas.length === 0 && (hasLandingPage(ad) || ad.redirect_link);
const handleSlideClick = () => (hasLandingPage(ad) ? setViewAd(ad) : onCtaClick?.(ad, undefined));
return (
<CarouselItem key={ad.advertisement_id}>
<Card className="border rounded-2xl overflow-hidden pl-0 py-0">
<CardContent
role={clickable ? "button" : undefined}
tabIndex={clickable ? 0 : undefined}
onClick={clickable ? handleSlideClick : undefined}
onKeyDown={clickable ? (e) => { if (e.key === "Enter" || e.key === " ") handleSlideClick(); } : undefined}
className={"relative xs:h-64 lg:h-96 bg-muted flex items-center justify-center" + (clickable ? " cursor-pointer" : "")}
>
{imageSrc ? (
<img
src={imageSrc}
alt={ad.headline || "Advertisement"}
className="absolute inset-0 w-full h-full object-cover"
/>
) : (
<Megaphone className="size-8 text-muted-foreground" />
)}
{/* Bottom gradient overlay */}
<div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-transparent" />
{hasLandingPage(ad) && (
<div className="absolute top-4 right-4">
<Button
variant="secondary"
aria-label="View advertisement details"
onClick={() => setViewAd(ad)}
>
View <Megaphone />
</Button>
</div>
)}
{/* Bottom-left content */}
<div className="absolute bottom-0 left-0 p-6 flex flex-col gap-3 xs:max-w-[280px] sm:max-w-sm lg:max-w-xl">
{badgeLabels.length > 0 && (
<div className="flex items-center gap-1.5 flex-wrap">
{badgeLabels.map((label, i) => (
<Badge key={i} variant="outline" className="pointer-events-none select-none w-fit border-white/30 bg-black/20 text-white">
<Megaphone /> {label}
</Badge>
))}
</div>
)}
{ad.headline && (
<div className="font-bold text-white xs:text-2xl lg:text-4xl leading-tight tracking-tighter pointer-events-none select-none">
{ad.headline}
</div>
)}
{ad.description && (
<p className="text-gray-200 xs:text-sm lg:text-md leading-relaxed pointer-events-none select-none line-clamp-2">
{ad.description}
</p>
)}
{ctas.length > 0 && (
<div className="flex items-center gap-2 pt-1">
{ctas.map((cta, i) => (
<Button
key={i}
variant={cta.variant === "outline" ? "outline" : "default"}
className={cta.variant !== "outline" ? "bg-[oklch(0.63_0.25_302)] text-white hover:bg-[oklch(0.63_0.25_302)]/85" : undefined}
onClick={() => onCtaClick?.(ad, cta)}
>
{cta.label}
</Button>
))}
</div>
)}
</div>
</CardContent>
</Card>
</CarouselItem>
);
})}
</CarouselContent>
{/* Navigation and Progress — only meaningful with more than one slide */}
{ads.length > 1 && (
<div className="flex items-center justify-between mt-4">
<div className="flex items-center gap-2">
<CarouselPrevious className="static translate-y-0 size-8 rounded-lg" />
<CarouselNext className="static translate-y-0 size-8 rounded-lg" />
</div>
<div className="flex-1 max-w-24 ml-4">
<Progress value={progressValue} className="h-2" />
</div>
</div>
)}
</Carousel>
{/* ── Page Builder content Dialog ─────────────────────────────────── */}
<Dialog open={!!viewAd} onOpenChange={(open) => !open && setViewAd(null)}>
<DialogContent className="sm:max-w-lg max-h-[80vh] overflow-y-auto">
{viewAd && (() => {
const page = viewAd.landing_page ?? {};
const imageSrc = resolveAssetSrc(viewAd.image) || viewAd.image_url || null;
const links = Array.isArray(page.links) ? page.links : [];
return (
<>
<DialogHeader>
<DialogTitle>{page.title || viewAd.headline || "Advertisement"}</DialogTitle>
{page.description && <DialogDescription>{page.description}</DialogDescription>}
</DialogHeader>
{imageSrc && (
<div className="rounded-lg overflow-hidden border h-48">
<img
src={imageSrc}
alt={page.title || viewAd.headline || "Advertisement"}
className="w-full h-full object-cover"
/>
</div>
)}
{page.body && (
<div className="prose prose-sm dark:prose-invert max-w-none whitespace-pre-wrap">
{page.body}
</div>
)}
{links.length > 0 && (
<div className="flex flex-wrap gap-2 pt-2">
{links.map((l, i) => (
<Button
key={i}
variant={i === 0 ? "default" : "outline"}
onClick={() => { onCtaClick?.(viewAd, l); setViewAd(null); }}
>
{l.label || l.link}
</Button>
))}
</div>
)}
</>
);
})()}
</DialogContent>
</Dialog>
</div>
);
}
// ── HeroSkeleton ─────────────────────────────────────────────────────────────
export function HeroSkeleton() {
return (
<div className="w-full">
<Card className="border rounded-2xl overflow-hidden pl-0 py-0">
<CardContent className="relative xs:h-64 lg:h-96">
<Skeleton className="absolute inset-0 h-full w-full rounded-none" />
<div className="absolute bottom-0 left-0 p-6 flex flex-col gap-3 w-full max-w-lg">
<Skeleton className="h-6 w-32 rounded-full" />
<Skeleton className="h-10 w-3/4" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-2/3" />
<div className="flex gap-2 pt-1">
<Skeleton className="h-9 w-24" />
<Skeleton className="h-9 w-28" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
@@ -0,0 +1,371 @@
import { useRef, useState, useEffect, useCallback } from "react";
import { Music2, RotateCcw, RotateCw, Play, Pause, VolumeOff, Volume2 } from "lucide-react";
import api from "@/utils/api.util";
import { MediaFallback } from "@/components/generic/MediaFallback";
import { useMediaWatchGuard } from "@/hooks/useMediaWatchGuard";
import { formatPlayerTime as fmtTime } from "@/utils/format.util";
const SPEEDS = [0.5, 0.75, 1, 1.25, 1.5, 2];
const API_BASE = (import.meta.env.VITE_API_URL ?? "http://localhost:3024").replace(/\/$/, "");
// ─── AudioBlock (Client — secure) ────────────────────────────────────────────
//
// S3/Garage:
// 1. POST /client/media/token → get JWT token
// 2. fetch(streamUrl, { credentials: "include" }) → get raw bytes
// 3. URL.createObjectURL(blob) → blob:http://... URL
// 4. <audio src="blob:..."> → real URL never visible in DOM
//
// Chibisafe:
// → content.url used directly (Chibisafe CDN, no proxy needed)
//
// Direct (legacy):
// → content.url / content.src used directly, no token flow
//
// content shape: { asset_id?, url?, storage_provider?, title?, artist?, tag?, thumbnail? }
// onWatchProgress(percent) — optional, called (throttled) as playback advances and
// immediately at 100% on end. Backing the watch_percent completion requirement type.
export function AudioBlock({ content, onWatchProgress, resumePercent, antiSkipEnabled }) {
const audioRef = useRef(null);
const guard = useMediaWatchGuard({ onWatchProgress, antiSkipEnabled });
const resumedRef = useRef(false);
// ── Stream state ──────────────────────────────────────────────────────────
const [blobUrl, setBlobUrl] = useState(null);
const [thumbnailUrl, setThumbnailUrl] = useState(null);
const [fetchLoading, setFetchLoading] = useState(false);
const [fetchError, setFetchError] = useState(false);
// ── Player state ──────────────────────────────────────────────────────────
const [playing, setPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [buffered, setBuffered] = useState(0);
const [duration, setDuration] = useState(0);
const [volume, setVolume] = useState(1);
const [muted, setMuted] = useState(false);
const [speedIdx, setSpeedIdx] = useState(2); // 1×
const assetId = content?.asset_id;
const storageProvider = content?.storage_provider;
const directUrl = content?.url ?? content?.src ?? null;
const title = content?.title ?? "Audio";
const artist = content?.artist ?? "";
const tag = content?.tag ?? "";
// For S3 assets, thumbnailUrl is set from the token response (presigned URL).
// For other providers, fall back to the raw content.thumbnail value.
const thumbnail = thumbnailUrl ?? content?.thumbnail ?? null;
// ── Resolve stream URL → set as audio src directly ───────────────────────
useEffect(() => {
setBlobUrl(null);
setThumbnailUrl(null);
setFetchError(false);
setPlaying(false);
setCurrentTime(0);
setDuration(0);
guard.reset();
resumedRef.current = false;
// Legacy direct URL — no asset_id
if (!assetId && directUrl) {
setBlobUrl(directUrl);
return;
}
if (!assetId) return;
let cancelled = false;
const load = async () => {
setFetchLoading(true);
try {
// Chibisafe — use raw URL directly (CDN is public, no token needed)
if (storageProvider === "chibisafe") {
if (!directUrl) throw new Error("No URL in content");
if (!cancelled) setBlobUrl(directUrl);
return;
}
// S3 — get token; response also includes presigned thumbnail URL
const { data } = await api.post("/client/media/token", { asset_id: assetId });
if (cancelled) return;
const { token, thumbnail_url } = data?.data ?? {};
if (!token) throw new Error("No token returned");
if (!cancelled) {
setBlobUrl(`${API_BASE}/client/media/stream/${token}`);
if (thumbnail_url) setThumbnailUrl(thumbnail_url);
}
} catch (err) {
if (cancelled) return;
console.error("[AudioBlock] load failed", err);
setFetchError(true);
} finally {
if (!cancelled) setFetchLoading(false);
}
};
load();
return () => { cancelled = true; };
}, [assetId, storageProvider, directUrl]);
// ── Audio events ──────────────────────────────────────────────────────────
const onTimeUpdate = useCallback(() => {
const el = audioRef.current;
setCurrentTime(el?.currentTime ?? 0);
guard.trackTimeUpdate(el?.currentTime ?? 0, el?.duration);
if (el?.duration) {
const pct = (el.currentTime / el.duration) * 100;
guard.maybeReport(pct);
}
}, [guard]);
const onLoadedMeta = useCallback(() => {
const el = audioRef.current;
const d = el?.duration ?? 0;
setDuration(d);
guard.setDuration(d);
// Resume from the last position reached, once per asset. Left alone once
// fully watched (>=99%) — restarting reads better than resuming at the end.
if (el && !resumedRef.current && resumePercent > 0 && resumePercent < 99 && d) {
resumedRef.current = true;
const resumeSeconds = Math.min((resumePercent / 100) * d, d - 0.25);
el.currentTime = resumeSeconds;
setCurrentTime(resumeSeconds);
// Seeds the seek-cap so forward-seeking within already-watched territory
// works immediately, instead of clamping back to 0 until the next tick.
guard.trackTimeUpdate(resumeSeconds, d);
}
}, [guard, resumePercent]);
const onEnded = useCallback(() => { setPlaying(false); onWatchProgress?.(100); }, [onWatchProgress]);
const onPlay = useCallback(() => {
const el = audioRef.current;
if (el?.duration) guard.reportPlayStart((el.currentTime / el.duration) * 100);
}, [guard]);
const onPause = useCallback(() => {
const el = audioRef.current;
if (el?.duration) guard.flush((el.currentTime / el.duration) * 100);
}, [guard]);
const onSeeking = useCallback(() => guard.markSeeking(), [guard]);
const onSeeked = useCallback(() => guard.markSeeked(), [guard]);
const onProgress = useCallback(() => {
const el = audioRef.current;
if (el?.buffered.length && el.duration) {
setBuffered((el.buffered.end(el.buffered.length - 1) / el.duration) * 100);
}
}, []);
// ── Controls ──────────────────────────────────────────────────────────────
const togglePlay = () => {
const el = audioRef.current;
if (!el) return;
if (playing) { el.pause(); setPlaying(false); }
else { el.play(); setPlaying(true); }
};
const seek = (e) => {
const el = audioRef.current;
const bar = e.currentTarget;
const pct = (e.clientX - bar.getBoundingClientRect().left) / bar.offsetWidth;
el.currentTime = guard.clampSeekTarget(pct * duration);
};
const skip = (secs) => {
const el = audioRef.current;
if (!el) return;
el.currentTime = guard.clampSeekTarget(Math.min(Math.max(0, el.currentTime + secs), duration));
};
const handleVolume = (e) => {
const v = parseFloat(e.target.value);
setVolume(v);
if (audioRef.current) audioRef.current.volume = v;
setMuted(v === 0);
};
const toggleMute = () => {
const el = audioRef.current;
if (!el) return;
el.muted = !muted;
setMuted(!muted);
};
const cycleSpeed = () => {
const next = (speedIdx + 1) % SPEEDS.length;
setSpeedIdx(next);
if (audioRef.current) audioRef.current.playbackRate = SPEEDS[next];
};
const progress = duration > 0 ? (currentTime / duration) * 100 : 0;
// ── States ────────────────────────────────────────────────────────────────
if (fetchLoading) {
return <MediaFallback className="w-full h-28 rounded-xl border border-border" />;
}
if (fetchError) {
return (
<div className="w-full rounded-xl border border-border bg-card flex items-center justify-center h-24 gap-2 text-muted-foreground text-sm">
<Music2 className="size-4" /> Audio unavailable.
</div>
);
}
if (!blobUrl) return null;
// ─────────────────────────────────────────────────────────────────────────
return (
<div className="w-full rounded-xl overflow-hidden border border-border bg-card text-card-foreground shadow-sm">
<audio
ref={audioRef}
src={blobUrl}
onTimeUpdate={onTimeUpdate}
onLoadedMetadata={onLoadedMeta}
onEnded={onEnded}
onPlay={onPlay}
onPause={onPause}
onSeeking={onSeeking}
onSeeked={onSeeked}
onProgress={onProgress}
preload="auto"
/>
{/* ── Header ── */}
<div className="relative overflow-hidden">
<div className="xs:opacity-0 lg:opacity-100 select-none absolute top-4 right-5 z-20">
<img src="/philpro-white-single.png" alt="Logo" className="h-6 w-auto" />
</div>
{thumbnail ? (
<div
className="absolute inset-0 scale-110"
style={{
backgroundImage: `url(${thumbnail})`,
backgroundSize: "cover",
backgroundPosition: "center",
filter: "blur(24px) brightness(0.35)",
}}
/>
) : (
<div className="absolute inset-0 bg-primary" />
)}
{/* Mobile */}
<div className="relative z-10 flex flex-col gap-4 pb-6 text-white sm:hidden">
<div className="w-full px-4 pt-4">
<div className="w-full h-72 aspect-square rounded-lg overflow-hidden bg-black/30 shadow-xl dark:border">
{thumbnail ? (
<img src={thumbnail} alt={title} className="w-full h-full object-cover" />
) : (
<div className="w-full h-full flex items-center justify-center">
<Music2 className="w-10 h-10 text-white/30" />
</div>
)}
</div>
</div>
<div className="flex flex-col gap-1 px-4">
{tag && (
<div className="text-xs font-semibold rounded-full uppercase px-3 py-1 bg-card text-card-foreground border w-fit mb-1">
{tag}
</div>
)}
<p className="text-lg font-semibold leading-tight">{title}</p>
{artist && <p className="text-sm text-white/60">{artist}</p>}
</div>
</div>
{/* Desktop */}
<div className="relative z-10 hidden sm:flex items-center gap-4 p-4 text-white">
<div className="shrink-0 w-48 h-48 rounded-md overflow-hidden bg-black/25">
{thumbnail ? (
<img src={thumbnail} alt={title} className="w-full h-full object-cover" />
) : (
<div className="w-full h-full flex items-center justify-center">
<Music2 className="w-7 h-7 text-white/30" />
</div>
)}
</div>
<div className="flex flex-col gap-1 min-w-0">
{tag && (
<div className="text-xs font-semibold rounded-full uppercase px-3 py-1 bg-card text-card-foreground border w-fit">
{tag}
</div>
)}
<p className="w-sm line-clamp-3 text-lg font-semibold leading-tight">{title}</p>
{artist && <p className="text-sm text-white/60 truncate">{artist}</p>}
</div>
</div>
</div>
{/* ── Controls ── */}
<div className="px-4 pb-4 pt-3 space-y-3">
<div className="flex items-center gap-2.5">
<span className="text-xs tabular-nums text-card-foreground w-8 shrink-0">
{fmtTime(currentTime)}
</span>
<div
className="flex-1 h-1.5 rounded-full bg-muted cursor-pointer relative group"
onClick={seek}
role="slider"
aria-label="Seek"
aria-valuenow={Math.round(progress)}
aria-valuemin={0}
aria-valuemax={100}
>
<div className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground/25 transition-[width] duration-300" style={{ width: `${buffered}%` }} />
<div className="h-full rounded-full bg-primary transition-all relative" style={{ width: `${progress}%` }} />
<div className="absolute top-1/2 w-3 h-3 rounded-full bg-primary opacity-0 group-hover:opacity-100 transition-opacity" style={{ left: `${progress}%`, transform: "translate(-50%, -50%)" }} />
</div>
<span className="text-xs tabular-nums text-card-foreground w-8 shrink-0 text-right">
{fmtTime(duration)}
</span>
</div>
<div className="grid grid-cols-3 items-center">
{/* Left — volume */}
<div className="flex items-center gap-1.5">
<button onClick={toggleMute} aria-label={muted ? "Unmute" : "Mute"} className="w-7 h-7 flex items-center justify-center rounded-full text-foreground hover:bg-muted transition-colors">
{muted || volume === 0 ? <VolumeOff className="size-4" /> : <Volume2 className="size-4" />}
</button>
<input
type="range" min="0" max="1" step="0.05"
value={muted ? 0 : volume}
onChange={handleVolume}
aria-label="Volume"
className="w-16 h-1.5 accent-primary cursor-pointer
[&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:size-3 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-webkit-slider-thumb]:cursor-pointer
[&::-moz-range-thumb]:appearance-none [&::-moz-range-thumb]:size-3 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:cursor-pointer"
/>
</div>
{/* Center — play controls */}
<div className="flex items-center justify-center gap-2">
<button onClick={() => skip(-10)} aria-label="Rewind 10 seconds" className="p-2 flex items-center justify-center rounded-full text-foreground hover:bg-muted transition-colors">
<RotateCcw className="size-4" />
</button>
<button onClick={togglePlay} aria-label={playing ? "Pause" : "Play"} className="p-3 rounded-full flex items-center justify-center bg-primary text-primary-foreground hover:opacity-80 transition-opacity active:scale-95 shadow-md">
{playing ? <Pause className="xs:size-4 lg:size-5" /> : <Play className="xs:size-4 lg:size-5" />}
</button>
<button onClick={() => skip(10)} aria-label="Forward 10 seconds" className="p-2 flex items-center justify-center rounded-full text-foreground hover:bg-muted transition-colors">
<RotateCw className="size-4" />
</button>
</div>
{/* Right — speed */}
<div className="flex items-center justify-end gap-1">
<button onClick={cycleSpeed} aria-label={`Playback speed ${SPEEDS[speedIdx]}x`} className="h-7 px-2 rounded text-sm font-medium text-foreground hover:bg-muted transition-colors tabular-nums">
{SPEEDS[speedIdx]}x
</button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,50 @@
import { useState } from "react";
import { Copy, Check } from "lucide-react";
export function CodeBlock({ content }) {
const [copied, setCopied] = useState(false);
const code = content.code ?? "";
const language = content.language ?? "text";
const handleCopy = () => {
navigator.clipboard.writeText(code).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
});
};
if (!code) {
return (
<div className="rounded-lg border border-dashed bg-muted/20 p-4 text-xs text-muted-foreground italic">
Empty code block
</div>
);
}
return (
<div className="rounded-lg overflow-hidden border border-zinc-700 dark:border-zinc-600 bg-zinc-950 text-zinc-100 my-2">
{/* ── Header bar ── */}
<div className="flex items-center justify-between px-4 py-2 bg-zinc-900 border-b border-zinc-700">
<span className="text-[11px] font-mono text-zinc-400 uppercase tracking-widest select-none">
{language}
</span>
<button
onClick={handleCopy}
className="flex items-center gap-1.5 text-xs text-zinc-400 hover:text-zinc-100 transition-colors"
>
{copied
? <Check className="size-3.5 text-emerald-400" />
: <Copy className="size-3.5" />
}
<span>{copied ? "Copied!" : "Copy"}</span>
</button>
</div>
{/* ── Code area ── */}
<pre className="overflow-x-auto p-4 text-sm leading-relaxed" style={{ margin: 0, background: "transparent" }}>
<code className="font-mono whitespace-pre">{code}</code>
</pre>
</div>
);
}
@@ -0,0 +1,32 @@
import { ImageIcon } from "lucide-react";
import { ZoomableImage } from "@/modules/admin/components/courses/LessonsPreview";
import { useAssetPreviewSrc } from "@/hooks/useAssetPreviewSrc";
import { MediaFallback } from "@/components/generic/MediaFallback";
// content shape: { asset_id?, url?, storage_provider?, alt? }
//
// url is redacted (null) server-side for S3 assets — see redactS3Url() in
// controllers/admin/assets.controller.js. Resolve through useAssetPreviewSrc
// (media.util.js) instead of reading content.url directly, so S3-backed
// images re-mint a fresh stream token/thumbnail at render time.
export function ImageBlock({ content }) {
const { src, loading } = useAssetPreviewSrc(
{ asset_id: content?.asset_id, storage_provider: content?.storage_provider, file_url: content?.url, thumbnail_url: content?.url },
{ scope: "client" },
);
if (loading) {
return <MediaFallback className="aspect-video rounded-lg" />;
}
if (!src) {
return (
<div className="flex items-center justify-center aspect-video rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
<ImageIcon className="h-4 w-4" />
No image
</div>
);
}
return <ZoomableImage url={src} alt={content?.alt} />;
}
@@ -0,0 +1,20 @@
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
export function MarkdownBlock({ content }) {
const body = content.body ?? "";
if (!body.trim()) {
return (
<div className="text-xs text-muted-foreground italic py-2">
Empty markdown block
</div>
);
}
return (
<div className="typeset">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{body}</ReactMarkdown>
</div>
);
}
@@ -0,0 +1,11 @@
export function TextBlock({ content }) {
if (!content.body) {
return <div className="text-xs text-muted-foreground italic py-2">Empty text block</div>;
}
return (
<div
className="typeset text-sm"
dangerouslySetInnerHTML={{ __html: content.body }}
/>
);
}
@@ -0,0 +1,15 @@
import { ImageBlock } from "./ImageBlock";
export function TextImageBlock({ content }) {
const imgLeft = content.image_position === "left";
return (
<div className="flex flex-col gap-6 items-start sm:grid sm:grid-cols-2 sm:gap-6">
{imgLeft && <ImageBlock content={content} />}
<div
className="typeset text-sm w-full"
dangerouslySetInnerHTML={{ __html: content.body || "<p class='text-muted-foreground italic'>Empty text</p>" }}
/>
{!imgLeft && <ImageBlock content={content} />}
</div>
);
}
@@ -0,0 +1,17 @@
import { VideoBlock } from "./VideoBlock";
export function TextVideoBlock({ content, onWatchProgress, resumePercent, antiSkipEnabled }) {
const vidLeft = content.video_position === "left";
return (
<div className="flex flex-col gap-6 items-start sm:grid sm:grid-cols-2 sm:gap-6">
{vidLeft && <VideoBlock content={content} onWatchProgress={onWatchProgress} resumePercent={resumePercent} antiSkipEnabled={antiSkipEnabled} />}
<div
className="typeset text-sm w-full"
dangerouslySetInnerHTML={{
__html: content.body || "<p class='text-muted-foreground italic'>Empty text</p>",
}}
/>
{!vidLeft && <VideoBlock content={content} onWatchProgress={onWatchProgress} resumePercent={resumePercent} antiSkipEnabled={antiSkipEnabled} />}
</div>
);
}
@@ -0,0 +1,730 @@
import { useRef, useState, useEffect, useCallback } from "react";
import {
Play, Pause, SkipBack, Volume2, VolumeX, Maximize2, Minimize2, Settings, VideoIcon,
Volume1, SkipForward, Gauge, X, RotateCcw,
} from "lucide-react";
import {
Tooltip, TooltipContent, TooltipProvider, TooltipTrigger,
} from "@/components/ui/tooltip";
import { ChevronLeft, ChevronRight } from "lucide-react";
import api from "@/utils/api.util";
import { MediaFallback } from "@/components/generic/MediaFallback";
import { useMediaWatchGuard } from "@/hooks/useMediaWatchGuard";
import { formatPlayerTime as fmtTime } from "@/utils/format.util";
const PLAYBACK_SPEEDS = ["0.5", "0.75", "Normal", "1.25", "1.5", "2"];
const API_BASE = (import.meta.env.VITE_API_URL ?? "http://localhost:3024").replace(/\/$/, "");
// ─── Tooltip control button ───────────────────────────────────────────────────
function CtrlBtn({ label, onClick, children, className = "" }) {
return (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
aria-label={label}
onClick={onClick}
className={`text-white/80 hover:text-white transition-colors flex items-center justify-center ${className}`}
>
{children}
</button>
</TooltipTrigger>
<TooltipContent side="top" className="text-sm">{label}</TooltipContent>
</Tooltip>
);
}
// ─── Settings panel ───────────────────────────────────────────────────────────
function SettingsPanel({ speed, onSpeed, onClose }) {
const [tab, setTab] = useState(null);
const Row = ({ icon: Icon, label, value, onClick }) => (
<button
type="button"
onClick={onClick}
className="w-full flex items-center justify-between px-4 py-2.5 hover:bg-white/10 transition-colors text-sm"
>
<span className="flex items-center gap-2.5 text-white/90">
<Icon className="size-4 text-white/50" />
{label}
</span>
<div className="text-white/50 flex items-center gap-2">
<p>{value}</p><ChevronRight className="size-4" />
</div>
</button>
);
const OptionList = ({ options, current, onSelect }) => (
<div className="py-1">
{options.map((opt) => (
<button
key={opt} type="button"
onClick={() => { onSelect(opt); setTab(null); }}
className={`w-full text-left px-4 py-2 text-sm transition-colors hover:bg-white/10 flex items-center justify-between ${current === opt ? "text-white font-medium" : "text-white/60"}`}
>
{opt}
{current === opt && <span className="text-white text-xs">✓</span>}
</button>
))}
</div>
);
return (
<>
<div
className="hidden lg:block absolute bottom-12 right-2 z-20 w-70 rounded-xl overflow-hidden shadow-2xl border border-white/10"
style={{ background: "rgba(18,18,18,0.96)", backdropFilter: "blur(16px)" }}
onClick={(e) => e.stopPropagation()}
>
{tab === null && (
<>
<p className="text-[10px] font-semibold uppercase tracking-widest text-white/30 px-4 pt-3 pb-1">Settings</p>
<Row icon={Gauge} label="Playback speed" value={speed} onClick={() => setTab("speed")} />
<div className="h-2" />
</>
)}
{tab !== null && (
<>
<button type="button" onClick={() => setTab(null)} className="flex items-center gap-1.5 px-4 pt-3 pb-1 text-sm text-white/40 hover:text-white/70 transition-colors w-full">
<ChevronLeft className="size-4" /> Playback speed
</button>
<OptionList options={PLAYBACK_SPEEDS} current={speed} onSelect={onSpeed} />
<div className="h-1" />
</>
)}
</div>
<div
className="lg:hidden absolute bottom-0 left-0 right-0 z-20 rounded-t-2xl border-t border-white/10 overflow-hidden"
style={{ background: "rgba(18,18,18,0.98)", backdropFilter: "blur(20px)" }}
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between px-4 pt-2.5 pb-1">
<div className="w-8 h-1 rounded-full bg-white/20 mx-auto" />
<button type="button" onClick={(e) => { e.stopPropagation(); onClose(); }} className="absolute right-3 top-3 text-white/40 hover:text-white transition-colors">
<X className="size-4" />
</button>
</div>
{tab === null && (
<>
<p className="text-[10px] font-semibold uppercase tracking-widest text-white/30 px-4 pt-2 pb-1">Settings</p>
<Row icon={Gauge} label="Playback speed" value={speed} onClick={() => setTab("speed")} />
<div className="h-safe pb-4" />
</>
)}
{tab !== null && (
<>
<button type="button" onClick={() => setTab(null)} className="flex items-center gap-1.5 px-4 pt-3 pb-1 text-sm text-white/40 hover:text-white/70 transition-colors w-full">
<ChevronLeft className="size-4" /> Playback speed
</button>
<div className="flex flex-wrap gap-2 px-4 py-3">
{PLAYBACK_SPEEDS.map((opt) => (
<button
key={opt} type="button"
onClick={() => { onSpeed(opt); setTab(null); }}
className={`px-4 py-1.5 rounded-full text-sm border transition-colors ${speed === opt ? "bg-white text-black border-white font-medium" : "bg-white/10 text-white/70 border-white/10 hover:bg-white/20"}`}
>
{opt}
</button>
))}
</div>
<div className="pb-4" />
</>
)}
</div>
</>
);
}
// ─── VideoBlock (Client — secure) ────────────────────────────────────────────
//
// S3/Garage:
// 1. POST /client/media/token → get JWT token
// 2. fetch(streamUrl, { credentials: "include" }) → get raw bytes
// 3. URL.createObjectURL(blob) → blob:http://... URL
// 4. <video src="blob:..."> → real URL never visible in DOM
//
// Chibisafe:
// → content.url used directly (Chibisafe CDN, no proxy needed)
//
// content shape: { asset_id, url, storage_provider, thumbnail_url? }
// onWatchProgress(percent) — optional, called (throttled) as playback advances and
// immediately at 100% on end. Backing the watch_percent completion requirement type;
// harmless/unused when the lesson isn't configured for it (caller just won't pass it).
export function VideoBlock({ content, onWatchProgress, resumePercent, antiSkipEnabled }) {
const wrapRef = useRef(null);
const vidRef = useRef(null);
const guard = useMediaWatchGuard({ onWatchProgress, antiSkipEnabled });
const resumedRef = useRef(false);
// ── Stream state ──────────────────────────────────────────────────────────
const [blobUrl, setBlobUrl] = useState(null);
const [freshThumb, setFreshThumb] = useState(null);
const [fetchLoading, setFetchLoading] = useState(false);
const [fetchError, setFetchError] = useState(false);
// ── Player state ──────────────────────────────────────────────────────────
const [playing, setPlaying] = useState(false);
const [progress, setProgress] = useState(0);
const [currentTime, setCurrentTime] = useState(0);
const [totalDuration, setTotalDuration] = useState(0);
const [muted, setMuted] = useState(false);
const [volume, setVolume] = useState(1);
const [ended, setEnded] = useState(false);
const [overlayVisible, setOverlayVisible] = useState(true);
const [controlsVisible, setControlsVisible] = useState(true);
// Native Fullscreen API works on desktop (all browsers) and Android Chrome.
// iOS Safari doesn't support Fullscreen API on arbitrary elements at all, so
// pseudoFullscreen is a CSS-only (fixed inset-0) fallback that keeps our
// custom controls instead of falling back to native <video> fullscreen.
const [nativeFullscreen, setNativeFullscreen] = useState(false);
const [pseudoFullscreen, setPseudoFullscreen] = useState(false);
const isFullscreen = nativeFullscreen || pseudoFullscreen;
const [settingsOpen, setSettingsOpen] = useState(false);
const [volumePanelOpen, setVolumePanelOpen] = useState(false);
const [keyFeedback, setKeyFeedback] = useState(null);
const [speed, setSpeed] = useState("Normal");
const [buffered, setBuffered] = useState(0);
const [buffering, setBuffering] = useState(false);
const [hoverProgress, setHoverProgress] = useState(null);
const hideTimer = useRef(null);
const keyFeedbackTimer = useRef(null);
const previewVidRef = useRef(null);
const assetId = content?.asset_id;
const storageProvider = content?.storage_provider;
// content.thumbnail_url is a presigned S3 URL captured at CMS pick time —
// it expires. For S3 assets, use the fresh thumbnail_url minted alongside
// the stream token below instead; only fall back to the persisted value
// for chibisafe (stable public CDN URL).
const poster = (storageProvider === "s3" ? freshThumb : content?.thumbnail_url) ?? undefined;
// ── Resolve stream URL → set as video src directly ───────────────────────
//
// Previously we fetched all bytes into a Blob and used URL.createObjectURL().
// That blob URL could be opened in a new tab and saved with "Save Video As...".
// Now we set the stream URL directly as <video src> — no blob is ever created.
// The backend blocks direct browser navigation (Sec-Fetch-Mode: navigate → 401)
// and the token is IP-bound, so sharing the URL is ineffective.
useEffect(() => {
if (!assetId) return;
setBlobUrl(null);
setFreshThumb(null);
setFetchError(false);
setPlaying(false);
setProgress(0);
setCurrentTime(0);
setTotalDuration(0);
setOverlayVisible(true);
setSettingsOpen(false);
setEnded(false);
guard.reset();
resumedRef.current = false;
let cancelled = false;
const load = async () => {
setFetchLoading(true);
try {
// Chibisafe — use raw URL directly
if (storageProvider === "chibisafe") {
const raw = content?.url;
if (!raw) throw new Error("No URL in content");
if (!cancelled) setBlobUrl(raw);
return;
}
// S3 — get token then stream directly; no blob download
const { data } = await api.post("/client/media/token", { asset_id: assetId });
if (cancelled) return;
const { token, thumbnail_url } = data?.data ?? {};
if (!token) throw new Error("No token returned");
if (!cancelled) {
setBlobUrl(`${API_BASE}/client/media/stream/${token}`);
if (thumbnail_url) setFreshThumb(thumbnail_url);
}
} catch (err) {
if (cancelled) return;
console.error("[VideoBlock] load failed", err);
setFetchError(true);
} finally {
if (!cancelled) setFetchLoading(false);
}
};
load();
return () => { cancelled = true; };
}, [assetId, storageProvider]);
// ── Video events ──────────────────────────────────────────────────────────
useEffect(() => {
const v = vidRef.current;
if (!v || !blobUrl) return;
const onTimeUpdate = () => {
setCurrentTime(v.currentTime);
guard.trackTimeUpdate(v.currentTime, v.duration);
if (v.duration) {
const pct = (v.currentTime / v.duration) * 100;
setProgress(pct);
guard.maybeReport(pct);
}
};
const onLoaded = () => {
setTotalDuration(v.duration);
guard.setDuration(v.duration);
// Resume from the last position reached, once per asset. Left alone once
// fully watched (>=99%) — restarting reads better than resuming at the end.
if (!resumedRef.current && resumePercent > 0 && resumePercent < 99 && v.duration) {
resumedRef.current = true;
const resumeSeconds = Math.min((resumePercent / 100) * v.duration, v.duration - 0.25);
v.currentTime = resumeSeconds;
setCurrentTime(resumeSeconds);
setProgress(resumePercent);
// Seeds the seek-cap so forward-seeking within already-watched territory
// works immediately, instead of clamping back to 0 until the next tick.
guard.trackTimeUpdate(resumeSeconds, v.duration);
}
};
const onEnded = () => {
setPlaying(false); setOverlayVisible(false); setEnded(true);
onWatchProgress?.(100);
};
const onPlay = () => {
if (v.duration) guard.reportPlayStart((v.currentTime / v.duration) * 100);
};
const onPause = () => {
if (v.duration) guard.flush((v.currentTime / v.duration) * 100);
};
const onSeeking = () => guard.markSeeking();
const onSeeked = () => guard.markSeeked();
const onWaiting = () => setBuffering(true);
const onCanPlay = () => setBuffering(false);
const onProgress = () => {
if (v.buffered.length && v.duration) {
setBuffered((v.buffered.end(v.buffered.length - 1) / v.duration) * 100);
}
};
v.addEventListener("waiting", onWaiting);
v.addEventListener("canplay", onCanPlay);
v.addEventListener("timeupdate", onTimeUpdate);
v.addEventListener("loadedmetadata", onLoaded);
v.addEventListener("ended", onEnded);
v.addEventListener("play", onPlay);
v.addEventListener("pause", onPause);
v.addEventListener("seeking", onSeeking);
v.addEventListener("seeked", onSeeked);
v.addEventListener("progress", onProgress);
if (v.readyState >= 1 && v.duration) onLoaded();
return () => {
v.removeEventListener("waiting", onWaiting);
v.removeEventListener("canplay", onCanPlay);
v.removeEventListener("timeupdate", onTimeUpdate);
v.removeEventListener("loadedmetadata", onLoaded);
v.removeEventListener("ended", onEnded);
v.removeEventListener("play", onPlay);
v.removeEventListener("pause", onPause);
v.removeEventListener("seeking", onSeeking);
v.removeEventListener("seeked", onSeeked);
v.removeEventListener("progress", onProgress);
};
}, [blobUrl]);
useEffect(() => {
const v = vidRef.current;
if (!v) return;
v.playbackRate = speed === "Normal" ? 1 : parseFloat(speed);
}, [speed]);
useEffect(() => {
// Safari (incl. desktop) still fires the prefixed webkitfullscreenchange
// event for element-level fullscreen, so both are listened for.
const onChange = () => {
const active = !!(document.fullscreenElement || document.webkitFullscreenElement);
setNativeFullscreen(active);
// Safari doesn't focus a <div tabIndex> on click, so keyboard
// shortcuts silently stop working after entering fullscreen unless
// we explicitly refocus the wrapper here.
if (active) wrapRef.current?.focus({ preventScroll: true });
};
document.addEventListener("fullscreenchange", onChange);
document.addEventListener("webkitfullscreenchange", onChange);
return () => {
document.removeEventListener("fullscreenchange", onChange);
document.removeEventListener("webkitfullscreenchange", onChange);
};
}, []);
// CSS pseudo-fullscreen fallback (iOS Safari) — lock page scroll and
// reclaim keyboard focus while it's active, restore on exit/unmount.
useEffect(() => {
if (!pseudoFullscreen) return;
const prevOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";
wrapRef.current?.focus({ preventScroll: true });
return () => { document.body.style.overflow = prevOverflow; };
}, [pseudoFullscreen]);
const resetHideTimer = useCallback(() => {
setControlsVisible(true);
clearTimeout(hideTimer.current);
if (playing) {
hideTimer.current = setTimeout(() => {
setControlsVisible(false);
setSettingsOpen(false);
}, 3000);
}
}, [playing]);
useEffect(() => {
resetHideTimer();
return () => clearTimeout(hideTimer.current);
}, [playing, resetHideTimer]);
const showFeedback = useCallback((icon, label) => {
setKeyFeedback((prev) => ({ icon, label, key: (prev?.key ?? 0) + 1 }));
clearTimeout(keyFeedbackTimer.current);
keyFeedbackTimer.current = setTimeout(() => setKeyFeedback(null), 800);
}, []);
const togglePlay = useCallback(() => {
const v = vidRef.current;
if (!v) return;
if (v.paused) { v.play(); setPlaying(true); setOverlayVisible(false); setEnded(false); }
else { v.pause(); setPlaying(false); setOverlayVisible(true); }
}, []);
// YouTube-style tap-to-reveal: while playing with the bar auto-hidden, the
// first tap only brings the controls back (doesn't pause); a second tap —
// once controls are already visible — toggles play, same as desktop where
// onMouseMove already keeps controls visible ahead of the click.
const handleWrapperClick = useCallback(() => {
// Safari doesn't focus a <div tabIndex> on click, which silently kills
// keyboard shortcuts afterwards — force it explicitly.
wrapRef.current?.focus({ preventScroll: true });
if (!controlsVisible) { resetHideTimer(); return; }
togglePlay();
resetHideTimer();
}, [controlsVisible, resetHideTimer, togglePlay]);
const restart = () => {
const v = vidRef.current;
if (!v) return;
v.currentTime = 0;
v.pause();
setPlaying(false);
setOverlayVisible(true);
};
const handleSeek = (e) => {
const v = vidRef.current;
if (!v || !v.duration) return;
v.currentTime = guard.clampSeekTarget((parseFloat(e.target.value) / 100) * v.duration);
};
const handleVolumeChange = (e) => {
const val = parseFloat(e.target.value);
setVolume(val);
if (vidRef.current) { vidRef.current.volume = val; vidRef.current.muted = val === 0; }
setMuted(val === 0);
};
const toggleMute = () => {
const v = vidRef.current;
if (!v) return;
v.muted = !v.muted;
setMuted(v.muted);
};
const toggleFullscreen = () => {
const el = wrapRef.current;
if (!el) return;
if (isFullscreen) {
if (document.fullscreenElement) document.exitFullscreen();
else if (document.webkitFullscreenElement) document.webkitExitFullscreen();
else setPseudoFullscreen(false);
} else if (el.requestFullscreen) {
el.requestFullscreen();
} else if (el.webkitRequestFullscreen) {
// Desktop Safari — supports element fullscreen via the prefixed API.
el.webkitRequestFullscreen();
} else {
// iOS Safari has no element-level Fullscreen API at all.
setPseudoFullscreen(true);
}
};
const handleKeyDown = useCallback((e) => {
if (e.target.tagName === "INPUT") return;
// Fold single-char keys to lowercase so Shift/Caps-Lock doesn't break
// letter shortcuts (e.g. Shift+F reporting as "F", not "f").
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
switch (key) {
case " ": case "k":
e.preventDefault();
togglePlay();
showFeedback(playing ? <Pause className="size-7 text-white" /> : <Play className="size-7 text-white" />, playing ? "Pause" : "Play");
resetHideTimer();
break;
case "ArrowRight":
e.preventDefault();
if (vidRef.current) vidRef.current.currentTime = guard.clampSeekTarget(Math.min(vidRef.current.currentTime + 5, vidRef.current.duration));
showFeedback(<SkipForward className="size-7 text-white" />, "+5s");
resetHideTimer();
break;
case "ArrowLeft":
e.preventDefault();
if (vidRef.current) vidRef.current.currentTime = Math.max(vidRef.current.currentTime - 5, 0);
showFeedback(<SkipBack className="size-7 text-white" />, "-5s");
resetHideTimer();
break;
case "ArrowUp":
e.preventDefault();
if (vidRef.current) {
const nv = Math.min(volume + 0.1, 1);
vidRef.current.volume = nv; setVolume(nv); setMuted(false);
showFeedback(<Volume2 className="size-7 text-white" />, `${Math.round(nv * 100)}%`);
}
break;
case "ArrowDown":
e.preventDefault();
if (vidRef.current) {
const nv = Math.max(volume - 0.1, 0);
vidRef.current.volume = nv; setVolume(nv); setMuted(nv === 0);
showFeedback(<Volume1 className="size-7 text-white" />, `${Math.round(nv * 100)}%`);
}
break;
case "m":
e.preventDefault();
toggleMute();
showFeedback(muted ? <Volume2 className="size-7 text-white" /> : <VolumeX className="size-7 text-white" />, muted ? "Unmuted" : "Muted");
break;
case "f":
e.preventDefault();
toggleFullscreen();
showFeedback(isFullscreen ? <Minimize2 className="size-7 text-white" /> : <Maximize2 className="size-7 text-white" />, isFullscreen ? "Exit fullscreen" : "Fullscreen");
break;
case "Escape":
if (isFullscreen) {
e.preventDefault();
toggleFullscreen();
showFeedback(<Minimize2 className="size-7 text-white" />, "Exit fullscreen");
}
break;
default: break;
}
}, [togglePlay, toggleMute, toggleFullscreen, resetHideTimer, volume, muted, isFullscreen, playing, showFeedback, guard]);
// ── States ────────────────────────────────────────────────────────────────
if (!assetId) {
return (
<div className="flex items-center justify-center aspect-video rounded-lg border border-dashed text-xs text-muted-foreground bg-muted/20 gap-1.5">
<VideoIcon className="h-4 w-4" /> No video
</div>
);
}
if (fetchLoading) {
return <MediaFallback className="aspect-video rounded-lg" />;
}
if (fetchError || !blobUrl) {
return (
<div className="flex flex-col items-center justify-center aspect-video rounded-lg bg-black/80 gap-2">
<VideoIcon className="h-8 w-8 text-white/30" />
<p className="text-sm text-white/50">Video unavailable.</p>
</div>
);
}
return (
<TooltipProvider delayDuration={400}>
<div
ref={wrapRef}
tabIndex={0}
className={`relative w-full overflow-hidden bg-black select-none outline-none ${pseudoFullscreen ? "fixed inset-0 z-[100]" : "rounded-lg"}`}
style={{ aspectRatio: isFullscreen ? undefined : "16/9" }}
onMouseMove={resetHideTimer}
onMouseLeave={() => { if (playing) setControlsVisible(false); }}
onClick={handleWrapperClick}
onKeyDown={handleKeyDown}
onContextMenu={(e) => e.preventDefault()}
>
<video
ref={vidRef}
src={blobUrl}
poster={poster}
preload="auto"
playsInline
controlsList="nodownload nofullscreen noremoteplayback"
disablePictureInPicture
disableRemotePlayback
onContextMenu={(e) => e.preventDefault()}
className={`w-full h-full ${isFullscreen ? "object-contain" : "object-cover"}`}
/>
{/* Centre overlay */}
<div
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-200 pointer-events-none ${overlayVisible ? "opacity-100" : "opacity-0"}`}
style={{ background: "rgba(0,0,0,0.3)" }}
>
<div className="w-14 h-14 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center border border-white/25">
{playing ? <Pause className="size-6 text-white" /> : <Play className="size-6 text-white ml-0.5" />}
</div>
</div>
{/* Buffering spinner */}
{buffering && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div className="w-12 h-12 rounded-full border-4 border-white/20 border-t-white animate-spin" />
</div>
)}
{/* Keyboard feedback */}
{keyFeedback && (
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
<div
key={keyFeedback.key}
className="flex flex-col items-center gap-1 px-5 py-3 rounded-2xl border border-white/10"
style={{ background: "rgba(0,0,0,0.65)", backdropFilter: "blur(12px)", animation: "fadeInOut 0.8s ease forwards" }}
>
<span className="leading-none">{keyFeedback.icon}</span>
<span className="text-white text-sm font-medium tracking-wide">{keyFeedback.label}</span>
</div>
<style>{`@keyframes fadeInOut{0%{opacity:0;transform:scale(.85)}20%{opacity:1;transform:scale(1)}70%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.95)}}`}</style>
</div>
)}
{/* End overlay */}
{ended && (
<div className="absolute inset-0 flex flex-col items-center justify-center gap-3 pointer-events-none" style={{ background: "rgba(0,0,0,0.55)" }}>
<button
type="button" aria-label="Replay"
className="pointer-events-auto w-16 h-16 rounded-full bg-white/20 hover:bg-white/30 backdrop-blur-sm border border-white/25 flex items-center justify-center transition-colors"
onClick={(e) => {
e.stopPropagation();
const v = vidRef.current;
if (!v) return;
v.currentTime = 0; v.play();
setPlaying(true); setEnded(false); setOverlayVisible(false);
}}
>
<RotateCcw className="size-7 text-white" />
</button>
<span className="text-white/70 text-sm">Replay</span>
</div>
)}
{/* Settings panel */}
{settingsOpen && (
<SettingsPanel speed={speed} onSpeed={setSpeed} onClose={() => setSettingsOpen(false)} />
)}
{/* Controls bar */}
<div
className={`absolute bottom-0 left-0 right-0 transition-opacity duration-300 ${controlsVisible ? "opacity-100" : "opacity-0 pointer-events-none"}`}
style={{ background: "linear-gradient(to top, rgba(0,0,0,0.98) 0%, rgba(0,0,0,0.4) 80%, transparent 100%)" }}
onClick={(e) => e.stopPropagation()}
>
<div className="px-3 pb-4">
<div
className="relative lg:h-2 xs:h-1 group cursor-pointer"
onMouseMove={(e) => {
const rect = e.currentTarget.getBoundingClientRect();
const pct = Math.min(Math.max((e.clientX - rect.left) / rect.width, 0), 1);
const time = pct * (vidRef.current?.duration ?? 0);
setHoverProgress({ x: e.clientX - rect.left, pct: pct * 100, time });
if (previewVidRef.current && isFinite(time) && time >= 0) {
previewVidRef.current.currentTime = time;
}
}}
onMouseLeave={() => setHoverProgress(null)}
>
<div className="absolute inset-0 bg-white/25 rounded-full" />
<div className="absolute inset-y-0 left-0 bg-white/40 rounded-full transition-[width] duration-300" style={{ width: `${buffered}%` }} />
<div className="absolute inset-y-0 left-0 bg-white rounded-full" style={{ width: `${progress}%` }} />
<div className="absolute top-1/2 -translate-y-1/2 w-3 h-3 rounded-full bg-white shadow-md -ml-1.5 opacity-0 group-hover:opacity-100 transition-opacity" style={{ left: `${progress}%` }} />
<input type="range" min="0" max="100" step="0.1" value={progress} onChange={handleSeek} aria-label="Seek" className="absolute inset-0 w-full h-full opacity-0 cursor-pointer" />
{/* Scrubber preview — also uses blob URL */}
{hoverProgress && (
<div
className="hidden lg:flex absolute bottom-5 flex-col items-center pointer-events-none z-30"
style={{ left: `${hoverProgress.x}px`, transform: "translateX(-50%)" }}
>
<div className="rounded-md overflow-hidden border border-white/20 shadow-xl" style={{ width: 160, height: 90 }}>
<video ref={previewVidRef} src={blobUrl} preload="auto" muted playsInline disablePictureInPicture disableRemotePlayback onContextMenu={(e) => e.preventDefault()} className="w-full h-full object-cover" />
</div>
<span className="text-white text-xs mt-1 font-medium tabular-nums drop-shadow">{fmtTime(hoverProgress.time)}</span>
<div className="w-2 h-2 bg-black/60 rotate-45 -mt-1 border-r border-b border-white/20" />
</div>
)}
</div>
</div>
<div className="flex items-center gap-3 px-2.5 pb-3">
<CtrlBtn label={playing ? "Pause" : "Play"} onClick={togglePlay}>
{playing ? <Pause className="size-4" /> : <Play className="size-4" />}
</CtrlBtn>
<CtrlBtn label="Restart" onClick={restart}>
<SkipBack className="size-4" />
</CtrlBtn>
<div className="relative" onClick={(e) => e.stopPropagation()}>
{volumePanelOpen && (
<div
className="lg:hidden absolute bottom-9 left-1/2 -translate-x-1/2 z-30 rounded-xl border border-white/10 px-4 py-3 flex flex-col items-center gap-2"
style={{ background: "rgba(18,18,18,0.96)", backdropFilter: "blur(16px)" }}
>
<span className="text-[10px] text-white/40 uppercase tracking-widest">Volume</span>
<input type="range" min="0" max="1" step="0.05" value={muted ? 0 : volume} onChange={handleVolumeChange} aria-label="Volume" className="accent-white cursor-pointer" style={{ writingMode: "vertical-lr", direction: "rtl", height: "80px", width: "auto" }} />
<span className="text-xs text-white/50 tabular-nums">{muted ? "0" : Math.round(volume * 100)}%</span>
</div>
)}
<CtrlBtn
label={muted ? "Unmute" : "Mute"}
onClick={() => {
if (window.innerWidth < 1024) setVolumePanelOpen((o) => !o);
else toggleMute();
}}
>
{muted ? <VolumeX className="size-4 sm:size-5" /> : <Volume2 className="size-4 sm:size-5" />}
</CtrlBtn>
</div>
<input type="range" min="0" max="1" step="0.05" value={muted ? 0 : volume} onChange={handleVolumeChange} aria-label="Volume" className="hidden lg:block w-16 accent-white cursor-pointer" onClick={(e) => e.stopPropagation()} />
<span className="text-white/60 text-sm tabular-nums ml-1.5">
{fmtTime(currentTime)} / {fmtTime(totalDuration)}
</span>
<div className="ml-auto flex items-center gap-3">
{speed !== "Normal" && (
<span className="text-sm text-white/60 bg-white/10 px-1.5 py-0.5 rounded-sm font-mono">{speed}x</span>
)}
<CtrlBtn label="Settings" onClick={(e) => { e.stopPropagation(); setSettingsOpen((o) => !o); }} className={settingsOpen ? "text-white" : ""}>
<Settings className={`size-5 transition-transform duration-300 ${settingsOpen ? "rotate-45" : ""}`} />
</CtrlBtn>
<CtrlBtn label={isFullscreen ? "Exit fullscreen" : "Fullscreen"} onClick={toggleFullscreen}>
{isFullscreen ? <Minimize2 className="size-5" /> : <Maximize2 className="size-5" />}
</CtrlBtn>
</div>
</div>
</div>
</div>
</TooltipProvider>
);
}