'use client'
import { DownloadIcon, ExternalLinkIcon, FilmIcon, PlayIcon, ScissorsIcon } from 'lucide-react'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import type { SpeechVodResolveResponse } from '@/app/(campaign)/campanha/(app)/comunicacao/acervo/resolver-vod/types'
import { SpeechExcerptControls } from '@/components/campaign/speech/SpeechExcerptControls'
import { SpeechExcerptShare } from '@/components/campaign/speech/SpeechExcerptShare'
import { SpeechHighlightParts } from '@/components/campaign/speech/SpeechHighlightParts'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/Spinner'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import {
extendRangeToSegment,
initialExcerptRange,
MIN_EXCERPT_SECONDS,
type ExcerptRange,
} from '@/lib/speechExcerptSelection'
import type { SpeechVodResolution } from '@/lib/speechVod'
import { cn } from '@/lib/utils'
import type { SpeechDetailSegmentViewModel } from '@/utilities/speech/speechViewModels'
const RESOLVE_ENDPOINT = '/campanha/comunicacao/acervo/resolver-vod'
const GENERATING_TITLE = 'A Câmara está gerando o trecho deste vídeo.'
const buildYoutubeSrc = (videoId: string, startSeconds: number | null): string => {
const params = new URLSearchParams({ playsinline: '1', rel: '0' })
if (startSeconds !== null && startSeconds > 0) {
params.set('start', String(Math.floor(startSeconds)))
}
return `https://www.youtube-nocookie.com/embed/${videoId}?${params.toString()}`
}
type ResolutionState =
| { kind: 'idle' }
| { kind: 'resolving' }
| { kind: 'generating' }
| { kind: 'resolved'; playbackUrl: string | null; downloadUrl: string | null }
| { kind: 'failed'; message: string | null }
const toResolutionState = (resolution: SpeechVodResolution): ResolutionState =>
resolution.state === 'pronto'
? {
kind: 'resolved',
playbackUrl: resolution.playbackUrl,
downloadUrl: resolution.downloadUrl,
}
: resolution.state === 'gerando'
? { kind: 'generating' }
: { kind: 'failed', message: null }
type SpeechDetailPlayerProps = {
speechId: number
/** C162 — YouTube default when the session link parses; null falls back to the VOD. */
youtubeVideoId: string | null
/** Seconds from the session start to the excerpt; null makes the YouTube seek inert. */
youtubeOffsetSeconds: number | null
/** Stored VOD + excerpt coordinates: the Câmara may be asked on click. */
vodResolvable: boolean
segments: readonly SpeechDetailSegmentViewModel[]
initialSeconds: number | null
sourceUrl: string | null
/** C166 — raw duration for the excerpt picker; null falls back to the last segment end. */
durationSeconds: number | null
/** C166 — speech type for the share message (`null` reads as "fala"). */
speechType: string | null
/** C166 — day label (`dd/mm/aaaa`) for the share message. */
speechDateLabel: string
}
const StatusPanel = ({
title,
detail,
busy = false,
children,
}: {
title: string
detail: string
busy?: boolean
children?: ReactNode
}) => (
{busy ? (
) : (
)}
{title}
{detail}
{children}
)
/**
* C162 — one player for the four acervo quadrants: YouTube default when the
* session link exists (no Câmara call on render), the stored VOD otherwise
* resolved on click (`video-sob-demanda`, exact `excerptTMs`, links probed
* before use), and honest states when neither path has a playable file.
* Transcript clicks seek the current surface: native seconds on the MP4,
* session-offset seconds on the YouTube embed.
*/
export const SpeechDetailPlayer = ({
speechId,
youtubeVideoId,
youtubeOffsetSeconds,
vodResolvable,
segments,
initialSeconds,
sourceUrl,
durationSeconds,
speechType,
speechDateLabel,
}: SpeechDetailPlayerProps) => {
const videoRef = useRef(null)
const [resolution, setResolution] = useState({ kind: 'idle' })
const [activeStart, setActiveStart] = useState(null)
// C166: one state for the explicit selection mode — a non-null range means
// the mode is on, so "selecting" cannot drift from "has a range".
const [selection, setSelection] = useState(null)
const [youtubeStart, setYoutubeStart] = useState(() =>
youtubeVideoId && youtubeOffsetSeconds !== null
? youtubeOffsetSeconds + (initialSeconds ?? 0)
: null,
)
const resolving = resolution.kind === 'resolving'
const playbackUrl = resolution.kind === 'resolved' ? resolution.playbackUrl : null
const selectionDuration = durationSeconds ?? segments.at(-1)?.endSeconds ?? null
const selectionAvailable = selectionDuration !== null && selectionDuration >= MIN_EXCERPT_SECONDS
const selecting = selection !== null
const showExcerptShare = selecting && Boolean(youtubeVideoId)
useEffect(() => {
const video = videoRef.current
if (!video || initialSeconds === null || initialSeconds <= 0) return
const seek = () => {
video.currentTime = initialSeconds
}
if (video.readyState >= 1) {
seek()
return
}
video.addEventListener('loadedmetadata', seek, { once: true })
return () => video.removeEventListener('loadedmetadata', seek)
}, [initialSeconds, playbackUrl])
const requestResolution = async (deliverDownload: boolean) => {
// Opened synchronously inside the click gesture so the popup blocker sees
// a user-initiated tab; pointed at the verified URL only after the probe.
const pendingTab = deliverDownload ? window.open('', '_blank') : null
setResolution({ kind: 'resolving' })
try {
const { ok, payload } = await postCampaignJson(RESOLVE_ENDPOINT, {
speechId,
})
if (!ok || payload.status !== 'success') {
pendingTab?.close()
setResolution({
kind: 'failed',
message: payload.status === 'error' ? payload.message : null,
})
return
}
const next = toResolutionState(payload.resolution)
setResolution(next)
if (!deliverDownload) return
if (next.kind === 'resolved' && next.downloadUrl) {
if (pendingTab) pendingTab.location.href = next.downloadUrl
else window.open(next.downloadUrl, '_blank')
return
}
pendingTab?.close()
} catch {
pendingTab?.close()
setResolution({ kind: 'failed', message: null })
}
}
const seekTo = (seconds: number) => {
if (youtubeVideoId) {
if (youtubeOffsetSeconds === null) return
setYoutubeStart(youtubeOffsetSeconds + seconds)
setActiveStart(seconds)
return
}
const video = videoRef.current
if (!video) return
video.currentTime = seconds
void video.play().catch(() => {})
}
const onTimeUpdate = () => {
const video = videoRef.current
if (!video) return
const current = video.currentTime
const active = segments.find(
(segment) => current >= segment.startSeconds && current < segment.endSeconds,
)
setActiveStart(active?.startSeconds ?? null)
}
const toggleSelection = () => {
if (selecting) {
setSelection(null)
return
}
if (selectionDuration === null || selectionDuration < MIN_EXCERPT_SECONDS) return
setSelection(initialExcerptRange(segments, selectionDuration))
}
// C162 keeps the transcript click seeking; C166 turns it into a phrase magnet
// while the explicit selection mode is on.
const onSegmentActivate = (index: number) => {
const segment = segments[index]
if (!segment) return
if (selection === null || selectionDuration === null) {
seekTo(segment.startSeconds)
return
}
setSelection(extendRangeToSegment(selection, segments, index, selectionDuration))
}
const seekable = youtubeVideoId ? youtubeOffsetSeconds !== null : Boolean(playbackUrl)
const renderMedia = (): ReactNode => {
if (youtubeVideoId) {
return (
)
}
if (playbackUrl) {
return (
)
}
if (resolution.kind === 'resolving') {
return (
)
}
if (resolution.kind === 'generating') {
return (
void requestResolution(false)}
>
Tentar novamente
)
}
if (resolution.kind === 'failed' || resolution.kind === 'resolved') {
return (
void requestResolution(false)}
>
Tentar novamente
)
}
if (vodResolvable) {
return (
void requestResolution(false)}>
Assistir o trecho
)
}
return (
)
}
const inlineNotice = youtubeVideoId ? (
resolution.kind === 'generating' ? (
{GENERATING_TITLE} Tente novamente em um momento.
) : resolution.kind === 'failed' ? (
{resolution.message ??
'Não foi possível resolver o arquivo deste trecho na Câmara. Tente novamente.'}
) : resolution.kind === 'resolved' && !resolution.downloadUrl ? (
O arquivo deste trecho não pôde ser verificado na Câmara agora.
) : null
) : null
return (
{renderMedia()}
{selection && selectionDuration !== null ? (
) : null}
{selectionAvailable ? (
Selecionar trecho
) : null}
{showExcerptShare && selection && youtubeVideoId ? (
) : null}
{vodResolvable ? (
{
if (resolution.kind === 'resolved' && resolution.downloadUrl) {
window.open(resolution.downloadUrl, '_blank')
return
}
void requestResolution(true)
}}
>
{resolving ? (
) : (
)}
Baixar vídeo (MP4)
) : null}
{sourceUrl ? (
Abrir fonte
) : null}
{inlineNotice}
{!youtubeVideoId && selectionAvailable ? (
Compartilhar por link exige o vídeo no YouTube
Esta fala não tem vídeo no YouTube — não há link externo que abra no ponto. Você ainda
pode baixar o MP4 ou abrir a fonte oficial, e a seleção de trecho continua disponível.
) : null}
{segments.length > 0 ? (
{selecting
? 'Transcrição (clique nas frases para marcar o trecho)'
: seekable
? 'Transcrição (clique para posicionar)'
: 'Transcrição'}
{segments.map((segment, index) => {
const active = activeStart === segment.startSeconds
const inSelection =
selection !== null &&
segment.endSeconds > selection.startSeconds &&
segment.startSeconds < selection.endSeconds
return (
onSegmentActivate(index)}
disabled={!seekable && !selecting}
className={cn(
'flex w-full gap-3 rounded-lg px-2 py-1.5 text-left transition-colors',
seekable && !selecting && 'hover:bg-muted',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
!selecting && active && 'bg-muted',
inSelection && 'border-l-2 border-primary bg-primary/10',
)}
>
{segment.startLabel}
)
})}
) : null}
)
}