import React from 'react';
import {
  ActivityIndicator,
  AppState,
  Dimensions,
  Image,
  Platform,
  Pressable,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import Video, {
  SelectedTrackType,
  SelectedVideoTrackType,
  type OnAudioTracksData,
  type OnBandwidthUpdateData,
  type OnLoadData,
  type OnPlaybackRateChangeData,
  type OnPlaybackStateChangedData,
  type OnProgressData,
  type OnReceiveAdEventData,
  type OnTextTracksData,
  type OnVideoErrorData,
  type OnVideoTracksData,
  type ReactVideoSourceProperties,
  type SelectedTrack,
  type SelectedVideoTrack,
  type VideoRef,
  type AdConfig,
  type EnumValues,
  type ResizeMode,
} from 'react-native-video';
import {
  type StreamConfig,
  fetchLiveStatus,
  fetchStreamConfig,
  getBannerFimUrl,
  getCdnName,
  getFailoverThresholds,
  getLiveSignal,
  getNextCdn,
  getStreamUrl,
  getSubtitleLanguages,
  getSubtitleTracks,
  getThumbnailUrl,
  getThumbnailVttUrl,
  isDvrEnabled,
  isVerticalVideo,
} from '../services/streamConfig';
import { getOrCreateUid } from '../services/uid';
import { HttpError, httpGetText } from '../services/http';
import {
  checkIntegration,
  takeIntegrationWarning,
  takeStaleBuildWarning,
  type IntegrationStatus,
} from '../services/integrationCheck';
import {
  fetchSubtitleCues,
  findCue,
  type SubtitleCue,
} from '../services/subtitles';
import {
  fetchImageStreamCues,
  fetchThumbnailCues,
  type ThumbnailCue,
} from '../services/thumbnails';
import { parseVariantBitrates } from '../services/manifest';
import { TelemetrySession } from '../services/telemetry';
import {
  buildCustomAdsConfig,
  resolveAdLoadRoute,
  resolveAdPlan,
  type AdPlan,
} from './ads';
import {
  loadMediaOnReceiver,
  subscribeToCastSession,
  type CastSessionHandle,
} from './cast';
import CastButton from './CastButton';
import { CdnFailoverController, type SwitchTrigger } from './cdnFailover';
import type {
  Props,
  SpallaPlayerNativeEvent,
  SubtitleSizeConfig,
  allowedPlaybackRates,
} from './types';

type TextTrackInfo = {
  index: number;
  title?: string;
  language?: string;
};

type AudioTrackInfo = {
  index: number;
  title?: string;
  language?: string;
  selected?: boolean;
};

type VideoTrackInfo = {
  index: number;
  bitrate?: number;
  width?: number;
  height?: number;
  selected?: boolean;
};

type State = {
  config: StreamConfig | null;
  uid: string;
  streamSource: string;
  currentLiveSignal: 's1' | 's2' | null;
  currentCdnName: string | null;
  includeAdInSource: boolean;
  // Two-phase ads: CSAI pre-roll first, then reload with the DAI stream.
  adPhase: 'preroll' | 'main';
  loading: boolean;
  errorMessage: string | null;
  paused: boolean;
  casting: boolean;
  castDeviceName: string | null;
  textTracks: TextTrackInfo[];
  audioTracks: AudioTrackInfo[];
  videoTracks: VideoTrackInfo[];
  fullscreen: boolean;
  pip: boolean;
  overlaySubtitleText: string | null;
  // Imperative overrides; undefined means "follow the prop".
  subtitleOverride: string | null | undefined;
  audioTrackOverride: string | null | undefined;
  playbackRateOverride: allowedPlaybackRates | undefined;
  // Quality pin; null/undefined means automatic ABR.
  bitrateOverride: number | null | undefined;
  // Temporary ABR cap right after a CDN switch (web's qualidadeMinima).
  qualityCapBitrate: number | null;
  // The thumbnail only stands in for content that never rendered; bringing it
  // back mid-session (a CDN switch) reads as the player crashing to a splash.
  posterVisible: boolean;
};

const PLAYBACK_RATES: allowedPlaybackRates[] = [0.25, 0.5, 1.0, 1.25, 1.5, 2.0];

// Web parity (prerollTimeout): give the pre-roll tag this long to start an ad
// break before skipping straight to the DAI stream.
const PREROLL_AD_TIMEOUT_MS = 8000;

// iOS never reports an error when a Google DAI stream request fails (Android
// does), so a broken DAI source would hang on a black screen forever. Give the
// DAI stream this long to start before dropping to the ad-free CDN stream.
const DAI_STREAM_TIMEOUT_MS = 10000;

// The IMA AdsMediaSource holds the content back until the pre-roll resolves, so
// a tag that never answers leaves the player buffering with no decoder activity.
const CSAI_CONTENT_TIMEOUT_MS = 12000;

// An ad break that goes this long without a sign of life is stuck: the creative
// stalled, or the break never opened after LOADED.
const AD_BREAK_STALL_MS = 30000;

// IMA keeps firing AD_PROGRESS on a creative that is frozen or crawling, so the
// break only counts as alive on a state transition — quartiles included, which
// an ad playing at a watchable speed always delivers well inside the window.
const AD_LIVENESS_EVENTS = new Set([
  'LOADED',
  'AD_BREAK_STARTED',
  'AD_PERIOD_STARTED',
  'CONTENT_PAUSE_REQUESTED',
  'STARTED',
  'RESUMED',
  'FIRST_QUARTILE',
  'MIDPOINT',
  'THIRD_QUARTILE',
  'COMPLETED',
  'SKIPPED',
]);

// ExoPlayer dispatches onIsPlayingChanged before the onEvents that produces
// onBuffer, so telling a real pause apart from a stall only settles a tick later.
const PAUSE_DETECT_DELAY_MS = 250;

// Hysteresis so the live-edge flag survives the DVR window growing in steps at
// every playlist refresh instead of blinking around a single threshold.
const LIVE_EDGE_ENTER_S = 12;
const LIVE_EDGE_EXIT_S = 20;

// A seek refills the buffer from scratch, which looks exactly like a stall.
const SEEK_GRACE_MS = 8000;

// Expanding a PiP window back to fullscreen also reports PiP as inactive; wait
// for the activity to resume before deciding the window was really dismissed.
// The 'active' AppState event still races this timer — it rides the same
// bridge, and a busy JS thread delivers it after the pause already fired — so
// settlePipExitPause() cancels or undoes the pause when 'active' lands.
const PIP_EXIT_PAUSE_DELAY_MS = 1500;

// An 'active' AppState event this long after the dismissal pause fired is the
// expansion winning the race late; after that it means the user reopened the
// app, which must stay paused.
const PIP_EXIT_RESUME_WINDOW_MS = 3000;

// media3 PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW, prefixed with the "2"
// react-native-video adds to every ExoPlayer code.
const BEHIND_LIVE_WINDOW_CODE = '21002';

// Live status drives the signal (s1/s2) swap and the "stream ended" banner.
const LIVE_STATUS_POLL_MS = 5000;

// Probing the failing manifest classifies the error for telemetry; the switch
// must not wait on it, so the probe is capped well under the switch delay.
const ERROR_DIAGNOSIS_TIMEOUT_MS = 3000;

// The master playlist is remote text fed to a parser; cap it like the others.
const MANIFEST_MAX_BYTES = 4 * 1024 * 1024;
const SDK_VERSION = '3.0.9';

const RESIZE_MODES: Record<string, EnumValues<ResizeMode>> = {
  fit: 'contain',
  fill: 'stretch',
  aspectFill: 'cover',
};

// Keeps captions clear of the bottom edge/system bars; scales with the font
// so it stays proportional at every size. Integrators override any of this
// through the `subtitleAppearance` prop; these are only the SDK defaults.
const SUBTITLE_BOTTOM_PADDING_RATIO = 1.8;
const VERTICAL_SUBTITLE_FONT_SIZE = 16;

function fullscreenSubtitleFontSize(width: number, height: number): number {
  return Math.round(Math.min(32, Math.max(18, Math.min(width, height) * 0.06)));
}

function resolveSubtitleSize(
  defaultFontSize: number,
  config: SubtitleSizeConfig | undefined
): { fontSize: number; paddingBottom: number } {
  const fontSize = config?.fontSize ?? defaultFontSize;
  const paddingBottom =
    config?.bottomPadding ??
    Math.round(
      fontSize * (config?.bottomPaddingRatio ?? SUBTITLE_BOTTOM_PADDING_RATIO)
    );
  return { fontSize, paddingBottom };
}

const DEFAULT_PIP_SUBTITLE_STYLE = resolveSubtitleSize(
  VERTICAL_SUBTITLE_FONT_SIZE,
  undefined
);

export default class SpallaPlayer extends React.Component<Props, State> {
  private videoRef = React.createRef<VideoRef>();
  private pollingInterval: ReturnType<typeof setInterval> | null = null;
  private dimensionsSubscription: ReturnType<
    typeof Dimensions.addEventListener
  > | null = null;
  private appStateSubscription: ReturnType<
    typeof AppState.addEventListener
  > | null = null;
  private castSubscription: CastSessionHandle | null = null;
  private loadGeneration = 0;
  private lastEmittedRate: number | null = null;
  private announcedSubtitlesKey: string | null = null;
  private announcedAudioTracksKey: string | null = null;
  private unmounted = false;
  private cachedAdPlanKey: string | null = null;
  private cachedAdPlan: AdPlan = {};
  private cachedAdConfigKey: string | null = null;
  private cachedAdConfig: AdConfig | undefined;
  private cachedSourceKey: string | null = null;
  private cachedSource: ReactVideoSourceProperties | null = null;
  private overlayCues: SubtitleCue[] | null = null;
  private overlayLanguage: string | null = null;
  private overlayGeneration = 0;
  // seekableDuration is not comparable across platforms (window length on iOS,
  // window end on Android), so the live edge is tracked in the player's own
  // timeline: currentTime advances at 1x on both while playing live, which
  // makes wall clock a shared ruler once anchored.
  private liveEdgeAnchorTime = -1;
  private liveEdgeAnchorWallMs = 0;
  private atLiveEdge = false;
  private lastLiveEdgeTime = 0;
  private pendingDaiLiveEdgeSeek = false;
  private lastSeekAtMs = 0;
  private availableSubtitles: string[] = [];
  private availableAudioTracks: string[] = [];
  private manifestBitrates: number[] = [];
  private currentBitrate = 0;
  private currentBandwidth = 0;
  private videoDuration = 0;
  private videoWidth = 0;
  private videoHeight = 0;
  private videoEnded = false;
  private telemetryInitTime = Date.now();
  private telemetryPlaybackTime = 0;
  private telemetryFirstPlayAt = 0;
  private telemetryFirstFrameTime = 0;
  private telemetryRebufferTotal = 0;
  private telemetryRebufferDuration = 0;
  private telemetryRebufferStartedAt = 0;
  private telemetrySeekTotal = 0;
  private telemetrySeekDuration = 0;
  private telemetrySeekDurationMax = 0;
  private telemetrySeekStartedAt = 0;
  private telemetryBuffer = 0;
  private fullscreen = false;
  private inPiP = false;
  private pipAspectRefreshPending = false;
  private telemetry: TelemetrySession | null = null;
  private failover = new CdnFailoverController();
  private stallTimer: ReturnType<typeof setTimeout> | null = null;
  private pendingErrorSwitch = false;
  private pendingErrorSwitchTimer: ReturnType<typeof setTimeout> | null = null;
  private qualityRestoreTimer: ReturnType<typeof setTimeout> | null = null;
  private lastCurrentTime = 0;
  // Last position reported outside an ad break: during a break Android
  // reports the ad timeline on the same callback, so only ticks outside one
  // are a valid VoD resume point for the ad fallback reload.
  private lastContentTime = 0;
  // VoD playhead to restore after a CDN switch, in seconds.
  private resumePosition = 0;
  private inAdBreak = false;
  private buffering = false;
  private metadataEmitted = false;
  private contentLoaded = false;
  private pauseDetectTimer: ReturnType<typeof setTimeout> | null = null;
  // Set by an SDK-initiated source swap (ad fallback, CDN failover) until the
  // new item loads: the old item stopping is not the viewer pausing.
  private sourceSwapPending = false;
  private prerollAdTimer: ReturnType<typeof setTimeout> | null = null;
  private adWatchdogTimer: ReturnType<typeof setTimeout> | null = null;
  private adWatchdogLoaded = false;
  private adWatchdogLastTime = -1;
  private adWatchdogAdvances = 0;
  private adBreakTimer: ReturnType<typeof setTimeout> | null = null;
  private adBreakCompleted = false;
  private contentAdvancedSinceBreak = false;
  // Set when an ad actually started playing in the current break: ticks then
  // report the ad timeline (Android), so only the pre-break content position
  // is a safe resume point for the fallback reload. A break that opened
  // without an ad leaves the content ticks flowing, and those are the
  // freshest playhead there is.
  private adStartedInBreak = false;
  private returnToLiveAfterBreak = false;
  private returnToLiveAfterSourceSwap = false;
  // A CSAI (VAST/VMAP) break actually opened in this player instance. Deliberately
  // not reset by loadContent: the pre-roll counts as watched for the session, so
  // switching VoD never replays it (see resolveAdLoadRoute).
  private csaiAdPlayed = false;
  private pipExitPauseTimer: ReturnType<typeof setTimeout> | null = null;
  // Set when the dismissal pause actually fires; lets settlePipExitPause()
  // tell a late 'active' event (expand won the race) from the user reopening
  // the app after dismissing the window.
  private pipDismissalPausedAtMs = 0;

  constructor(props: Props) {
    super(props);
    this.state = {
      config: null,
      uid: '',
      streamSource: '',
      currentLiveSignal: null,
      currentCdnName: null,
      includeAdInSource: true,
      adPhase: 'preroll',
      loading: true,
      errorMessage: null,
      paused: props.autoplay === false,
      casting: false,
      castDeviceName: null,
      textTracks: [],
      audioTracks: [],
      videoTracks: [],
      fullscreen: false,
      pip: false,
      overlaySubtitleText: null,
      subtitleOverride: undefined,
      audioTrackOverride: undefined,
      playbackRateOverride: undefined,
      bitrateOverride: undefined,
      qualityCapBitrate: null,
      posterVisible: true,
    };
  }

  private effectiveSubtitle(): String | null | undefined {
    return this.state.subtitleOverride !== undefined
      ? this.state.subtitleOverride
      : this.props.subtitle;
  }

  private effectiveAudioTrack(): String | null | undefined {
    return this.state.audioTrackOverride !== undefined
      ? this.state.audioTrackOverride
      : this.props.audioTrack;
  }

  private effectivePlaybackRate(): allowedPlaybackRates {
    return this.state.playbackRateOverride ?? this.props.playbackRate ?? 1.0;
  }

  private getTelemetryData = (): Record<string, unknown> => {
    const { config, videoTracks } = this.state;
    const selected = videoTracks.find((track) => track.selected);
    const dimensions = Dimensions.get('window');
    const currentTime = this.lastCurrentTime;
    const source = this.state.streamSource.split('?')[0] || null;
    let sourceHostname = '';
    let sourceDomain = '';
    try {
      const parsed = new URL(this.state.streamSource);
      sourceHostname = parsed.hostname;
      sourceDomain = parsed.hostname.split('.').slice(-2).join('.');
    } catch {
      // The source can be empty or a relative URL during initial loading.
    }
    const counters = this.failover.getCounters();
    return {
      page_url: '',
      page_load_time: 0,
      connect_time: 0,
      render_time: 0,
      segmento: null,
      segmento_completo: null,
      segmento_tempo_download: 0,
      segmento_bytes: 0,
      usuario_id: this.state.uid,
      cdn: this.state.currentCdnName ?? '',
      cdn_tipo: 'global',
      cdn_troca_motivo: null,
      trocas_por_erro: counters.trocas_por_erro,
      trocas_por_tempo: counters.trocas_por_tempo,
      trocas_por_buffer: counters.trocas_por_buffer,
      tempo_limite_download: this.failover.stallLimitMs,
      intervalo_troca_cdn_automatico: this.failover.qualityRestoreMs,
      dash: false,
      stream_codec: '',
      stream_tipo: '',
      tipo: config?.lm_live_vod ? 'vod' : 'live',
      apenas_audio: false,
      saida_antes: false,
      telemetria_error_code: '',
      telemetria_error_message: '',
      engine: 'spalla-rn',
      nativo: true,
      safari: false,
      ios: Platform.OS === 'ios',
      tipo_embed: 'spalla_rn',
      player_nome: 'spalla-react-native',
      player_init_time: this.telemetryInitTime,
      player_autoplay: this.props.autoplay !== false,
      player_idioma: '',
      player_velocidade: this.effectivePlaybackRate(),
      player_fullscreen: this.fullscreen,
      player_pausado: this.state.paused || this.state.casting,
      player_playhead_time: currentTime,
      player_ui_current_time: currentTime,
      player_ui_altura: dimensions.height,
      player_ui_largura: dimensions.width,
      player_altura: this.videoHeight || selected?.height || 0,
      player_largura: this.videoWidth || selected?.width || 0,
      player_casting: this.state.casting,
      player_caster: this.state.casting ? 'chromecast' : '',
      spalla_build: SDK_VERSION,
      network_online: true,
      host: '',
      video_nome: config?.lm_live_nome || this.props.contentId,
      video_src: source,
      video_source_domain: sourceDomain || null,
      video_source_hostname: sourceHostname || null,
      video_source_duration: this.videoDuration,
      video_bitrate: this.currentBitrate,
      video_altura: this.videoHeight || selected?.height || 0,
      video_largura: this.videoWidth || selected?.width || 0,
      video_live: config ? !config.lm_live_vod : true,
      video_ended: this.videoEnded,
      current_time: Math.trunc(currentTime) || 0,
      video_rebuffer_total: this.telemetryRebufferTotal,
      video_rebuffer_duracao:
        this.telemetryRebufferDuration +
        (this.telemetryRebufferStartedAt
          ? Date.now() - this.telemetryRebufferStartedAt
          : 0),
      video_seek_total: this.telemetrySeekTotal,
      video_seek_duracao: this.telemetrySeekDuration,
      seek_duracao_maxima: this.telemetrySeekDurationMax,
      seek_duracao_total: this.telemetrySeekDuration,
      tempo_primeiro_frame: this.telemetryFirstFrameTime,
      tempo_reproduzindo: this.telemetryPlaybackTime,
      percentual_reproduzido:
        this.videoDuration > 0
          ? Math.min(100, (currentTime / this.videoDuration) * 100)
          : 0,
      view_content_playback_time: this.telemetryPlaybackTime,
      fazendo_rebuffer: this.buffering,
      bitrate_manual: this.state.bitrateOverride != null,
      frames_dropados: 0,
      frames_corrompidos: 0,
      banda_estimada: this.currentBandwidth,
      tamanho_buffer: this.telemetryBuffer,
      conta: config?.sp_conta ?? '',
      diretorio_id: config?.sp_diretorio_id ?? '',
      caminho_diretorio: config?.sp_caminho_diretorio ?? [],
      resume_habilitado: false,
      tipo_dispositivo: 'mobile',
      user_agent: Platform.OS,
      sistema_memoria: 0,
      browser_engine: Platform.OS,
      browser_nome: Platform.OS,
      browser_versao: String(Platform.Version),
      browser_fabricante: Platform.OS,
      browser_dispositivo: '',
      browser_mobile: true,
      browser_os_familia: Platform.OS,
      browser_os_versao: String(Platform.Version),
      browser_os_arquitetura: '',
      browser_webview: false,
    };
  };

  componentDidMount() {
    this.dimensionsSubscription = Dimensions.addEventListener('change', () => {
      if (!this.unmounted) {
        this.forceUpdate();
      }
    });
    this.appStateSubscription = AppState.addEventListener(
      'change',
      (nextState) => {
        if (
          Platform.OS === 'android' &&
          nextState === 'background' &&
          this.props.pipEnabled
        ) {
          this.requestEnterPiP();
        }
        if (nextState === 'active') {
          this.settlePipExitPause();
        }
      }
    );
    this.reportIntegration(takeIntegrationWarning());
    this.loadContent();
    this.castSubscription = subscribeToCastSession(
      () => this.getCastMediaParams(),
      (casting, deviceName) => {
        if (!this.unmounted) {
          if (casting) {
            // Playback moves to the receiver; the local ad watchdog would
            // otherwise fire on the now-paused <Video>.
            this.clearAdWatchdog();
            this.clearAdBreakTimer();
          }
          this.setState({ casting, castDeviceName: deviceName });
          this.telemetry?.event(casting ? 'caststart' : 'castend', {
            player_casting: casting,
            player_caster: casting ? 'chromecast' : '',
          });
          this.emit({ event: 'castStateChanged', casting, deviceName });
        }
      }
    );
    if (this.props.presentationMode === 'pip') {
      this.requestEnterPiP();
    }
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.contentId !== this.props.contentId) {
      this.loadContent();
      return;
    }

    if (prevProps.muted !== this.props.muted) {
      this.telemetry?.event('volumechange', {
        player_muted: this.props.muted === true,
      });
      this.emit({ event: this.props.muted ? 'muted' : 'unmuted' });
    }

    if (
      prevProps.subtitle !== this.props.subtitle &&
      this.props.subtitle != null
    ) {
      this.emit({
        event: 'subtitleSelected',
        subtitle: this.props.subtitle,
      });
    }

    if (prevProps.subtitle !== this.props.subtitle) {
      // A prop change overrules any earlier imperative override.
      this.setState({ subtitleOverride: undefined }, () =>
        this.syncOverlaySubtitle()
      );
    }

    if (
      prevProps.audioTrack !== this.props.audioTrack &&
      this.props.audioTrack !== undefined
    ) {
      this.emit({
        event: 'audioTrackSelected',
        audioTrack: this.props.audioTrack ?? null,
      });
    }

    if (prevProps.audioTrack !== this.props.audioTrack) {
      this.setState({ audioTrackOverride: undefined });
    }

    if (prevProps.playbackRate !== this.props.playbackRate) {
      this.setState({ playbackRateOverride: undefined });
    }

    if (prevProps.presentationMode !== this.props.presentationMode) {
      if (this.props.presentationMode === 'pip') {
        this.requestEnterPiP();
      } else if (prevProps.presentationMode === 'pip') {
        this.videoRef.current?.exitPictureInPicture();
      }
    }
  }

  componentWillUnmount() {
    this.unmounted = true;
    this.stopPolling();
    this.clearFailoverTimers();
    this.clearPrerollAdTimer();
    this.clearPauseDetectTimer();
    this.clearAdWatchdog();
    this.clearAdBreakTimer();
    this.clearPipExitPauseTimer();
    this.dimensionsSubscription?.remove();
    this.dimensionsSubscription = null;
    this.appStateSubscription?.remove();
    this.appStateSubscription = null;
    this.castSubscription?.remove();
    this.telemetry?.end();
    this.telemetry = null;
    this.failover.destroy();
    if (this.inPiP) {
      // iOS keeps the detached PiP layer alive after unmount, leaving an
      // orphaned window playing the old content.
      this.videoRef.current?.exitPictureInPicture();
    }
  }

  play = () => {
    // autoplay=false keeps the watchdog disarmed until playback is requested.
    if (!this.telemetryFirstPlayAt) {
      this.telemetryFirstPlayAt = Date.now();
    }
    this.setState({ paused: false }, () => this.armAdWatchdog());
    this.telemetry?.setData({ player_pausado: false });
    this.telemetry?.onPlay();
    this.emit({ event: 'play' });
  };

  pause = () => {
    this.setState({ paused: true });
    this.telemetry?.setData({ player_pausado: true });
    this.telemetry?.onPause();
    this.emit({ event: 'pause' });
  };

  seekTo = (time: number) => {
    if (!Number.isFinite(time) || time < 0) {
      this.reportNonFatal('seek_invalido', `seekTo(${time})`);
      return;
    }
    this.telemetrySeekTotal += 1;
    this.telemetrySeekStartedAt = Date.now();
    this.telemetry?.event('seeking');
    this.telemetry?.onSeek();
    this.lastSeekAtMs = Date.now();
    this.videoRef.current?.seek(time);
  };

  // On live streams with DVR, jumps back to the live edge.
  seekToLive = () => {
    const target = this.liveEdgeEstimate();
    if (target == null) {
      if (this.isLiveContent()) {
        this.reportNonFatal('seek_invalido', 'seekToLive sem borda ao vivo');
      }
      return;
    }
    this.telemetrySeekTotal += 1;
    this.telemetrySeekStartedAt = Date.now();
    this.telemetry?.event('seeking');
    this.telemetry?.onSeek();
    this.lastSeekAtMs = Date.now();
    this.videoRef.current?.seek(target);
  };

  // Native-control seeks don't pass through seekTo(); without this a DVR
  // seek back would be folded into the window-slide compensation, and the
  // post-seek buffer refill could be blamed on the CDN inside SEEK_GRACE_MS.
  private handleSeek = () => {
    this.lastSeekAtMs = Date.now();
  };

  private isLiveContent(): boolean {
    const { config } = this.state;
    return config != null && !config.lm_live_vod;
  }

  // Where the playhead would be now had it never left the live edge. That is
  // already one hold-back behind the true edge, which is exactly where a live
  // player is supposed to sit — seeking to the raw edge starves the buffer.
  private liveEdgeEstimate(): number | null {
    if (this.liveEdgeAnchorTime < 0) {
      return null;
    }
    return (
      this.liveEdgeAnchorTime + (Date.now() - this.liveEdgeAnchorWallMs) / 1000
    );
  }

  private trackLiveEdge(currentTime: number) {
    // Android reports the playhead inside the sliding DVR window: at each
    // playlist refresh the coordinate drops by ~one segment even though the
    // absolute position never moved. Left alone, the estimate pulls away from
    // those drops and the "latency" grows ~1x wall clock forever (340s in 6
    // minutes on a 2h window), flagging an edge-parked viewer as behind live.
    // A backward jump of at most a couple of segments is that window slide:
    // move the anchor down with it. Bigger drops (ad break, backgrounding)
    // are real time away from the edge, and the seek grace keeps user seeks
    // out — neither moves the anchor.
    if (this.liveEdgeAnchorTime >= 0 && this.lastLiveEdgeTime > 0) {
      const slide = this.lastLiveEdgeTime - currentTime;
      if (
        slide > 0 &&
        slide <= this.liveWindowSlideMaxS() &&
        Date.now() - this.lastSeekAtMs >= SEEK_GRACE_MS
      ) {
        this.liveEdgeAnchorTime -= slide;
      }
    }
    this.lastLiveEdgeTime = currentTime;
    const estimate = this.liveEdgeEstimate();
    // The playhead can never be ahead of the edge, so overtaking the estimate
    // means it drifted: re-anchor instead of accumulating the error.
    if (estimate == null || currentTime > estimate) {
      this.liveEdgeAnchorTime = currentTime;
      this.liveEdgeAnchorWallMs = Date.now();
      this.atLiveEdge = true;
      return;
    }
    const latency = estimate - currentTime;
    this.atLiveEdge = this.atLiveEdge
      ? latency <= LIVE_EDGE_EXIT_S
      : latency <= LIVE_EDGE_ENTER_S;
  }

  // One DVR window slide is ~one segment (lm_live_delay is the segment
  // duration the failover thresholds already use); a couple of segments of
  // jitter still cannot swallow an ad break or a backgrounding gap, which are
  // real time away from the edge and must keep their latency.
  private liveWindowSlideMaxS(): number {
    const segmentS = this.state.config?.lm_live_delay || 10;
    return segmentS * 2;
  }

  private resetLiveEdge() {
    this.liveEdgeAnchorTime = -1;
    this.liveEdgeAnchorWallMs = 0;
    this.lastLiveEdgeTime = 0;
    this.atLiveEdge = false;
    this.pendingDaiLiveEdgeSeek = false;
  }

  // null disables subtitles; a language/name from getAvailableSubtitles selects.
  setSubtitle = (subtitle: string | null) => {
    this.setState({ subtitleOverride: subtitle }, () =>
      this.syncOverlaySubtitle()
    );
    if (subtitle != null) {
      this.emit({ event: 'subtitleSelected', subtitle });
    }
  };

  getSubtitle = (): string | null => {
    const value = this.effectiveSubtitle();
    return value == null || value === '' ? null : String(value);
  };

  getAvailableSubtitles = (): string[] => {
    return [...this.availableSubtitles];
  };

  // null returns to the default track.
  setAudioTrack = (audioTrack: string | null) => {
    this.setState({ audioTrackOverride: audioTrack });
    this.emit({ event: 'audioTrackSelected', audioTrack });
  };

  getAudioTrack = (): string | null => {
    const value = this.effectiveAudioTrack();
    if (value != null && value !== '') {
      return String(value);
    }
    const selected = this.state.audioTracks.find((t) => t.selected);
    return selected ? selected.title || selected.language || null : null;
  };

  getAvailableAudioTracks = (): string[] => {
    return [...this.availableAudioTracks];
  };

  setPlaybackRate = (rate: allowedPlaybackRates) => {
    if (!PLAYBACK_RATES.includes(rate)) {
      this.reportNonFatal('velocidade_invalida', `setPlaybackRate(${rate})`);
      return;
    }
    this.setState({ playbackRateOverride: rate });
  };

  getPlaybackRate = (): allowedPlaybackRates => {
    return this.effectivePlaybackRate();
  };

  getAvailablePlaybackRates = (): allowedPlaybackRates[] => {
    return [...PLAYBACK_RATES];
  };

  enterFullscreen = () => {
    this.videoRef.current?.presentFullscreenPlayer();
  };

  exitFullscreen = () => {
    this.videoRef.current?.dismissFullscreenPlayer();
  };

  isFullscreen = (): boolean => {
    return this.fullscreen;
  };

  enterPiP = () => {
    this.requestEnterPiP();
  };

  exitPiP = () => {
    this.videoRef.current?.exitPictureInPicture();
  };

  isInPiP = (): boolean => {
    return this.inPiP;
  };

  // Android pauses the host activity once the PiP transition starts, and
  // React prop updates never reach the native view while paused (same as
  // pushSourceIfPiP()). Flip the appearance to the SDK default *before*
  // asking the OS to enter PiP, so the commit lands while the activity is
  // still fully active.
  private requestEnterPiP() {
    this.setState({ pip: true }, () => {
      this.videoRef.current?.enterPictureInPicture();
    });
  }

  // Pins the quality to a variant bitrate (from getAvailableBitrates);
  // null returns to automatic ABR.
  setBitrate = (bitrate: number | null) => {
    if (bitrate != null && (!Number.isFinite(bitrate) || bitrate <= 0)) {
      this.reportNonFatal('bitrate_invalido', `setBitrate(${bitrate})`);
      return;
    }
    this.setState({ bitrateOverride: bitrate });
  };

  getBitrate = (): number | null => {
    if (this.currentBitrate > 0) {
      return this.currentBitrate;
    }
    return this.state.bitrateOverride ?? null;
  };

  getAvailableBitrates = (): number[] => {
    // O manifest é a fonte confiável: parseVariantBitrates ignora as renditions
    // de I-FRAME/IMAGE, que o ExoPlayer devolve em videoTracks como se fossem
    // qualidades — fixar numa delas congela o vídeo.
    if (this.manifestBitrates.length > 0) {
      return [...this.manifestBitrates].sort((a, b) => a - b);
    }
    const bitrates = new Set<number>();
    for (const track of this.state.videoTracks) {
      if (track.bitrate && track.bitrate > 0) {
        bitrates.add(track.bitrate);
      }
    }
    return [...bitrates].sort((a, b) => a - b);
  };

  /** Diagnoses whether the required react-native-video patches are active. */
  checkIntegration = (): IntegrationStatus => checkIntegration();

  // An unpatched (or stale) react-native-video misbehaves in ways that look
  // like content bugs, so surface it on every channel the host app has.
  private reportIntegration(status: IntegrationStatus | null) {
    if (!status || status.ok || !status.message) {
      return;
    }
    console.error(`SpallaPlayer: ${status.message}`);
    this.telemetry?.keyEvent('erro_integracao', {
      player_error_code: status.issue,
      player_error_message: status.message,
    });
    this.emit({
      event: 'integrationWarning',
      code: status.issue ?? 'unknown',
      message: status.message,
    });
  }

  // Failures that don't stop playback still have to be observable: without
  // this a broken subtitle or cast session only shows up in a dev console.
  private reportNonFatal(scope: string, error: unknown) {
    const message =
      error instanceof Error ? error.message : String(error ?? 'unknown');
    this.telemetry?.keyEvent('erro_nao_fatal', {
      player_error_code: scope,
      player_error_message: message,
    });
    console.warn(`SpallaPlayer: ${scope}`, error);
  }

  private emit(
    payload: SpallaPlayerNativeEvent | { event: string; [key: string]: unknown }
  ) {
    this.props.onPlayerEvent?.({
      nativeEvent: payload as SpallaPlayerNativeEvent,
    });
  }

  private getCastMediaParams() {
    const { config, streamSource, uid, currentCdnName } = this.state;
    if (!config || !streamSource) {
      return null;
    }
    const dai = config.sp_ads_google_dai;
    let castDai;
    if (dai?.enabled === true) {
      if (dai.type === 'live' && dai.assetKey) {
        castDai = {
          availabilityType: 'live' as const,
          apiKey: dai.apiKey ?? '',
          assetKey: dai.assetKey,
        };
      } else if (dai.type === 'vod' && dai.contentSourceId && dai.videoId) {
        castDai = {
          availabilityType: 'vod' as const,
          apiKey: dai.apiKey ?? '',
          contentSourceID: dai.contentSourceId,
          videoID: dai.videoId,
        };
      }
    }
    return {
      contentUrl:
        streamSource || getStreamUrl(config, uid, currentCdnName ?? undefined),
      contentId: this.props.contentId,
      title: config.lm_live_nome,
      imageUrl: getThumbnailUrl(config) || undefined,
      isLive: !config.lm_live_vod,
      startTime: this.props.startTime,
      uid,
      accountId: config.sp_conta,
      dai: castDai,
      jwt: config.lm_live_jwt === true,
      imaCustParams: this.props.customImaParams,
    };
  }

  private async loadContent() {
    const generation = ++this.loadGeneration;
    this.stopPolling();
    // viewend da view anterior ao trocar de conteúdo
    this.telemetry?.end();
    this.telemetry = null;
    this.announcedSubtitlesKey = null;
    this.announcedAudioTracksKey = null;
    this.overlayCues = null;
    this.overlayLanguage = null;
    this.overlayGeneration++;
    this.resetLiveEdge();
    this.availableSubtitles = [];
    this.availableAudioTracks = [];
    this.manifestBitrates = [];
    this.currentBitrate = 0;
    this.currentBandwidth = 0;
    this.videoDuration = 0;
    this.videoWidth = 0;
    this.videoHeight = 0;
    this.videoEnded = false;
    this.telemetryPlaybackTime = 0;
    this.telemetryFirstPlayAt = 0;
    this.telemetryFirstFrameTime = 0;
    this.telemetryRebufferTotal = 0;
    this.telemetryRebufferDuration = 0;
    this.telemetryRebufferStartedAt = 0;
    this.telemetrySeekTotal = 0;
    this.telemetrySeekDuration = 0;
    this.telemetrySeekDurationMax = 0;
    this.telemetrySeekStartedAt = 0;
    this.telemetryBuffer = 0;
    this.pipAspectRefreshPending = false;
    this.failover.destroy();
    this.failover = new CdnFailoverController();
    this.clearFailoverTimers();
    this.clearPrerollAdTimer();
    this.clearPauseDetectTimer();
    this.clearAdBreakTimer();
    this.lastCurrentTime = 0;
    this.lastContentTime = 0;
    this.resumePosition = 0;
    this.inAdBreak = false;
    this.adBreakCompleted = false;
    this.contentAdvancedSinceBreak = false;
    this.adStartedInBreak = false;
    this.returnToLiveAfterBreak = false;
    this.returnToLiveAfterSourceSwap = false;
    this.buffering = false;
    this.metadataEmitted = false;
    this.contentLoaded = false;
    this.sourceSwapPending = false;
    // config/streamSource are intentionally NOT cleared: the <Video> must stay
    // mounted across content switches so an active PiP session survives and
    // starts playing the new item (playlist behavior). The new source simply
    // replaces the old one when it arrives. The ad route (includeAdInSource /
    // adPhase) is also kept for now: resetting it here would change the source
    // object and reload the OLD stream — mid-ad that means the pre-roll
    // playing again over the previous item while the config is in flight.
    this.setState({
      currentLiveSignal: null,
      loading: true,
      errorMessage: null,
      posterVisible: true,
      textTracks: [],
      audioTracks: [],
      videoTracks: [],
      overlaySubtitleText: null,
      subtitleOverride: undefined,
      audioTrackOverride: undefined,
      playbackRateOverride: undefined,
      bitrateOverride: undefined,
      qualityCapBitrate: null,
    });

    try {
      const uid = await getOrCreateUid();
      if (this.unmounted || generation !== this.loadGeneration) {
        return;
      }
      this.telemetry = new TelemetrySession({
        contentId: this.props.contentId,
        uid,
        getData: this.getTelemetryData,
      });
      const config = await fetchStreamConfig(this.props.contentId, uid);
      if (this.unmounted || generation !== this.loadGeneration) {
        return;
      }
      this.telemetry.setConfig(config);
      this.failover.configure({
        cdnCount: config.lm_live_cdns?.length ?? 0,
        isVod: config.lm_live_vod === true,
        thresholds: getFailoverThresholds(config),
      });
      // The ad route is decided against the NEW config: once a VAST/VMAP
      // break has played in this instance, a VoD switch loads without
      // repeating the ad (two-phase plans skip straight to the DAI stream).
      const adRoute = resolveAdLoadRoute(
        resolveAdPlan(config, this.props.customAds, this.props.customImaParams),
        config.lm_live_vod === true,
        this.csaiAdPlayed
      );
      const nextSource = getStreamUrl(config, uid);
      // Swapping the source of a mounted <Video> (e.g. dubbed ↔ original as
      // separate contentIds): the iOS fork pauses the old AVPlayer item before
      // replaceCurrentItem, and that stop must not be mirrored as a user pause.
      if (
        this.state.streamSource &&
        this.state.streamSource !== nextSource &&
        !this.state.casting
      ) {
        this.beginSourceSwap();
      }
      this.setState(
        {
          config,
          uid,
          streamSource: nextSource,
          currentLiveSignal: getLiveSignal(config),
          currentCdnName: getCdnName(config) || null,
          includeAdInSource: adRoute.includeAdInSource,
          adPhase: adRoute.adPhase,
          loading: false,
        },
        () => {
          // 'main' here only happens on the skip route (two-phase plan that
          // bypassed the pre-roll), so either branch means ads were held back.
          if (adRoute.adPhase === 'main' || !adRoute.includeAdInSource) {
            this.telemetry?.event('ad_suprimido');
          }
          this.startPollingIfLive();
          if (this.state.casting) {
            // Content switched while casting: play it on the receiver, not
            // locally (the local <Video> stays paused).
            const params = this.getCastMediaParams();
            if (params) {
              loadMediaOnReceiver(params).catch((e) =>
                this.reportNonFatal('erro_cast_load', e)
              );
            }
          }
          this.pushSourceIfPiP();
          // The ad route can silently never yield content (DAI request that
          // never answers, pre-roll tag that gates the AdsMediaSource), so
          // start watching right away.
          this.armAdWatchdog();
        }
      );
      this.loadThumbnails(config, uid, generation);
    } catch (e: any) {
      if (this.unmounted || generation !== this.loadGeneration) {
        return;
      }
      const message = e?.message || 'Failed to load stream';
      if (message === 'Network request failed') {
        this.telemetry?.event('networkerror');
        this.telemetry?.errorEvent('erro_config', 'network', message);
      } else {
        this.telemetry?.errorEvent('erro_config', 'config', message);
      }
      this.setState({ loading: false, errorMessage: message });
      this.emit({ event: 'error', message, error: message, canRetry: true });
    }
  }

  private startPollingIfLive() {
    const { config, uid } = this.state;
    if (!config || config.lm_live_vod || !uid) {
      return;
    }

    this.pollingInterval = setInterval(async () => {
      try {
        const status = await fetchLiveStatus(
          this.props.contentId,
          this.state.uid
        );
        if (this.unmounted) {
          return;
        }
        let changedSignal: 's1' | 's2' | null = null;
        this.setState(
          (prev) => {
            if (!prev.config) {
              return prev;
            }
            const nextConfig = { ...prev.config, ...status } as StreamConfig;
            const nextSignal = getLiveSignal(nextConfig);
            const currentSignal =
              prev.currentLiveSignal ?? getLiveSignal(prev.config);

            if (nextSignal && currentSignal && nextSignal !== currentSignal) {
              changedSignal = nextSignal;
              return {
                ...prev,
                config: nextConfig,
                currentLiveSignal: nextSignal,
                streamSource: getStreamUrl(
                  nextConfig,
                  prev.uid,
                  prev.currentCdnName ?? undefined
                ),
                includeAdInSource: false,
              };
            }
            return { ...prev, config: nextConfig };
          },
          () => {
            if (changedSignal) {
              this.telemetry?.event('cdnchange', { signal: changedSignal });
            }
          }
        );
      } catch (e) {
        this.reportNonFatal('erro_polling_live', e);
      }
    }, LIVE_STATUS_POLL_MS);
  }

  private stopPolling() {
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
      this.pollingInterval = null;
    }
  }

  private clearStallTimer() {
    if (this.stallTimer) {
      clearTimeout(this.stallTimer);
      this.stallTimer = null;
    }
  }

  private clearPrerollAdTimer() {
    if (this.prerollAdTimer) {
      clearTimeout(this.prerollAdTimer);
      this.prerollAdTimer = null;
    }
  }

  private clearPauseDetectTimer() {
    if (this.pauseDetectTimer) {
      clearTimeout(this.pauseDetectTimer);
      this.pauseDetectTimer = null;
    }
  }

  // If the pre-roll tag never opens an ad break (empty or slow VAST), skip
  // straight to the DAI stream.
  private maybeStartPrerollAdTimer() {
    if (
      this.prerollAdTimer ||
      this.inAdBreak ||
      this.state.paused ||
      this.state.adPhase !== 'preroll' ||
      !this.state.includeAdInSource ||
      !this.isTwoPhaseAdPlan()
    ) {
      return;
    }
    this.prerollAdTimer = setTimeout(() => {
      this.prerollAdTimer = null;
      this.advanceToDaiPhase();
    }, PREROLL_AD_TIMEOUT_MS);
  }

  // No-op unless the two-phase plan is still in the pre-roll phase.
  private advanceToDaiPhase() {
    this.clearPrerollAdTimer();
    if (
      this.unmounted ||
      this.state.adPhase !== 'preroll' ||
      !this.isTwoPhaseAdPlan()
    ) {
      return;
    }
    this.inAdBreak = false;
    // IMA may have paused the content for an ad that never started; the
    // switch to the DAI stream must resume playback on its own.
    this.setState({ adPhase: 'main', paused: false }, () => {
      this.pushSourceIfPiP();
      this.armAdWatchdog();
    });
  }

  // In PiP the host activity is paused and React prop updates never reach the
  // native view, so the new source has to be pushed imperatively.
  private pushSourceIfPiP() {
    if (!this.inPiP) {
      return;
    }
    const source = this.getSourceForRender(this.getAdConfigForRender());
    if (source) {
      this.videoRef.current?.setSource?.(source);
    }
  }

  private clearAdWatchdog() {
    if (this.adWatchdogTimer) {
      clearTimeout(this.adWatchdogTimer);
      this.adWatchdogTimer = null;
    }
    this.adWatchdogLoaded = false;
    this.adWatchdogLastTime = -1;
    this.adWatchdogAdvances = 0;
  }

  private clearAdBreakTimer() {
    if (this.adBreakTimer) {
      clearTimeout(this.adBreakTimer);
      this.adBreakTimer = null;
    }
  }

  // The break has to keep proving it is alive with an IMA state transition
  // (AD_LIVENESS_EVENTS); silence means a creative that will never finish.
  private armAdBreakTimer() {
    this.clearAdBreakTimer();
    if (this.unmounted || !this.state.includeAdInSource) {
      return;
    }
    this.adBreakTimer = setTimeout(() => {
      this.adBreakTimer = null;
      if (!this.inAdBreak) {
        return;
      }
      if (
        this.state.paused ||
        this.state.casting ||
        // IMA holds the ad while Notification/Control Center or the app
        // switcher covers the app, and resumes it on 'active'.
        (Platform.OS === 'ios' && AppState.currentState !== 'active')
      ) {
        // Nothing can advance while the app holds playback; keep watching.
        this.armAdBreakTimer();
        return;
      }
      this.fallbackFromAds('ad_break_stalled');
    }, AD_BREAK_STALL_MS);
  }

  // Returns false when the break was dropped instead of started: a new break
  // with no content progress since the previous one is the pre-roll repeating
  // over content that never played (a mid-roll always has content in between).
  // That is a CSAI pathology: DAI pods are stitched into the stream, so a pod
  // can legitimately open with no content in between.
  private noteAdBreakStart(): boolean {
    // IMA announces one DAI pod more than once (AD_PERIOD_STARTED before
    // AD_BREAK_STARTED, and again per pod inside the same break): a start
    // while the break is already open is that same break, not a new one.
    if (this.inAdBreak) {
      return true;
    }
    if (
      this.getAdConfigForRender()?.type !== 'ssai' &&
      this.adBreakCompleted &&
      !this.contentAdvancedSinceBreak
    ) {
      this.fallbackFromAds('csai_repeat');
      return false;
    }
    this.inAdBreak = true;
    this.contentAdvancedSinceBreak = false;
    this.adStartedInBreak = false;
    // The break opening (not merely the tag loading) is what counts as the
    // session's ad watched; a later VoD switch must not replay it.
    if (this.getAdConfigForRender()?.type === 'csai') {
      this.csaiAdPlayed = true;
    }
    // A break holds the content while the live edge keeps moving, so a viewer
    // who was live must be taken back there; one who was scrubbing the DVR
    // window stays where they were.
    this.returnToLiveAfterBreak = this.isLiveContent() && this.atLiveEdge;
    this.clearStallTimer();
    this.armAdBreakTimer();
    return true;
  }

  // Guards against an ad route that never yields playable content:
  // - SSAI: iOS reports "loaded"/"playing" even when the DAI stream never
  //   renders (black/stalled), so it only stands down once playback actually
  //   advances (see handleProgress) or a DAI ad break starts.
  // - CSAI: the content is gated behind the pre-roll, so it stands down once
  //   the content itself plays — onLoad, or real progress after a mid-roll.
  //   onLoad is not guaranteed: on Android the first READY can land inside
  //   the pre-roll period and videoLoaded skips onLoad for it, so the
  //   progress path carries the stand-down (see handleProgress).
  // Either way the fallback is the same: drop the ad, play the CDN stream.
  private armAdWatchdog() {
    const kind = this.getAdConfigForRender()?.type;
    if (
      this.adWatchdogTimer ||
      this.unmounted ||
      this.state.paused ||
      this.state.casting ||
      this.inAdBreak ||
      !this.state.includeAdInSource ||
      (kind !== 'ssai' && kind !== 'csai') ||
      // Content that played before the break says nothing about this one: a
      // second break can gate it again and never give it back.
      (kind === 'csai' && this.contentAdvancedSinceBreak)
    ) {
      return;
    }
    this.adWatchdogLoaded = false;
    this.adWatchdogLastTime = -1;
    this.adWatchdogAdvances = 0;
    this.adWatchdogTimer = setTimeout(
      () => {
        this.adWatchdogTimer = null;
        if (kind === 'ssai' && !this.contentLoaded) {
          // A DAI stream that never even loads is the unpatched-Android shape.
          this.reportIntegration(takeStaleBuildWarning('dai_stream_timeout'));
        }
        this.fallbackFromAds(`${kind}_timeout`);
      },
      kind === 'ssai' ? DAI_STREAM_TIMEOUT_MS : CSAI_CONTENT_TIMEOUT_MS
    );
  }

  // Drops the ad and reloads the plain CDN stream (the DAI fallbackUri).
  private fallbackFromAds(reason: string) {
    const code =
      this.getAdConfigForRender()?.type === 'csai'
        ? 'csai_fallback'
        : 'dai_fallback';
    this.clearAdWatchdog();
    this.clearAdBreakTimer();
    if (this.unmounted || !this.state.includeAdInSource) {
      return;
    }
    this.telemetry?.keyEvent('erro_ad', {
      player_error_code: code,
      player_error_message: reason,
    });
    this.emit({ event: 'adError', error: `${code}: ${reason}` });
    if (this.inAdBreak) {
      // Dropping the ad mid-break: without closing it the app stays in "ad
      // playing" forever.
      this.inAdBreak = false;
      this.emit({ event: 'adBreakEnd' });
    }
    this.noteReturnToLiveAfterSourceSwap();
    // A stalled mid-roll leaves the viewer mid-content: carry the playhead
    // into the reload (the same resume a CDN switch keeps), instead of
    // restarting the VoD from zero. With an ad playing the ticks report the
    // ad timeline, so only the pre-break position is safe; a break that
    // opened without an ad kept the content playing, and its ticks are the
    // freshest position there is — resuming from the frozen pre-break one
    // would rewind the viewer by however long the break hung. Pre-roll
    // failures leave both at zero because no content ever played.
    if (!this.isLiveContent()) {
      const resume = this.adStartedInBreak
        ? this.lastContentTime
        : this.lastCurrentTime;
      if (resume > 0) {
        this.resumePosition = resume;
      }
    }
    this.beginSourceSwap();
    this.setState({ includeAdInSource: false }, () => this.pushSourceIfPiP());
  }

  private beginSourceSwap() {
    this.sourceSwapPending = true;
    this.clearPauseDetectTimer();
  }

  // Leaving the DAI stream rebuilds the player around the plain CDN source,
  // and the fork resumes the CDN timeline at the DAI position — the edge of a
  // 30-min DAI window lands ~90 min behind a 2h CDN window. The fresh load
  // then re-anchors the live-edge estimate wherever it landed, so nothing
  // downstream notices; a viewer who was at the edge has to be brought back.
  private noteReturnToLiveAfterSourceSwap() {
    if (
      this.state.includeAdInSource &&
      this.getAdConfigForRender()?.type === 'ssai' &&
      this.isLiveContent() &&
      this.atLiveEdge
    ) {
      this.returnToLiveAfterSourceSwap = true;
    }
  }

  // seekableDuration is the live window end in the playhead's own coordinates
  // on both platforms; the edge minus a small hold-back (3 segments, the same
  // room liveEdgeEstimate leaves) is where a live player is supposed to sit.
  private liveEdgeTargetFor(seekableDuration: number): number | null {
    if (!Number.isFinite(seekableDuration) || seekableDuration <= 0) {
      return null;
    }
    const segmentS = this.state.config?.lm_live_delay || 10;
    return Math.max(0, seekableDuration - segmentS * 3);
  }

  private prepareDaiLiveStart() {
    const adConfig = this.getAdConfigForRender();
    this.pendingDaiLiveEdgeSeek =
      Platform.OS === 'android' &&
      this.isLiveContent() &&
      this.state.config != null &&
      isDvrEnabled(this.state.config) &&
      !(this.props.startTime && this.props.startTime > 0) &&
      adConfig?.type === 'ssai' &&
      adConfig.streamType === 'live';
  }

  private clearFailoverTimers() {
    this.clearStallTimer();
    if (this.pendingErrorSwitchTimer) {
      clearTimeout(this.pendingErrorSwitchTimer);
      this.pendingErrorSwitchTimer = null;
    }
    this.pendingErrorSwitch = false;
    if (this.qualityRestoreTimer) {
      clearTimeout(this.qualityRestoreTimer);
      this.qualityRestoreTimer = null;
    }
  }

  private failoverAvailable(): boolean {
    const { config, casting } = this.state;
    if (!config || casting || this.props.autoCdnSwitch === false) {
      return false;
    }
    if (!this.failover.isEnabled()) {
      return false;
    }
    return getNextCdn(config, this.state.currentCdnName) !== null;
  }

  private applyCdnSwitch(trigger: SwitchTrigger, reason: string) {
    const { config, uid } = this.state;
    if (!config || !this.failoverAvailable()) {
      return;
    }
    const next = getNextCdn(config, this.state.currentCdnName);
    if (!next) {
      return;
    }
    if (config.lm_live_vod && this.lastCurrentTime > 0) {
      this.resumePosition = this.lastCurrentTime;
    }
    this.failover.recordSwitch(trigger);
    this.clearStallTimer();
    // Switching off the DAI stream rebuilds the player around the plain CDN
    // source: the same cross-timeline resume the ad fallback suffers from.
    this.noteReturnToLiveAfterSourceSwap();
    // The new CDN brings its own timeline; the old anchor no longer maps to it.
    this.resetLiveEdge();
    this.telemetry?.setCdn(next.Nome);
    this.telemetry?.event('cdnchange', {
      cdn_tipo: 'automatico',
      cdn_troca_motivo: reason,
      ...this.failover.getCounters(),
    });
    this.applyQualityCap();
    this.beginSourceSwap();
    this.setState(
      {
        streamSource: getStreamUrl(config, uid, next.Nome),
        currentCdnName: next.Nome,
        includeAdInSource: false,
        errorMessage: null,
      },
      () => this.pushSourceIfPiP()
    );
    this.emit({ event: 'cdnChanged', cdn: next.Nome, reason });
  }

  // Web's qualidadeMinima(): start light on the new CDN, then restore ABR.
  private applyQualityCap() {
    if (
      this.state.bitrateOverride != null ||
      this.manifestBitrates.length === 0
    ) {
      return;
    }
    this.setState({ qualityCapBitrate: Math.min(...this.manifestBitrates) });
    if (this.qualityRestoreTimer) {
      clearTimeout(this.qualityRestoreTimer);
    }
    this.qualityRestoreTimer = setTimeout(() => {
      this.qualityRestoreTimer = null;
      if (!this.unmounted) {
        this.setState({ qualityCapBitrate: null });
      }
    }, this.failover.qualityRestoreMs);
  }

  // Approximates the web's per-request download timeout, which RNV does not
  // expose: a continuous rebuffer longer than one segment duration.
  private startStallTimer() {
    if (this.stallTimer || this.inAdBreak || !this.failoverAvailable()) {
      return;
    }
    this.stallTimer = setTimeout(() => {
      this.stallTimer = null;
      if (this.unmounted || this.state.paused || this.state.casting) {
        return;
      }
      if (this.failover.canSwitchForBuffer()) {
        this.applyCdnSwitch('stall', 'troca_por_tempo');
      } else {
        // Still buffering: re-arm and re-check after another segment window.
        this.startStallTimer();
      }
    }, this.failover.stallLimitMs);
  }

  private tryFailoverForError(code: string): boolean {
    if (!this.failoverAvailable()) {
      return false;
    }
    if (this.pendingErrorSwitch) {
      return true;
    }
    this.pendingErrorSwitch = true;
    const generation = this.loadGeneration;
    const run = async () => {
      this.pendingErrorSwitchTimer = null;
      const reason = await this.diagnoseErrorReason(code);
      if (this.unmounted || generation !== this.loadGeneration) {
        this.pendingErrorSwitch = false;
        return;
      }
      this.pendingErrorSwitch = false;
      this.applyCdnSwitch('error', reason);
    };
    const delay = this.failover.errorSwitchDelayMs();
    if (delay <= 0) {
      run();
    } else {
      this.pendingErrorSwitchTimer = setTimeout(run, delay);
    }
    return true;
  }

  // The native error rarely carries the HTTP status; probe the manifest so
  // telemetry can distinguish http_404 from generic failures.
  private async diagnoseErrorReason(code: string): Promise<string> {
    const url = this.state.streamSource;
    if (!url) {
      return `troca_por_erro: ${code}`;
    }
    try {
      const response = await httpGetText(url, undefined, {
        timeoutMs: ERROR_DIAGNOSIS_TIMEOUT_MS,
      });
      if (response && !response.ok) {
        return `troca_por_erro: http_${response.status}`;
      }
    } catch (e) {
      if (e instanceof HttpError && e.kind === 'timeout') {
        return `troca_por_erro: timeout (${code})`;
      }
      return `troca_por_erro: network (${code})`;
    }
    return `troca_por_erro: ${code}`;
  }

  private checkBufferHealth(data: OnProgressData) {
    const { config, paused, casting } = this.state;
    if (!config || paused || casting || this.inAdBreak) {
      return;
    }
    // 0/negative means the platform didn't report buffered media; not a stall.
    if (data.playableDuration <= 0) {
      return;
    }
    const bufferAhead = data.playableDuration - data.currentTime;
    // A negative buffer is physically impossible: on Android the integer
    // buffered percentage quantizes playableDuration into 1% steps of the DVR
    // window, and right after the window slides the reading falls a whole
    // step (~72s on a 2h window) below the playhead. Discard the sample
    // instead of switching CDNs on a full buffer.
    if (bufferAhead < 0) {
      return;
    }
    if (bufferAhead >= this.failover.bufferMinS) {
      this.failover.recordRecovery();
      return;
    }
    if (config.sp_llhls === true || this.atLiveEdge) {
      // At the live edge there is nothing published left to buffer; LL-HLS runs
      // that close by design. Neither is a CDN fault.
      return;
    }
    // End of a VoD: the buffer-ahead shrinks toward zero because there is no
    // more media left to buffer, not because the CDN stopped delivering —
    // with this little remaining, even a healthy CDN reads below the minimum.
    // Reloading the source to play the last seconds costs a full player
    // rebuild (black screen with the spinner) for nothing.
    if (
      config.lm_live_vod === true &&
      this.videoDuration > 0 &&
      this.videoDuration - data.currentTime <= this.failover.bufferMinS
    ) {
      return;
    }
    if (Date.now() - this.lastSeekAtMs < SEEK_GRACE_MS) {
      return;
    }
    if (this.failoverAvailable() && this.failover.canSwitchForBuffer()) {
      this.applyCdnSwitch('buffer', 'troca_por_buffer');
    }
  }

  private async loadThumbnails(
    config: StreamConfig,
    uid: string,
    generation: number
  ) {
    // Single master fetch feeds both the variant bitrate list and the
    // manifest-declared thumbnails (EXT-X-IMAGE-STREAM-INF).
    const masterUrl = getStreamUrl(config, uid);
    let master: string | null = null;
    try {
      const response = await httpGetText(masterUrl, undefined, {
        maxBytes: MANIFEST_MAX_BYTES,
      });
      if (response.ok) {
        master = response.text;
      }
    } catch {
      // best-effort
    }
    if (this.unmounted || generation !== this.loadGeneration) {
      return;
    }
    if (master) {
      this.manifestBitrates = parseVariantBitrates(master);
    }

    if (!config.lm_live_vod) {
      return;
    }
    // Manifest-declared EXT-X-IMAGE-STREAM-INF wins over the thumbnail.vtt
    // convention; both produce the same cue shape.
    let cues: ThumbnailCue[] = [];
    if (master) {
      try {
        cues = await fetchImageStreamCues(masterUrl);
      } catch {
        // fall through to the VTT convention
      }
    }
    if (cues.length === 0) {
      const url = getThumbnailVttUrl(config, uid);
      if (!url) {
        return;
      }
      try {
        cues = await fetchThumbnailCues(url);
      } catch {
        // Best-effort: not every VoD ships a thumbnail track.
        return;
      }
    }
    if (this.unmounted || generation !== this.loadGeneration) {
      return;
    }
    if (cues.length > 0) {
      this.emit({ event: 'thumbnailsAvailable', thumbnails: cues });
    }
  }

  // Neither platform can sideload subtitle files into HLS through
  // react-native-video (AVPlayer has no API; the Android HLS factory ignores
  // subtitleConfigurations), so non-embedded languages render as a JS overlay
  // fed by the parsed SRT. Embedded manifest tracks always win.
  private shouldUseOverlay(value: string): boolean {
    const { config, textTracks } = this.state;
    if (!config || !getSubtitleLanguages(config).includes(value)) {
      return false;
    }
    return !textTracks.some((t) => t.language === value || t.title === value);
  }

  private syncOverlaySubtitle() {
    const subtitle = this.effectiveSubtitle();
    const value = subtitle == null || subtitle === '' ? null : String(subtitle);
    const generation = ++this.overlayGeneration;

    if (!value || !this.shouldUseOverlay(value)) {
      this.overlayCues = null;
      this.overlayLanguage = null;
      if (this.state.overlaySubtitleText !== null) {
        this.setState({ overlaySubtitleText: null });
      }
      return;
    }

    if (this.overlayLanguage === value && this.overlayCues) {
      return;
    }

    const { config, uid } = this.state;
    const track = getSubtitleTracks(config!, uid).find(
      (t) => t.language === value
    );
    if (!track) {
      return;
    }
    this.overlayLanguage = value;
    this.overlayCues = null;
    fetchSubtitleCues(track.uri)
      .then((cues) => {
        if (this.unmounted || generation !== this.overlayGeneration) {
          return;
        }
        this.overlayCues = cues;
      })
      .catch((e) => {
        this.reportNonFatal('erro_legenda', e);
      });
  }

  private getAdPlan(): AdPlan {
    const { config } = this.state;
    const { customAds, customImaParams } = this.props;

    // Memoize so the returned objects keep a stable identity across renders.
    // A new object each render makes react-native-video re-setup the player
    // (it memoizes its internal source by reference), causing a reload loop.
    const key = JSON.stringify({
      customAds: customAds ?? null,
      customImaParams: customImaParams ?? null,
      vast: config?.sp_ads_vast ?? null,
      vmap: config?.sp_ads_vmap ?? null,
      dai: config?.sp_ads_google_dai ?? null,
      ima: config?.sp_ads_google_ima ?? null,
      vertical: config?.sp_vertical === true,
    });
    if (key === this.cachedAdPlanKey) {
      return this.cachedAdPlan;
    }

    let plan: AdPlan = {};
    if (config) {
      plan = resolveAdPlan(config, customAds, customImaParams);
    } else if (customAds && customAds.length > 0) {
      const csai = buildCustomAdsConfig(customAds, customImaParams);
      plan = csai ? { csai } : {};
    }

    this.cachedAdPlanKey = key;
    this.cachedAdPlan = plan;
    return plan;
  }

  private isTwoPhaseAdPlan(): boolean {
    const plan = this.getAdPlan();
    return !!(plan.csai && plan.dai);
  }

  private getAdConfigForRender(): AdConfig | undefined {
    const plan = this.getAdPlan();
    const { adPhase, streamSource } = this.state;

    const key = `${this.cachedAdPlanKey}|${adPhase}|${streamSource}`;
    if (key === this.cachedAdConfigKey) {
      return this.cachedAdConfig;
    }

    const dai =
      plan.dai && streamSource
        ? { ...plan.dai, fallbackUri: streamSource }
        : plan.dai;
    const result =
      plan.csai && dai
        ? adPhase === 'preroll'
          ? plan.csai
          : dai
        : (dai ?? plan.csai);

    this.cachedAdConfigKey = key;
    this.cachedAdConfig = result;
    return result;
  }

  private getSourceForRender(
    adConfig: AdConfig | undefined
  ): ReactVideoSourceProperties | null {
    const { streamSource, includeAdInSource } = this.state;
    const { startTime } = this.props;

    if (!streamSource) {
      return null;
    }

    // Memoize the source object identity; see getAdConfigForRender above.
    const resume = this.resumePosition;
    const key = JSON.stringify({
      streamSource,
      startTime: startTime ?? null,
      resume,
      includeAdInSource,
      adConfig: adConfig ?? null,
    });
    if (key === this.cachedSourceKey) {
      return this.cachedSource;
    }

    const startPositionMs =
      resume > 0
        ? Math.floor(resume * 1000)
        : startTime && startTime > 0
          ? startTime * 1000
          : 0;
    const source: ReactVideoSourceProperties = {
      uri: streamSource,
      ...(startPositionMs > 0 ? { startPosition: startPositionMs } : {}),
      ...(includeAdInSource && adConfig ? { ad: adConfig } : {}),
    };
    this.cachedSourceKey = key;
    this.cachedSource = source;
    return source;
  }

  private resolveSelectedTextTrack(): SelectedTrack | undefined {
    const subtitle = this.effectiveSubtitle();
    if (subtitle === undefined) {
      return undefined;
    }
    if (subtitle === null || subtitle === '') {
      return { type: SelectedTrackType.DISABLED };
    }
    const value = String(subtitle);
    if (this.shouldUseOverlay(value)) {
      return { type: SelectedTrackType.DISABLED };
    }
    const tracks = this.state.textTracks;
    if (tracks.some((t) => t.language === value)) {
      return { type: SelectedTrackType.LANGUAGE, value };
    }
    if (Platform.OS === 'ios') {
      // react-native-video's iOS title lookup traps on metadata-less options
      // (e.g. CC placeholders), so address the track by index instead.
      const byTitle = tracks.find((t) => t.title === value);
      if (byTitle) {
        return {
          type: SelectedTrackType.INDEX,
          value: String(byTitle.index),
        };
      }
      return { type: SelectedTrackType.DISABLED };
    }
    return { type: SelectedTrackType.TITLE, value };
  }

  private resolveSelectedAudioTrack(): SelectedTrack | undefined {
    const audioTrack = this.effectiveAudioTrack();
    if (audioTrack === undefined) {
      return undefined;
    }
    if (audioTrack === null || audioTrack === '') {
      return undefined;
    }
    const value = String(audioTrack);
    const tracks = this.state.audioTracks;
    if (tracks.some((t) => t.language === value)) {
      return { type: SelectedTrackType.LANGUAGE, value };
    }
    if (Platform.OS === 'ios') {
      // Same crash-avoidance as resolveSelectedTextTrack; unknown values fall
      // back to the system default instead of disabling audio.
      const byTitle = tracks.find((t) => t.title === value);
      if (byTitle) {
        return {
          type: SelectedTrackType.INDEX,
          value: String(byTitle.index),
        };
      }
      return undefined;
    }
    return { type: SelectedTrackType.TITLE, value };
  }

  // Android pins the exact variant when a matching track is known; otherwise
  // (and always on iOS) the pin degrades to a maxBitRate cap on the ABR.
  private resolveSelectedVideoTrack(): SelectedVideoTrack | undefined {
    const { bitrateOverride, videoTracks } = this.state;
    if (bitrateOverride == null) {
      return undefined;
    }
    if (Platform.OS === 'android') {
      const match = videoTracks.find((t) => t.bitrate === bitrateOverride);
      if (match) {
        return { type: SelectedVideoTrackType.INDEX, value: match.index };
      }
    }
    return undefined;
  }

  private resolveMaxBitRate(): number {
    const { bitrateOverride, videoTracks, qualityCapBitrate } = this.state;
    const target = bitrateOverride ?? qualityCapBitrate;
    if (target == null) {
      return 0;
    }
    if (
      bitrateOverride != null &&
      Platform.OS === 'android' &&
      videoTracks.some((t) => t.bitrate === bitrateOverride)
    ) {
      return 0;
    }
    return this.bitrateCeilingFor(target);
  }

  // maxBitRate (e preferredPeakBitRate no iOS) é teto, não seleção: no valor
  // exato do BANDWIDTH declarado nenhuma variante cabe e o playback congela.
  // O teto vai logo abaixo da próxima variante, que é a maior folga possível
  // sem liberar a qualidade seguinte.
  private bitrateCeilingFor(bitrate: number): number {
    const ladder = this.getAvailableBitrates();
    const next = ladder.find((value) => value > bitrate);
    return next ? next - 1 : Math.round(bitrate * 1.1);
  }

  private announceSubtitles(incoming: TextTrackInfo[]) {
    const tracks = incoming.length > 0 ? incoming : this.state.textTracks;
    if (incoming.length > 0) {
      this.setState({ textTracks: incoming });
    }

    // Nameless tracks (e.g. iOS CC placeholders) cannot be selected safely.
    const usable = tracks.filter((t) => t.title || t.language);
    const labels = usable.map((t) => t.title || t.language || String(t.index));
    const { config } = this.state;
    const configLanguages = config ? getSubtitleLanguages(config) : [];
    // Sem case: o manifest declara LANGUAGE="pt-BR" e o config, "pt-br" — o
    // ExoPlayer normaliza para minúsculas, o AVPlayer não, e a legenda saía
    // duplicada no iOS.
    const sameLabel = (a: string | undefined, b: string) =>
      typeof a === 'string' && a.toLowerCase() === b.toLowerCase();
    for (const lang of configLanguages) {
      const covered =
        labels.some((label) => sameLabel(label, lang)) ||
        tracks.some(
          (t) => sameLabel(t.language, lang) || sameLabel(t.title, lang)
        );
      if (!covered) {
        labels.push(lang);
      }
    }

    if (labels.length === 0) {
      return;
    }
    this.availableSubtitles = labels;
    const key = JSON.stringify(labels);
    if (key !== this.announcedSubtitlesKey) {
      this.announcedSubtitlesKey = key;
      this.emit({ event: 'subtitlesAvailable', subtitles: labels });
    }
    this.syncOverlaySubtitle();
  }

  private handleAudioTracks = (data: OnAudioTracksData) => {
    const tracks: AudioTrackInfo[] = (data.audioTracks ?? []).map((t) => ({
      index: t.index,
      title: t.title,
      language: t.language,
      selected: t.selected,
    }));
    if (tracks.length === 0) {
      return;
    }
    this.setState({ audioTracks: tracks });
    // Nameless tracks cannot be selected safely; see announceSubtitles.
    const labels = tracks
      .filter((t) => t.title || t.language)
      .map((t) => t.title || t.language || String(t.index));
    if (labels.length === 0) {
      return;
    }
    this.availableAudioTracks = labels;
    const key = JSON.stringify(labels);
    if (key !== this.announcedAudioTracksKey) {
      this.announcedAudioTracksKey = key;
      this.emit({ event: 'audioTracksAvailable', audioTracks: labels });
    }
  };

  private handleVideoTracks = (data: OnVideoTracksData) => {
    const tracks: VideoTrackInfo[] = (data.videoTracks ?? []).map((t, i) => ({
      index: t.index ?? i,
      bitrate: t.bitrate,
      width: t.width,
      height: t.height,
      selected: t.selected,
    }));
    if (tracks.length === 0) {
      return;
    }
    this.setState({ videoTracks: tracks });
    const selected = tracks.find((t) => t.selected);
    if (selected?.bitrate && selected.bitrate > 0) {
      const changed = this.currentBitrate !== selected.bitrate;
      this.currentBitrate = selected.bitrate;
      if (changed) {
        this.telemetry?.event('renditionchange', {
          video_bitrate: selected.bitrate,
          video_largura: selected.width ?? 0,
          video_altura: selected.height ?? 0,
        });
      }
    }
  };

  // Android only emits onLoad once the content (not the ad) is ready, so a
  // pre-roll defers metadataLoaded forever when the content stalls afterwards.
  // Callers without OnLoadData get the payload derived from the stream config.
  private emitMetadata(data?: OnLoadData) {
    const { config } = this.state;
    const selectedVideoTrack = data?.videoTracks?.find((t) => t.selected);
    const width = selectedVideoTrack?.width ?? data?.naturalSize.width ?? 0;
    const height = selectedVideoTrack?.height ?? data?.naturalSize.height ?? 0;
    const duration = data?.duration ?? 0;
    this.videoWidth = width;
    this.videoHeight = height;
    this.videoDuration = duration;
    this.videoEnded = false;
    this.metadataEmitted = true;
    this.emit({
      event: 'metadataLoaded',
      isLive: config ? !config.lm_live_vod : duration === 0,
      duration,
      isVertical:
        (config ? isVerticalVideo(config) : false) ||
        data?.naturalSize.orientation === 'portrait' ||
        (height > 0 && width > 0 && height > width),
      dvrEnabled: config ? isDvrEnabled(config) : false,
      lowLatency: config?.sp_llhls === true,
      // extra diagnostic fields, not part of the legacy contract
      width,
      height,
      bitrate: selectedVideoTrack?.bitrate ?? 0,
    });
  }

  private emitMetadataIfPending() {
    if (!this.metadataEmitted && this.state.config) {
      this.emitMetadata();
    }
  }

  private handleLoad = (data: OnLoadData) => {
    // Rebaseline the DAI watchdog to this freshly loaded item so residual
    // progress ticks from the previous (pre-roll) source can't confirm it.
    if (this.adWatchdogTimer) {
      this.adWatchdogLoaded = true;
      this.adWatchdogLastTime = -1;
      this.adWatchdogAdvances = 0;
    }
    // Real content is playable: a CSAI pre-roll can no longer gate it.
    this.contentLoaded = true;
    if (this.sourceSwapPending) {
      this.sourceSwapPending = false;
      // With native controls the iOS view mirrors the old item stopping into
      // its own paused flag and re-applies it to the new item; the `paused`
      // prop never changed, so only an explicit resume clears it.
      if (Platform.OS === 'ios' && !this.state.paused) {
        this.videoRef.current?.resume?.();
      }
    }
    // A fresh item means a fresh timeline; the old anchor no longer maps to it.
    this.resetLiveEdge();
    this.prepareDaiLiveStart();
    if (this.state.posterVisible) {
      this.setState({ posterVisible: false });
    }
    if (this.getAdConfigForRender()?.type === 'csai') {
      this.clearAdWatchdog();
    }
    if (data.videoTracks && data.videoTracks.length > 0) {
      this.handleVideoTracks({ videoTracks: data.videoTracks });
    }
    this.emitMetadata(data);
    this.emit({ event: 'durationUpdate', duration: data.duration });
    this.telemetry?.event('loadedmetadata');
    this.announceSubtitles(data.textTracks ?? []);
    if (Platform.OS === 'android' && this.inPiP) {
      // RNV only sets the PiP window aspect ratio on enter; re-invoking it
      // with the activity already in PiP just refreshes the params. Deferred
      // to the next progress tick (timers are paused in PiP) so ExoPlayer is
      // READY and player.videoSize reflects the new content.
      this.pipAspectRefreshPending = true;
    }
    this.maybeStartPrerollAdTimer();
  };

  private handleTextTracks = (data: OnTextTracksData) => {
    this.announceSubtitles(data.textTracks ?? []);
  };

  private handleProgress = (data: OnProgressData) => {
    const previousTime = this.lastCurrentTime;
    this.lastCurrentTime = data.currentTime;
    let soughtToDaiLiveEdge = false;
    const delta = data.currentTime - previousTime;
    if (
      !this.state.paused &&
      !this.state.casting &&
      !this.inAdBreak &&
      delta > 0 &&
      delta <= 2
    ) {
      this.telemetryPlaybackTime += delta;
    }
    if (this.telemetrySeekStartedAt && delta >= 0) {
      const elapsed = Date.now() - this.telemetrySeekStartedAt;
      this.telemetrySeekDuration += elapsed;
      this.telemetrySeekDurationMax = Math.max(
        this.telemetrySeekDurationMax,
        elapsed
      );
      this.telemetrySeekStartedAt = 0;
      this.telemetry?.event('seeked');
    }
    this.telemetryBuffer = Math.max(
      0,
      (data.playableDuration ?? data.currentTime) - data.currentTime
    );
    if (
      this.pendingDaiLiveEdgeSeek &&
      !this.inAdBreak &&
      this.isLiveContent()
    ) {
      const target = this.liveEdgeTargetFor(data.seekableDuration);
      if (target != null) {
        this.pendingDaiLiveEdgeSeek = false;
        if (target > data.currentTime + LIVE_EDGE_ENTER_S) {
          this.lastSeekAtMs = Date.now();
          this.videoRef.current?.seek(target);
          soughtToDaiLiveEdge = true;
        }
      }
    }
    if (
      !this.pendingDaiLiveEdgeSeek &&
      !soughtToDaiLiveEdge &&
      !this.inAdBreak &&
      this.isLiveContent()
    ) {
      this.trackLiveEdge(data.currentTime);
    }
    // Outside a break the position belongs to the content; inside it, to the ad
    // (Android reports the ad position on the same callback).
    if (!this.inAdBreak) {
      this.lastContentTime = data.currentTime;
    }
    // Real advance outside a break is the content playing, even without a
    // load event: on Android the first READY can land inside the pre-roll
    // period, and the native videoLoaded skips onLoad for it — so
    // contentLoaded stays false while the video plays and the previous gate
    // here let the CSAI watchdog drop a source that was working.
    if (!this.inAdBreak && data.currentTime > previousTime + 0.1) {
      this.contentAdvancedSinceBreak = true;
      // Content moving is stronger evidence than onLoad, which a mid-roll
      // never fires again.
      if (
        this.adWatchdogTimer &&
        this.getAdConfigForRender()?.type === 'csai'
      ) {
        this.clearAdWatchdog();
      }
    }
    if (
      !this.inAdBreak &&
      this.contentLoaded &&
      data.currentTime > previousTime + 0.1
    ) {
      // Waiting for real progress: at adBreakEnd the content has not resumed
      // yet and the seek would be swallowed.
      if (this.returnToLiveAfterBreak) {
        this.returnToLiveAfterBreak = false;
        if (!this.atLiveEdge && !this.state.paused && !this.state.casting) {
          this.seekToLive();
        }
      }
      // The DAI→CDN swap lands wherever the DAI timeline was (see
      // noteReturnToLiveAfterSourceSwap) and the re-anchored estimate calls
      // that the edge, so the target comes from the window itself.
      if (this.returnToLiveAfterSourceSwap) {
        this.returnToLiveAfterSourceSwap = false;
        const target = this.liveEdgeTargetFor(data.seekableDuration);
        if (target != null && !this.state.paused && !this.state.casting) {
          this.seekTo(target);
        }
      }
    }
    // Real playback confirms the DAI stream is rendering (not black/stalled),
    // so stand the watchdog down only after currentTime actually advances.
    if (this.adWatchdogTimer && this.adWatchdogLoaded) {
      if (
        this.adWatchdogLastTime >= 0 &&
        data.currentTime > this.adWatchdogLastTime + 0.1
      ) {
        this.adWatchdogAdvances += 1;
        if (this.adWatchdogAdvances >= 2) {
          this.clearAdWatchdog();
        }
      }
      this.adWatchdogLastTime = data.currentTime;
    }
    this.checkBufferHealth(data);
    if (this.pipAspectRefreshPending && this.inPiP) {
      this.pipAspectRefreshPending = false;
      this.videoRef.current?.enterPictureInPicture();
    }
    if (this.overlayCues) {
      const cue = findCue(this.overlayCues, data.currentTime);
      const text = cue?.text ?? null;
      if (text !== this.state.overlaySubtitleText) {
        this.setState({ overlaySubtitleText: text });
      }
    } else if (this.state.overlaySubtitleText !== null) {
      this.setState({ overlaySubtitleText: null });
    }
    this.telemetry?.onTimeUpdate(data.currentTime);
    const liveEdge = this.liveEdgeEstimate();
    this.emit({
      event: 'timeUpdate',
      time: data.currentTime,
      seekableDuration: data.seekableDuration,
      // extra diagnostic field, not part of the legacy contract
      playableDuration: data.playableDuration,
      ...(liveEdge != null
        ? {
            liveLatency: Math.max(0, liveEdge - data.currentTime),
            atLiveEdge: this.atLiveEdge,
          }
        : {}),
    });
  };

  private handleBandwidthUpdate = (data: OnBandwidthUpdateData) => {
    // Network throughput estimate — NOT the playing variant bitrate, so it
    // must not feed getBitrate(); diagnostic-only event.
    this.emit({
      event: 'bandwidthUpdate',
      bitrate: data.bitrate,
      width: data.width,
      height: data.height,
    });
    this.currentBandwidth = (data.bitrate ?? 0) / 1e6;
  };

  private handleBuffer = (data: { isBuffering: boolean }) => {
    this.buffering = data.isBuffering;
    if (data.isBuffering) {
      if (!this.telemetryRebufferStartedAt) {
        this.telemetryRebufferStartedAt = Date.now();
        this.telemetryRebufferTotal += 1;
      }
      this.startStallTimer();
      this.telemetry?.event('waiting');
      this.emit({ event: 'buffering' });
    } else {
      if (this.telemetryRebufferStartedAt) {
        this.telemetryRebufferDuration +=
          Date.now() - this.telemetryRebufferStartedAt;
        this.telemetryRebufferStartedAt = 0;
      }
      this.clearStallTimer();
      if (!this.state.paused) {
        this.telemetry?.onPlaying();
        this.emit({ event: 'playing' });
      }
    }
  };

  private handlePlaybackStateChanged = (data: OnPlaybackStateChangedData) => {
    if (data.isPlaying) {
      if (!this.telemetryFirstPlayAt) {
        this.telemetryFirstPlayAt = Date.now();
      }
      if (!this.telemetryFirstFrameTime) {
        this.telemetryFirstFrameTime = Math.max(
          1,
          Date.now() - this.telemetryFirstPlayAt
        );
      }
      this.clearPauseDetectTimer();
      if (this.state.paused) {
        this.setState({ paused: false });
        this.telemetry?.onPlay();
        this.emit({ event: 'play' });
      }
      this.telemetry?.onPlaying();
      this.emit({ event: 'playing' });
      this.maybeStartPrerollAdTimer();
      return;
    }
    // inAdBreak: IMA pausa o conteúdo para tocar o ad; ecoar esse pause na
    // prop paused faria o RNV pausar o próprio adsManager antes do STARTED.
    if (
      this.state.paused ||
      data.isSeeking ||
      this.inAdBreak ||
      this.sourceSwapPending
    ) {
      return;
    }
    if (
      (Platform.OS === 'ios' &&
        (this.inPiP || AppState.currentState !== 'active')) ||
      (Platform.OS === 'android' && this.inPiP)
    ) {
      return;
    }
    // `paused` alimenta a prop do <Video>, então espelhar um stall aqui pausaria
    // o player de verdade e ele nunca retomaria sozinho. Só um pause real (ex.:
    // controles nativos), confirmado pela ausência de buffering, é espelhado.
    this.clearPauseDetectTimer();
    this.pauseDetectTimer = setTimeout(() => {
      this.pauseDetectTimer = null;
      if (this.unmounted || this.buffering || this.state.paused) {
        return;
      }
      this.setState({ paused: true });
      this.telemetry?.onPause();
      this.emit({ event: 'pause' });
    }, PAUSE_DETECT_DELAY_MS);
  };

  private handleEnd = () => {
    this.videoEnded = true;
    this.setState({ paused: true });
    this.telemetry?.onEnded();
    this.emit({ event: 'ended' });
  };

  private handleError = (err: OnVideoErrorData) => {
    this.sourceSwapPending = false;
    const message =
      err?.error?.errorString || err?.error?.error || 'Playback error';
    const code = String(err?.error?.code ?? err?.error?.errorCode ?? 'unknown');
    // ExoPlayer already recovers from this one (seekToDefaultPosition +
    // prepare) but reports it first; switching CDN on top only reloads the
    // stream and flashes the poster.
    if (code === BEHIND_LIVE_WINDOW_CODE) {
      this.resetLiveEdge();
      this.telemetry?.errorEvent('erro_playback', code, message);
      return;
    }
    // Only reachable on an Android build without the bundled patch.
    if (code === 'DAI_ADS_LOADER_NULL_ERROR') {
      this.reportIntegration(takeStaleBuildWarning(code));
    }
    // Two-phase plans use the direct CDN stream only as a base to render the
    // CSAI pre-roll over; when it can't load (a DAI-only live has no standalone
    // CDN playlist and 404s on every CDN) skip straight to the DAI stream
    // instead of looping failover forever.
    if (this.state.adPhase === 'preroll' && this.isTwoPhaseAdPlan()) {
      this.telemetry?.errorEvent('erro_playback', code, message);
      this.advanceToDaiPhase();
      return;
    }
    // A DAI stream request failure isn't a CDN fault: drop the ad and play the
    // ad-free CDN stream (the DAI fallbackUri) instead of a black screen. Both
    // the native DAI_REQUEST_ERROR and any error raised while the DAI source is
    // still the active ad route funnel here.
    if (
      code === 'DAI_REQUEST_ERROR' ||
      (this.state.includeAdInSource &&
        this.getAdConfigForRender()?.type === 'ssai')
    ) {
      this.fallbackFromAds(code);
      return;
    }
    this.telemetry?.errorEvent('erro_playback', code, message);
    if (this.tryFailoverForError(code)) {
      // Recoverable: a CDN switch is queued, skip the error UI/event.
      return;
    }
    this.setState({ errorMessage: message });
    this.emit({ event: 'error', message, error: message, canRetry: true });
  };

  private handlePlaybackRateChange = (data: OnPlaybackRateChangeData) => {
    const rate = data.playbackRate;
    // 0 é pausa. Qualquer outra taxa diferente da desejada é transitória (o
    // AVPlayer oscila ao rebufferizar); emiti-la realimenta a prop controlada
    // do app e vira um laço que satura a ponte e trava o playback.
    if (rate === 0 || rate !== this.effectivePlaybackRate()) {
      return;
    }
    if (rate === this.lastEmittedRate) {
      return;
    }
    this.lastEmittedRate = rate;
    this.emit({ event: 'playbackRateSelected', rate: rate as any });
  };

  private handlePipStatusChanged = (data: { isActive: boolean }) => {
    this.inPiP = data.isActive;
    this.setState({ pip: data.isActive });
    this.clearPipExitPauseTimer();
    this.clearPauseDetectTimer();
    if (data.isActive) {
      if (this.state.paused) {
        this.setState({ paused: false });
      }
    }
    if (!data.isActive) {
      this.pipAspectRefreshPending = false;
      this.schedulePipExitPause();
    }
    this.emit({ event: data.isActive ? 'enterPiP' : 'exitPiP' });
    if (Platform.OS === 'android') {
      // legacy Android event kept for backwards compatibility
      this.emit({
        event: 'pipModeChanged',
        isInPictureInPictureMode: data.isActive,
      });
    }
  };

  // After the PiP window is dismissed with the X, nothing natively stops the
  // player: on Android enterPictureInPictureOnLeave makes the native side skip
  // the pause on host pause, and on iOS the fork's exit handler only handles
  // playInBackground — where it even resumes — so without this mirror the
  // audio keeps running in the background. Expanding the window reports the
  // same status change, and the 'active' AppState event that distinguishes it
  // is delivered asynchronously: on a busy JS thread it can land after this
  // pause fired, which used to pause the video right after the user expanded
  // it back (and for good, since the platform-side resume had already run).
  // settlePipExitPause() covers both directions of that race.
  private schedulePipExitPause() {
    if (this.props.playInBackground) {
      return;
    }
    this.pipExitPauseTimer = setTimeout(() => {
      this.pipExitPauseTimer = null;
      if (this.unmounted || this.inPiP || this.state.paused) {
        return;
      }
      // Expanding PiP back to fullscreen reports the same status change; by now
      // the app has returned to the foreground on both platforms.
      if (AppState.currentState === 'active') {
        return;
      }
      this.pipDismissalPausedAtMs = Date.now();
      this.pause();
    }, PIP_EXIT_PAUSE_DELAY_MS);
  }

  // Runs when the app turns active. Cancels a dismissal pause that has not
  // fired yet, and resumes one that fired moments before this event — the
  // late 'active' means the user expanded the window, not that they reopened
  // the app after dismissing it. Past the window the dismissal pause stands.
  private settlePipExitPause() {
    this.clearPipExitPauseTimer();
    if (!this.pipDismissalPausedAtMs) {
      return;
    }
    const raced =
      Date.now() - this.pipDismissalPausedAtMs <= PIP_EXIT_RESUME_WINDOW_MS;
    this.pipDismissalPausedAtMs = 0;
    if (raced && !this.inPiP && this.state.paused && !this.state.casting) {
      this.play();
    }
  }

  private clearPipExitPauseTimer() {
    if (this.pipExitPauseTimer) {
      clearTimeout(this.pipExitPauseTimer);
      this.pipExitPauseTimer = null;
    }
  }

  private handleReceiveAdEvent = (event: OnReceiveAdEventData) => {
    // Emitido antes do switch para que nenhuma heurística abaixo (repetição de
    // pre-roll, fallback) esconda um evento do integrador.
    if (event.event) {
      this.emit({ event: 'adEvent', name: event.event, data: event.data });
    }
    if (this.inAdBreak && AD_LIVENESS_EVENTS.has(event.event ?? '')) {
      this.armAdBreakTimer();
    }
    switch (event.event) {
      case 'LOADED':
        // iOS CSAI: o IMA pausa o conteúdo logo após LOADED sem emitir
        // CONTENT_PAUSE_REQUESTED; marcar o break já aqui evita ecoar o pause.
        // Android não pode depender disso: um LOADED tardio (prefetch do
        // próximo break do VMAP, retomada do IMA) abriria um break fantasma
        // sobre o conteúdo tocando — o ad_break_stalled derrubaria 30s depois
        // uma fonte que está boa.
        if (
          Platform.OS === 'ios' &&
          this.getAdConfigForRender()?.type === 'csai'
        ) {
          if (!this.noteAdBreakStart()) {
            break;
          }
        }
        this.emitMetadataIfPending();
        break;
      case 'AD_BREAK_STARTED':
      case 'AD_PERIOD_STARTED':
      case 'CONTENT_PAUSE_REQUESTED': {
        // The break-opening event can arrive twice for the same DAI pod (see
        // noteAdBreakStart); adBreakBegin belongs to the first one only.
        const freshBreak = !this.inAdBreak;
        // Ads legitimately stall content; suspend the failover monitors.
        if (!this.noteAdBreakStart()) {
          break;
        }
        this.clearPrerollAdTimer();
        // A DAI ad break means the stream loaded; the watchdog can stand down.
        this.clearAdWatchdog();
        // The ad period began (CONTENT_PAUSE_REQUESTED alone does not say
        // that): from here the ticks report the ad timeline, so the fallback
        // resume must use the pre-break position (see adStartedInBreak).
        if (event.event !== 'CONTENT_PAUSE_REQUESTED') {
          this.adStartedInBreak = true;
        }
        this.emitMetadataIfPending();
        if (freshBreak) {
          this.emit({ event: 'adBreakBegin' });
        }
        break;
      }
      case 'STARTED':
        this.clearPrerollAdTimer();
        this.clearAdWatchdog();
        this.adStartedInBreak = true;
        this.telemetry?.event('ad_iniciou');
        this.emit({ event: 'adBegin' });
        break;
      case 'COMPLETED':
      case 'SKIPPED':
        this.telemetry?.event('ad_terminou');
        this.emit({ event: 'adEnd' });
        break;
      case 'AD_BREAK_ENDED':
      case 'AD_PERIOD_ENDED':
      case 'ALL_ADS_COMPLETED':
      case 'CONTENT_RESUME_REQUESTED':
        this.inAdBreak = false;
        this.adBreakCompleted = true;
        this.clearAdBreakTimer();
        this.emit({ event: 'adBreakEnd' });
        this.advanceToDaiPhase();
        // The break is over but a CSAI content stream may still never arrive.
        this.armAdWatchdog();
        break;
      case 'ERROR': {
        // extras carregam os campos de erro sem disparar initerror: um ad
        // com falha não impede o conteúdo de tocar.
        const details = (event.data ?? {}) as {
          message?: string;
          code?: number | string;
        };
        const message = details.message || 'Ad playback error';
        this.telemetry?.keyEvent('erro_ad', {
          player_error_code:
            details.code != null ? `ad_error_${details.code}` : 'ad_error',
          player_error_message: message,
        });
        this.inAdBreak = false;
        this.adBreakCompleted = true;
        this.clearAdBreakTimer();
        this.emit({
          event: 'adError',
          error: `${details.code ?? 'ad_error'}: ${message}`,
          data: event.data,
        });
        this.emit({ event: 'adBreakEnd' });
        this.advanceToDaiPhase();
        this.armAdWatchdog();
        break;
      }
    }
  };

  render() {
    const {
      style,
      children,
      hideUI,
      muted,
      pipEnabled,
      aspectRatio,
      subtitleAppearance,
    } = this.props;
    const {
      config,
      loading,
      errorMessage,
      paused,
      casting,
      castDeviceName,
      posterVisible,
      fullscreen,
      pip,
    } = this.state;

    const adConfig = this.getAdConfigForRender();
    const source = this.getSourceForRender(adConfig);
    const { width, height } = Dimensions.get('window');
    // PiP renders the caption in a tiny window; a custom size there would
    // either be unreadable or overflow it, so it always uses the SDK default.
    const effectiveSubtitleAppearance = pip ? undefined : subtitleAppearance;
    // Entering PiP from the native fullscreen player does not always fire
    // onFullscreenPlayerWillDismiss, so `fullscreen` can still read true while
    // in PiP; without this guard the tiny window would keep the fullscreen
    // (screen-relative) caption size instead of the plain default.
    const effectiveFullscreen = fullscreen && !pip;
    const verticalSubtitleStyle = resolveSubtitleSize(
      VERTICAL_SUBTITLE_FONT_SIZE,
      effectiveSubtitleAppearance
    );
    const fullscreenSubtitleStyle = effectiveFullscreen
      ? resolveSubtitleSize(fullscreenSubtitleFontSize(width, height), {
          fontSize: effectiveSubtitleAppearance?.fullscreen?.fontSize,
          bottomPaddingRatio:
            effectiveSubtitleAppearance?.fullscreen?.bottomPaddingRatio ??
            effectiveSubtitleAppearance?.bottomPaddingRatio,
          bottomPadding:
            effectiveSubtitleAppearance?.fullscreen?.bottomPadding ??
            effectiveSubtitleAppearance?.bottomPadding,
        })
      : undefined;
    const verticalContent = config ? isVerticalVideo(config) : false;
    // resizeMode 'cover' zooms the video to fill the screen, which crops the
    // frame the native caption size is computed from; the ExoPlayer/AVPlayer
    // default then renders too small relative to what's actually on screen.
    const coverFit = aspectRatio === 'aspectFill';

    const thumbnailUrl = config && posterVisible ? getThumbnailUrl(config) : '';
    const endBannerUrl = config?.lm_live_terminada
      ? getBannerFimUrl(config)
      : '';

    // Native controls freezing with ads/LL-HLS was a react-native-video bug
    // (overlay KVO vs react-native-screens safe area), fixed by the vendored
    // yarn patch on RCTVideo.handleViewControllerOverlayViewFrameChange.
    const nativeControls = !(hideUI ?? false);

    return (
      <View style={[styles.container, style]}>
        {source ? (
          <Video
            ref={this.videoRef}
            source={source}
            style={StyleSheet.absoluteFill}
            controls={nativeControls}
            resizeMode={RESIZE_MODES[aspectRatio ?? 'fit'] ?? 'contain'}
            paused={paused || casting}
            muted={muted ?? false}
            rate={this.effectivePlaybackRate()}
            poster={thumbnailUrl || undefined}
            posterResizeMode="cover"
            selectedTextTrack={this.resolveSelectedTextTrack()}
            subtitleStyle={
              pip
                ? DEFAULT_PIP_SUBTITLE_STYLE
                : verticalContent && !effectiveFullscreen
                  ? verticalSubtitleStyle
                  : effectiveFullscreen && (verticalContent || coverFit)
                    ? fullscreenSubtitleStyle
                    : undefined
            }
            selectedAudioTrack={this.resolveSelectedAudioTrack()}
            selectedVideoTrack={this.resolveSelectedVideoTrack()}
            maxBitRate={this.resolveMaxBitRate()}
            reportBandwidth={true}
            playInBackground={this.props.playInBackground ?? false}
            playWhenInactive={Platform.OS === 'ios'}
            enterPictureInPictureOnLeave={pipEnabled ?? false}
            onLoad={this.handleLoad}
            onProgress={this.handleProgress}
            onSeek={this.handleSeek}
            onBuffer={this.handleBuffer}
            onBandwidthUpdate={this.handleBandwidthUpdate}
            onPlaybackStateChanged={this.handlePlaybackStateChanged}
            onPlaybackRateChange={this.handlePlaybackRateChange}
            onEnd={this.handleEnd}
            onError={this.handleError}
            onTextTracks={this.handleTextTracks}
            onAudioTracks={this.handleAudioTracks}
            onVideoTracks={this.handleVideoTracks}
            onReceiveAdEvent={this.handleReceiveAdEvent}
            onFullscreenPlayerWillPresent={() => {
              this.fullscreen = true;
              this.setState({ fullscreen: true });
              this.telemetry?.event('fullscreenchange', { fullscreen: true });
              this.emit({ event: 'enterFullScreen' });
            }}
            onFullscreenPlayerWillDismiss={() => {
              this.fullscreen = false;
              this.setState({ fullscreen: false });
              this.telemetry?.event('fullscreenchange', { fullscreen: false });
              this.emit({ event: 'exitFullScreen' });
            }}
            onPictureInPictureStatusChanged={this.handlePipStatusChanged}
            onRestoreUserInterfaceForPictureInPictureStop={() => {
              this.videoRef.current?.restoreUserInterfaceForPictureInPictureStopCompleted(
                true
              );
            }}
          />
        ) : null}

        {loading && !hideUI ? (
          <View style={styles.overlayCentered} pointerEvents="none">
            <ActivityIndicator size="large" color="#fff" />
          </View>
        ) : null}

        {errorMessage && !hideUI ? (
          <View style={styles.overlayCentered} pointerEvents="none">
            <Text style={styles.errorText}>{errorMessage}</Text>
          </View>
        ) : null}

        {endBannerUrl ? (
          <View style={styles.overlayCentered} pointerEvents="none">
            <Image source={{ uri: endBannerUrl }} style={styles.endBanner} />
          </View>
        ) : null}

        {this.state.overlaySubtitleText ? (
          <View style={styles.subtitleOverlay} pointerEvents="none">
            <Text
              style={[
                styles.subtitleText,
                {
                  fontSize: effectiveFullscreen
                    ? fullscreenSubtitleStyle?.fontSize
                    : verticalSubtitleStyle.fontSize,
                },
              ]}
            >
              {this.state.overlaySubtitleText}
            </Text>
          </View>
        ) : null}

        {Platform.OS === 'ios' && nativeControls && pipEnabled && source ? (
          <Pressable
            accessibilityLabel="Picture in Picture"
            accessibilityRole="button"
            onPress={this.enterPiP}
            style={styles.pipButton}
          >
            <Text style={styles.pipButtonText}>PiP</Text>
          </Pressable>
        ) : null}

        {casting ? (
          <View style={styles.castOverlay}>
            {thumbnailUrl ? (
              <Image
                source={{ uri: thumbnailUrl }}
                style={styles.castBackdrop}
                resizeMode="cover"
              />
            ) : null}
            <View style={styles.castScrim} />
            <View style={styles.castInfoRow}>
              <CastButton tintColor="#fff" style={styles.castOverlayButton} />
              <Text style={styles.castText}>
                {castDeviceName
                  ? `Reproduzindo em ${castDeviceName}`
                  : 'Reproduzindo no Chromecast'}
              </Text>
            </View>
          </View>
        ) : null}

        {children ? (
          <View style={StyleSheet.absoluteFill} pointerEvents="box-none">
            {children}
          </View>
        ) : null}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#000',
    overflow: 'hidden',
  },
  overlayCentered: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorText: {
    color: '#fff',
    fontSize: 14,
    textAlign: 'center',
    paddingHorizontal: 16,
  },
  endBanner: {
    width: '100%',
    height: '100%',
    position: 'absolute',
  },
  subtitleOverlay: {
    position: 'absolute',
    left: 16,
    right: 16,
    // clears the example's custom control bar without hugging mid-screen
    bottom: 84,
    alignItems: 'center',
  },
  subtitleText: {
    color: '#fff',
    fontSize: 16,
    textAlign: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
    overflow: 'hidden',
  },
  pipButton: {
    position: 'absolute',
    top: 12,
    right: 12,
    minWidth: 44,
    height: 32,
    paddingHorizontal: 10,
    borderRadius: 4,
    backgroundColor: 'rgba(0, 0, 0, 0.72)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  pipButtonText: {
    color: '#fff',
    fontSize: 13,
    fontWeight: '600',
  },
  castOverlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: '#000',
    justifyContent: 'center',
    alignItems: 'center',
  },
  castBackdrop: {
    ...StyleSheet.absoluteFillObject,
  },
  castScrim: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
  },
  castInfoRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  castOverlayButton: {
    width: 28,
    height: 28,
  },
  castText: {
    color: 'rgba(255, 255, 255, 0.85)',
    fontSize: 16,
    fontWeight: '600',
  },
});
