import { useEffect, useMemo, useState } from "react"; import { BookOpen, Calendar, Edit2, MoreVertical, Pencil, Play, Trash2, } from "lucide-react"; import { Button } from "../../../components/ui/button"; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "../../../components/ui/dialog"; import { isAdminOrSuperAdminRole } from "../../../lib/sessionRole"; import { learnEnglishPracticeLimitHint } from "../../../lib/practiceParents"; import { cn } from "../../../lib/utils"; import { SearchHighlight } from "../../../components/SearchHighlight"; import { applyShortPreviewToEmbedUrl, DEFAULT_PREVIEW_MAX_SECONDS, extractVimeoVideoId, formatPreviewLength, formatVideoDurationLabel, getVideoPreview, isDirectVideoFileUrl, } from "../../../lib/videoPreview"; import { fetchVimeoDurationSeconds } from "../../../lib/vimeoVideoCache"; import { PreviewLimitedFileVideo } from "./PreviewLimitedFileVideo"; import type { ContentAccessTier, PracticePublishStatus, } from "../../../types/course.types"; import { ContentAccessTierChip } from "./ContentAccessTierChip"; import { ContentPublishStatusChip } from "./ContentPublishStatusChip"; function resolvePublishBadge( publishStatus?: PracticePublishStatus | string | null, status?: "Draft" | "Published", hoverModuleActions?: boolean, ): { label: string; isPublished: boolean } | null { const raw = publishStatus ?? (status === "Published" ? "PUBLISHED" : status === "Draft" ? "DRAFT" : null); if (raw) { const label = String(raw).toUpperCase(); return { label, isPublished: label === "PUBLISHED" }; } if (hoverModuleActions) { return { label: "DRAFT", isPublished: false }; } return null; } interface VideoCardProps { id?: string | number; title: string; /** Omits the duration chip when not provided (e.g. API has no length yet). */ duration?: string; /** Total seconds; shown when `duration` string is omitted. Direct file URLs may still be probed in-browser. */ durationSeconds?: number | null; /** When omitted, shows a neutral "Lesson" chip and no Publish button. */ status?: "Draft" | "Published"; /** From GET lesson list — preferred for module lesson cards (`PUBLISHED` / `DRAFT`). */ publishStatus?: PracticePublishStatus | string | null; thumbnailGradient?: string; thumbnailUrl?: string | null; /** * When set, the hover play control opens a preview (Vimeo, YouTube, or direct * video file) in a dialog. */ videoUrl?: string; /** * When true, shows edit/delete (and optional view practices) in the top-right * of the thumbnail on hover, and removes the footer + overflow menu. */ hoverModuleActions?: boolean; onEdit?: () => void; onDelete?: () => void; /** When set (e.g. on module lesson cards), shows an "Add practice" control scoped to this lesson. */ onAddPractice?: () => void; /** When true, the lesson card shows a disabled "Add practice" control. */ addPracticeDisabled?: boolean; /** When set with hoverModuleActions, shows a book icon next to edit/delete on thumbnail hover. */ onViewPractices?: () => void; onPublish?: () => void; /** Toggle draft ↔ published via PUT /lessons/:id (module lesson cards). */ onTogglePublishStatus?: (nextStatus: PracticePublishStatus) => void; publishStatusUpdating?: boolean; accessTier?: ContentAccessTier | string | null; onToggleAccessTier?: (nextTier: ContentAccessTier) => void; accessTierUpdating?: boolean; /** Shown under title on module lesson cards; reserved height keeps grid rows even. */ description?: string | null; /** When set, matching search keywords are highlighted in title/description. */ searchQuery?: string; } export function VideoCard({ title, duration, durationSeconds, status, publishStatus, thumbnailGradient = "from-[#D4D4D8] to-[#71717A]", thumbnailUrl, videoUrl, onEdit, onDelete, onPublish, onAddPractice, addPracticeDisabled = false, onViewPractices, onTogglePublishStatus, publishStatusUpdating = false, accessTier, onToggleAccessTier, accessTierUpdating = false, hoverModuleActions = false, description, searchQuery = "", }: VideoCardProps) { const [thumbFailed, setThumbFailed] = useState(false); const [probedDurationSeconds, setProbedDurationSeconds] = useState< number | null >(null); const [vimeoDurationSeconds, setVimeoDurationSeconds] = useState< number | null >(null); const [previewOpen, setPreviewOpen] = useState(false); /** Iframe players ignore URL limits in many cases — unmount after real time. */ const [iframeSessionDone, setIframeSessionDone] = useState(false); const [iframeSessionKey, setIframeSessionKey] = useState(0); const useGradient = !thumbnailUrl?.trim() || thumbFailed; const videoPreview = useMemo( () => (videoUrl?.trim() ? getVideoPreview(videoUrl) : { kind: "none" as const }), [videoUrl], ); const limitedEmbedSrc = useMemo(() => { if (videoPreview.kind !== "iframe") return null; return applyShortPreviewToEmbedUrl( videoPreview.src, videoPreview.label, DEFAULT_PREVIEW_MAX_SECONDS, ); }, [videoPreview]); const canPreview = Boolean(videoUrl?.trim()); const previewLengthLabel = formatPreviewLength( DEFAULT_PREVIEW_MAX_SECONDS, ); const publishBadge = resolvePublishBadge( publishStatus, status, hoverModuleActions, ); useEffect(() => { if (duration?.trim()) { setProbedDurationSeconds(null); return; } if ( typeof durationSeconds === "number" && Number.isFinite(durationSeconds) && durationSeconds > 0 ) { setProbedDurationSeconds(null); return; } const url = videoUrl?.trim() ?? ""; if (!isDirectVideoFileUrl(url)) { setProbedDurationSeconds(null); return; } let cancelled = false; const video = document.createElement("video"); video.preload = "metadata"; video.muted = true; const onLoaded = () => { if (cancelled) return; const d = video.duration; if (Number.isFinite(d) && d > 0 && !Number.isNaN(d)) { setProbedDurationSeconds(d); } else { setProbedDurationSeconds(null); } }; const onError = () => { if (!cancelled) setProbedDurationSeconds(null); }; video.addEventListener("loadedmetadata", onLoaded); video.addEventListener("error", onError); video.src = url; return () => { cancelled = true; video.removeEventListener("loadedmetadata", onLoaded); video.removeEventListener("error", onError); video.removeAttribute("src"); video.load(); }; }, [duration, durationSeconds, videoUrl]); useEffect(() => { if (duration?.trim()) { setVimeoDurationSeconds(null); return; } if ( typeof durationSeconds === "number" && Number.isFinite(durationSeconds) && durationSeconds > 0 ) { setVimeoDurationSeconds(null); return; } const url = videoUrl?.trim() ?? ""; const vimeoId = extractVimeoVideoId(url); if (!vimeoId) { setVimeoDurationSeconds(null); return; } let cancelled = false; void fetchVimeoDurationSeconds(vimeoId).then((seconds) => { if (!cancelled) setVimeoDurationSeconds(seconds); }); return () => { cancelled = true; }; }, [duration, durationSeconds, videoUrl]); const durationLabel = (() => { const trimmed = duration?.trim(); if (trimmed) return trimmed; const fromApi = typeof durationSeconds === "number" && Number.isFinite(durationSeconds) && durationSeconds > 0 ? durationSeconds : null; if (fromApi != null) return formatVideoDurationLabel(fromApi); if ( vimeoDurationSeconds != null && Number.isFinite(vimeoDurationSeconds) && vimeoDurationSeconds > 0 ) { return formatVideoDurationLabel(vimeoDurationSeconds); } if ( probedDurationSeconds != null && Number.isFinite(probedDurationSeconds) && probedDurationSeconds > 0 ) { return formatVideoDurationLabel(probedDurationSeconds); } return null; })(); useEffect(() => { if (!previewOpen) { setIframeSessionDone(false); return; } if (videoPreview.kind !== "iframe" || !limitedEmbedSrc) { return; } if (iframeSessionDone) { return; } const ms = DEFAULT_PREVIEW_MAX_SECONDS * 1000; const id = window.setTimeout(() => { setIframeSessionDone(true); }, ms); return () => window.clearTimeout(id); }, [ previewOpen, videoPreview.kind, limitedEmbedSrc, iframeSessionDone, ]); const handlePreviewOpenChange = (open: boolean) => { setPreviewOpen(open); if (!open) { setIframeSessionDone(false); setIframeSessionKey((k) => k + 1); } }; return ( <>
{/* Thumbnail */}
{hoverModuleActions && (onEdit || onDelete || onViewPractices) ? (
{onViewPractices ? ( ) : null} {onEdit ? ( ) : null} {onDelete ? ( ) : null}
) : null} {!useGradient && thumbnailUrl ? ( setThumbFailed(true)} /> ) : null} {/* Duration — bottom-right on thumbnail */} {durationLabel ? (
{durationLabel}
) : null} {/* Play: opens preview dialog when videoUrl is set */} {canPreview ? ( ) : (
)}
e.preventDefault()} >

Short preview

{title}

The player closes automatically after {previewLengthLabel} in this window (YouTube/Vimeo can’t be trimmed reliably). For the full lesson, use your LMS app.

{videoPreview.kind === "iframe" && limitedEmbedSrc ? ( iframeSessionDone ? (

Preview time in this window has ended

The embed is removed after {previewLengthLabel} of real time so the full video is not available here.

{videoUrl && isAdminOrSuperAdminRole() ? ( Open full video in new tab ) : null}
) : (