'use client'
import {
DownloadIcon,
ExternalLinkIcon,
FilmIcon,
PauseIcon,
PlayIcon,
ScissorsIcon,
} from 'lucide-react'
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
import type { SpeechVodResolveResponse } from '@/app/(campaign)/campanha/(app)/comunicacao/acervo/resolver-vod/types'
import { SpeechCutDialog } from '@/components/campaign/speech/SpeechCutDialog'
import { SpeechCutResultCard } from '@/components/campaign/speech/SpeechCutResultCard'
import { SpeechExcerptControls } from '@/components/campaign/speech/SpeechExcerptControls'
import { SpeechExcerptShare } from '@/components/campaign/speech/SpeechExcerptShare'
import { SpeechHighlightParts } from '@/components/campaign/speech/SpeechHighlightParts'
import { YoutubeIcon } from '@/components/socialIcons'
import { Button } from '@/components/ui/button'
import { Spinner } from '@/components/ui/Spinner'
import { postCampaignJson } from '@/lib/campaignJsonRequest'
import type { SpeechCutViewModel } from '@/lib/speechCut'
import {
excerptPreviewStopAt,
excerptSelectionDuration,
extendRangeToSegment,
initialExcerptRange,
isExcerptSelectionAvailable,
MIN_EXCERPT_SECONDS,
SPEECH_EXCERPT_REQUEST_EVENT,
type ExcerptPreviewPhase,
type ExcerptRange,
} from '@/lib/speechExcerptSelection'
import { buildSpeechExcerptYoutubeUrl } from '@/lib/speechShare'
import { youtubeThumbnailUrl, 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.'
/** C173 — the preview action keeps the row's height and goes full width on touch. */
const PREVIEW_BUTTON_CLASS = 'min-h-10 w-full sm:w-auto'
/** C181 — the pre-C178 embed contract, preserved for the in-page YouTube surface. */
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.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 id for the external exit; without it the exit block does not render. */
youtubeVideoId: string | null
/** Seconds from the session start to the excerpt; null drops `t=` from the external links. */
youtubeOffsetSeconds: number | null
/** Stored VOD + excerpt coordinates: the Câmara may be asked on click. */
vodResolvable: boolean
segments: readonly SpeechDetailSegmentViewModel[]
initialSeconds: number | null
/**
* C177 — official source (Diário) link; null drops the source button. Never
* fed with the YouTube URL: a source button that opened a video without the
* point duplicated (worse) the "Abrir no YouTube" exit.
*/
officialTextUrl: 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
/** C167 — official summary, the deterministic fallback for the cut metadata. */
speechSummary: string | null
}
const StatusPanel = ({
title,
detail,
busy = false,
children,
}: {
title: string
detail: string
busy?: boolean
children?: ReactNode
}) => (
{busy ? (
) : (
)}
{title}
{detail}
{children}
)
/**
* C178 — the YouTube is never an embedded entry surface (the anonymous embed can
* greet the assessor with a signin wall the app cannot even detect). Without a
* Câmara excerpt the speech gets an honest cover instead: a single click opens
* the video on YouTube, no iframe on the page.
*/
const YoutubeFacade = ({ videoId, href }: { videoId: string; href: string }) => (
Vídeo no YouTube
Abrir no YouTube
)
/**
* C178 — one player for the four acervo quadrants: the Câmara excerpt is the
* default surface when the speech has one (resolved on click: `video-sob-demanda`,
* exact `excerptTMs`, links probed before use), a clickable YouTube cover when it
* only has a session link, and honest states when neither path has a playable
* file. C181 — the YouTube embed returns as the opt-in in-page surface behind
* "Assistir no YouTube" (never the automatic entry, so the C178 signin wall is
* not re-created); transcript clicks seek the active surface (native seconds on
* the MP4, session-offset seconds on the embed).
*/
export const SpeechDetailPlayer = ({
speechId,
youtubeVideoId,
youtubeOffsetSeconds,
vodResolvable,
segments,
initialSeconds,
officialTextUrl,
durationSeconds,
speechType,
speechDateLabel,
speechSummary,
}: SpeechDetailPlayerProps) => {
const videoRef = useRef(null)
// C181 (C171-F1) — a transcript point clicked while the embed is active has to
// survive until the Câmara `