'use client';

import React, { useEffect, useRef, useState, useCallback } from 'react';
import {
  PlaybackIntervalSample,
  SessionStatus,
  ContentInterval,
  mergeContentIntervals,
} from '@/lib/tracking-engine';
import {
  Clock,
  Eye,
  Pause,
  VolumeX,
  CheckCircle2,
  Video,
  Activity,
  Layers,
  AlertCircle,
} from 'lucide-react';

declare global {
  interface Window {
    onYouTubeIframeAPIReady?: () => void;
    YT?: {
      Player: new (
        elementId: string | HTMLElement,
        options: {
          videoId: string;
          playerVars?: Record<string, unknown>;
          events?: {
            onReady?: (event: { target: YTPlayerInstance }) => void;
            onStateChange?: (event: { data: number; target: YTPlayerInstance }) => void;
            onPlaybackRateChange?: (event: { data: number; target: YTPlayerInstance }) => void;
            onError?: (event: { data: number }) => void;
          };
        }
      ) => YTPlayerInstance;
      PlayerState: {
        UNSTARTED: number;
        ENDED: number;
        PLAYING: number;
        PAUSED: number;
        BUFFERING: number;
        CUED: number;
      };
    };
  }
}

interface YTPlayerInstance {
  playVideo: () => void;
  pauseVideo: () => void;
  getCurrentTime: () => number;
  getDuration: () => number;
  getPlaybackRate: () => number;
  getPlayerState: () => number;
  isMuted: () => boolean;
  getVolume: () => number;
  destroy: () => void;
}

interface YouTubeTrackerProps {
  token: string;
  sessionId: string;
  videoId: string;
  videoTitle: string;
  // Initial session metrics (from server on page load)
  initialTotalWatchSeconds?: number;
  initialForegroundWatchSeconds?: number;
  initialPauseSeconds?: number;
  initialTabInactiveSeconds?: number;
  initialMutedSeconds?: number;
  initialContentWatchedSeconds?: number;
  initialContentIntervals?: ContentInterval[];
}

function formatDuration(totalSeconds: number): string {
  const sec = Math.max(0, Math.round(totalSeconds));
  const hrs = Math.floor(sec / 3600);
  const mins = Math.floor((sec % 3600) / 60);
  const remSec = sec % 60;
  if (hrs > 0) {
    return `${hrs}:${String(mins).padStart(2, '0')}:${String(remSec).padStart(2, '0')}`;
  }
  return `${mins}:${String(remSec).padStart(2, '0')}`;
}

export function YouTubeTracker({
  token,
  sessionId,
  videoId,
  videoTitle,
  initialTotalWatchSeconds = 0,
  initialForegroundWatchSeconds = 0,
  initialPauseSeconds = 0,
  initialTabInactiveSeconds = 0,
  initialMutedSeconds = 0,
  initialContentWatchedSeconds = 0,
  initialContentIntervals = [],
}: YouTubeTrackerProps) {
  const playerContainerRef = useRef<HTMLDivElement>(null);
  const playerRef = useRef<YTPlayerInstance | null>(null);

  // Error & authorization states
  const [playerError, setPlayerError] = useState<string | null>(null);
  const [isRevoked, setIsRevoked] = useState<boolean>(false);

  // ─── DISPLAY STATE ───────────────────────────────────────────────────────────
  // These are what the UI renders. They start from initial session values (page
  // load) and ONLY ever increase — server responses never decrease them.
  const [displayTotalWatch, setDisplayTotalWatch] = useState<number>(initialTotalWatchSeconds);
  const [displayForegroundWatch, setDisplayForegroundWatch] = useState<number>(initialForegroundWatchSeconds);
  const [displayPause, setDisplayPause] = useState<number>(initialPauseSeconds);
  const [displayTabInactive, setDisplayTabInactive] = useState<number>(initialTabInactiveSeconds);
  const [displayMuted, setDisplayMuted] = useState<number>(initialMutedSeconds);
  const [displayContentWatched, setDisplayContentWatched] = useState<number>(initialContentWatchedSeconds);
  const [displayDuration, setDisplayDuration] = useState<number>(0);
  const [currentStatus, setCurrentStatus] = useState<SessionStatus>('Not Started');

  // ─── SERVER CHECKPOINT REFS ──────────────────────────────────────────────────
  // The last server-confirmed values. ONLY updated when server confirms values
  // that are >= current display (monotonically increasing rule).
  const serverTotalRef = useRef<number>(initialTotalWatchSeconds);
  const serverForegroundRef = useRef<number>(initialForegroundWatchSeconds);
  const serverPauseRef = useRef<number>(initialPauseSeconds);
  const serverTabInactiveRef = useRef<number>(initialTabInactiveSeconds);
  const serverMutedRef = useRef<number>(initialMutedSeconds);
  const serverContentWatchedRef = useRef<number>(initialContentWatchedSeconds);

  // Last acknowledged heartbeat sequence (prevents stale responses overwriting newer state)
  const lastAcknowledgedSeqRef = useRef<number>(0);

  // ─── LOCAL ACCUMULATOR REFS ──────────────────────────────────────────────────
  // Tracks time accumulated SINCE the last server checkpoint (using performance.now)
  const localWatchAccRef = useRef<number>(0);       // seconds since checkpoint
  const localFgAccRef = useRef<number>(0);
  const localPauseAccRef = useRef<number>(0);
  const localTabAccRef = useRef<number>(0);
  const localMutedAccRef = useRef<number>(0);
  const contentIntervalsRef = useRef<ContentInterval[]>(initialContentIntervals);

  // ─── PLAYBACK STATE REFS ─────────────────────────────────────────────────────
  const sequenceNumberRef = useRef<number>(1);
  const lastSampleTimeRef = useRef<number>(Date.now());
  const lastSamplePosRef = useRef<number>(0);
  const pendingIntervalsRef = useRef<PlaybackIntervalSample[]>([]);
  const isFlushingRef = useRef<boolean>(false);
  const lastFlushTimeRef = useRef<number>(Date.now());
  const isRevoked_ref = useRef<boolean>(false);
  const playbackRateRef = useRef<number>(1);
  const durationRef = useRef<number>(0);

  // ─── HELPERS ─────────────────────────────────────────────────────────────────
  // Applies a server response — only updates display if server value is HIGHER
  // than what we're currently showing. Prevents backward jumps.
  const applyServerResponse = useCallback((data: {
    totalWatchSeconds?: number;
    foregroundWatchSeconds?: number;
    pauseSeconds?: number;
    tabInactiveSeconds?: number;
    mutedSeconds?: number;
    contentWatchedSeconds?: number;
  }, respondingToSeq: number) => {
    // Ignore if a newer response has already been applied
    if (respondingToSeq <= lastAcknowledgedSeqRef.current) return;
    lastAcknowledgedSeqRef.current = respondingToSeq;

    // For each metric: if server confirms a higher value, adopt it as new checkpoint
    // and reset the local accumulator (the extra was already counted server-side)
    if (typeof data.totalWatchSeconds === 'number' && data.totalWatchSeconds > serverTotalRef.current) {
      const delta = data.totalWatchSeconds - serverTotalRef.current;
      serverTotalRef.current = data.totalWatchSeconds;
      // Reduce local accumulator by what server has now confirmed
      localWatchAccRef.current = Math.max(0, localWatchAccRef.current - delta);
      setDisplayTotalWatch((prev) => Math.max(prev, data.totalWatchSeconds!));
    }
    if (typeof data.foregroundWatchSeconds === 'number' && data.foregroundWatchSeconds > serverForegroundRef.current) {
      const delta = data.foregroundWatchSeconds - serverForegroundRef.current;
      serverForegroundRef.current = data.foregroundWatchSeconds;
      localFgAccRef.current = Math.max(0, localFgAccRef.current - delta);
      setDisplayForegroundWatch((prev) => Math.max(prev, data.foregroundWatchSeconds!));
    }
    if (typeof data.pauseSeconds === 'number' && data.pauseSeconds > serverPauseRef.current) {
      const delta = data.pauseSeconds - serverPauseRef.current;
      serverPauseRef.current = data.pauseSeconds;
      localPauseAccRef.current = Math.max(0, localPauseAccRef.current - delta);
      setDisplayPause((prev) => Math.max(prev, data.pauseSeconds!));
    }
    if (typeof data.tabInactiveSeconds === 'number' && data.tabInactiveSeconds > serverTabInactiveRef.current) {
      const delta = data.tabInactiveSeconds - serverTabInactiveRef.current;
      serverTabInactiveRef.current = data.tabInactiveSeconds;
      localTabAccRef.current = Math.max(0, localTabAccRef.current - delta);
      setDisplayTabInactive((prev) => Math.max(prev, data.tabInactiveSeconds!));
    }
    if (typeof data.mutedSeconds === 'number' && data.mutedSeconds > serverMutedRef.current) {
      const delta = data.mutedSeconds - serverMutedRef.current;
      serverMutedRef.current = data.mutedSeconds;
      localMutedAccRef.current = Math.max(0, localMutedAccRef.current - delta);
      setDisplayMuted((prev) => Math.max(prev, data.mutedSeconds!));
    }
    if (typeof data.contentWatchedSeconds === 'number' && data.contentWatchedSeconds > serverContentWatchedRef.current) {
      serverContentWatchedRef.current = data.contentWatchedSeconds;
      setDisplayContentWatched((prev) => Math.max(prev, data.contentWatchedSeconds!));
    }
  }, []);

  // ─── HEARTBEAT FLUSH ─────────────────────────────────────────────────────────
  // Captured in a ref so the sampling interval never needs to be recreated
  const flushRef = useRef<(eventType?: string, useBeacon?: boolean) => Promise<void>>(async () => {});

  useEffect(() => {
    flushRef.current = async (eventType = 'batch_intervals', useBeacon = false) => {
      if (isRevoked_ref.current || isFlushingRef.current) return;

      const intervalsToFlush = [...pendingIntervalsRef.current];
      if (intervalsToFlush.length === 0 && eventType === 'batch_intervals') return;

      isFlushingRef.current = true;
      const seq = sequenceNumberRef.current++;
      const currentPos = playerRef.current?.getCurrentTime() || lastSamplePosRef.current || 0;
      const currentDur = playerRef.current?.getDuration() || durationRef.current || 0;

      const payload = {
        token,
        sessionId,
        sequence_number: seq,
        event_type: eventType,
        position_seconds: Math.round(currentPos * 10) / 10,
        playback_rate: playbackRateRef.current,
        client_timestamp: Date.now(),
        duration_seconds: Math.round(currentDur),
        intervals: intervalsToFlush,
      };

      const basePath = process.env.NEXT_PUBLIC_BASE_PATH || '';
      const heartbeatUrl = `${basePath}/api/watch/heartbeat`;

      if (useBeacon && typeof navigator !== 'undefined' && navigator.sendBeacon) {
        const blob = new Blob([JSON.stringify(payload)], { type: 'application/json' });
        navigator.sendBeacon(heartbeatUrl, blob);
        pendingIntervalsRef.current = [];
        isFlushingRef.current = false;
        return;
      }

      try {
        const res = await fetch(heartbeatUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload),
          keepalive: true,
        });

        if (res.status === 403) {
          isRevoked_ref.current = true;
          setIsRevoked(true);
          playerRef.current?.pauseVideo();
          return;
        }

        if (res.ok) {
          pendingIntervalsRef.current = pendingIntervalsRef.current.slice(intervalsToFlush.length);
          lastFlushTimeRef.current = Date.now();
          const data = await res.json();
          // Apply server response — will only update display if values are higher
          applyServerResponse(data, seq);
        }
      } catch (err) {
        // Retained in buffer for next flush attempt
        console.warn('Heartbeat flush deferred:', err);
      } finally {
        isFlushingRef.current = false;
      }
    };
  }, [token, sessionId, applyServerResponse]);

  // ─── YOUTUBE PLAYER INIT ─────────────────────────────────────────────────────
  useEffect(() => {
    let isCancelled = false;

    function initPlayer() {
      if (isCancelled || !playerContainerRef.current || !window.YT || !window.YT.Player) return;

      try {
        playerRef.current = new window.YT.Player(playerContainerRef.current, {
          videoId,
          playerVars: {
            autoplay: 0,
            controls: 1,
            rel: 0,
            modestbranding: 1,
            playsinline: 1,
            origin: typeof window !== 'undefined' ? window.location.origin : '',
          },
          events: {
            onReady: (event) => {
              if (isCancelled) return;
              try {
                const dur = event.target.getDuration();
                if (dur > 0) {
                  durationRef.current = dur;
                  setDisplayDuration(dur);
                }
                playbackRateRef.current = event.target.getPlaybackRate() || 1;
              } catch { /* ignore */ }
            },
            onPlaybackRateChange: (event) => {
              playbackRateRef.current = event.data;
              flushRef.current('rate_change');
            },
            onStateChange: (event) => {
              const state = event.data;
              const target = event.target;
              try {
                const dur = target.getDuration ? target.getDuration() : 0;
                if (dur > 0) {
                  durationRef.current = dur;
                  setDisplayDuration(dur);
                }
              } catch { /* ignore */ }

              if (state === window.YT!.PlayerState.PLAYING) {
                setCurrentStatus(document.hidden ? 'Tab Inactive' : 'Watching');
                flushRef.current('play');
              } else if (state === window.YT!.PlayerState.PAUSED) {
                setCurrentStatus('Paused');
                flushRef.current('pause');
              } else if (state === window.YT!.PlayerState.BUFFERING) {
                setCurrentStatus('Buffering');
              } else if (state === window.YT!.PlayerState.ENDED) {
                setCurrentStatus('Completed');
                flushRef.current('ended');
              }
            },
            onError: (event) => {
              if (event.data === 101 || event.data === 150) {
                setPlayerError('The owner of this YouTube video has restricted playback in embedded players.');
              } else if (event.data === 100) {
                setPlayerError('The video has been removed or marked private by its creator.');
              } else {
                setPlayerError('An error occurred loading the YouTube video player.');
              }
            },
          },
        });
      } catch (e) {
        console.error('Failed to instantiate YouTube player:', e);
      }
    }

    if (!window.YT) {
      const existingScript = document.getElementById('youtube-iframe-api');
      if (!existingScript) {
        const tag = document.createElement('script');
        tag.id = 'youtube-iframe-api';
        tag.src = 'https://www.youtube.com/iframe_api';
        document.body.appendChild(tag);
      }
      window.onYouTubeIframeAPIReady = () => { initPlayer(); };
    } else {
      initPlayer();
    }

    return () => {
      isCancelled = true;
      if (playerRef.current) {
        try { playerRef.current.destroy(); } catch { /* ignore */ }
      }
    };
  }, [videoId]); // Only videoId — flushRef is stable

  // ─── 1-SECOND SAMPLING ENGINE ────────────────────────────────────────────────
  // This interval NEVER recreates — all callbacks are accessed via refs.
  useEffect(() => {
    lastSampleTimeRef.current = Date.now();
    lastFlushTimeRef.current = Date.now();

    const timer = setInterval(() => {
      const player = playerRef.current;
      if (!player || isRevoked_ref.current) return;

      const now = Date.now();
      const dt = (now - lastSampleTimeRef.current) / 1000;
      if (dt < 0.5) return; // Guard against spurious rapid calls

      let currentPos = 0;
      let dur = durationRef.current;
      let state = -1;
      let isMuted = false;
      let vol = 100;

      try {
        currentPos = player.getCurrentTime() || 0;
        const playerDur = player.getDuration();
        if (playerDur > 0) {
          dur = playerDur;
          durationRef.current = dur;
          setDisplayDuration(playerDur);
        }
        state = player.getPlayerState();
        isMuted = player.isMuted();
        vol = player.getVolume();
      } catch {
        return;
      }

      const tabHidden = typeof document !== 'undefined' && document.hidden;
      const isPlaying = state === 1;
      const isPaused = state === 2;
      const isBuffering = state === 3;
      const rate = playbackRateRef.current;

      // Update status
      if (isPlaying && !isBuffering) {
        setCurrentStatus(tabHidden ? 'Tab Inactive' : 'Watching');
      } else if (isPaused) {
        setCurrentStatus(tabHidden ? 'Tab Inactive' : 'Paused');
      } else if (isBuffering) {
        setCurrentStatus('Buffering');
      }

      const startPos = lastSamplePosRef.current;
      const posDelta = currentPos - startPos;

      // ── Accumulate local metrics ─────────────────────────────────────────────
      // Tab inactive
      if (tabHidden) {
        localTabAccRef.current += dt;
        setDisplayTabInactive(serverTabInactiveRef.current + localTabAccRef.current);
      }

      // Pause time
      if (isPaused && !isBuffering) {
        localPauseAccRef.current += dt;
        setDisplayPause(serverPauseRef.current + localPauseAccRef.current);
      }

      // Active playback — strict validation to prevent seek/buffer counting
      if (isPlaying && !isBuffering) {
        // posDelta must be in a reasonable range: 0 to (dt * rate + 1.5s tolerance)
        const maxExpectedDelta = dt * rate + 1.5;
        if (posDelta >= 0 && posDelta <= maxExpectedDelta) {
          // content slice: how much video content was consumed
          const contentSlice = posDelta;         // actual video seconds consumed
          // watch slice: real elapsed time (not speed-adjusted)
          const watchSlice = Math.min(dt, contentSlice / rate + 0.1);

          localWatchAccRef.current += watchSlice;
          setDisplayTotalWatch(serverTotalRef.current + localWatchAccRef.current);

          if (!tabHidden) {
            localFgAccRef.current += watchSlice;
            setDisplayForegroundWatch(serverForegroundRef.current + localFgAccRef.current);
          }

          if (isMuted || vol === 0) {
            localMutedAccRef.current += watchSlice;
            setDisplayMuted(serverMutedRef.current + localMutedAccRef.current);
          }

          if (currentPos > startPos) {
            const res = mergeContentIntervals(contentIntervalsRef.current, {
              start: startPos,
              end: currentPos,
            });
            contentIntervalsRef.current = res.merged;
            setDisplayContentWatched((prev) => Math.max(prev, res.totalSeconds));
          }
        }
        // If posDelta is out of range (seek detected), skip — don't count this interval
      }

      // ── Enqueue for server flush ─────────────────────────────────────────────
      pendingIntervalsRef.current.push({
        start_time: lastSampleTimeRef.current,
        end_time: now,
        start_pos: startPos,
        end_pos: currentPos,
        playback_rate: rate,
        is_playing: isPlaying,
        is_paused: isPaused,
        is_buffering: isBuffering,
        is_tab_hidden: tabHidden,
        is_muted: isMuted,
        volume: vol,
      });

      lastSampleTimeRef.current = now;
      lastSamplePosRef.current = currentPos;

      // Flush every ~5 seconds or when buffer has 8+ items
      if (now - lastFlushTimeRef.current >= 4800 || pendingIntervalsRef.current.length >= 8) {
        flushRef.current('batch_intervals');
      }
    }, 1000);

    return () => clearInterval(timer);
  }, []); // Empty deps — interval never recreates; all state accessed via refs

  // ─── TAB VISIBILITY ──────────────────────────────────────────────────────────
  useEffect(() => {
    const handleVisibility = () => {
      const hidden = typeof document !== 'undefined' && document.hidden;
      flushRef.current(hidden ? 'visibility_hidden' : 'visibility_visible');
    };
    document.addEventListener('visibilitychange', handleVisibility);
    return () => document.removeEventListener('visibilitychange', handleVisibility);
  }, []); // Empty deps — flushRef is stable

  // ─── SAFE UNLOAD ─────────────────────────────────────────────────────────────
  useEffect(() => {
    const handleUnload = () => { flushRef.current('pause', true); };
    window.addEventListener('beforeunload', handleUnload);
    window.addEventListener('pagehide', handleUnload);
    return () => {
      window.removeEventListener('beforeunload', handleUnload);
      window.removeEventListener('pagehide', handleUnload);
    };
  }, []); // Empty deps — flushRef is stable

  // ─── DERIVED DISPLAY VALUES ──────────────────────────────────────────────────
  if (isRevoked) {
    return (
      <div className="rounded-xl border border-red-200 bg-red-50 p-6 text-center text-red-800 shadow-sm">
        <h3 className="text-base font-bold mb-2">Access Revoked</h3>
        <p className="text-sm">
          This tracking link has been deactivated by the administrator. Playback is no longer permitted.
        </p>
      </div>
    );
  }

  const completionPercent = displayDuration > 0
    ? Math.min(100, Math.round((displayContentWatched / displayDuration) * 100))
    : 0;

  return (
    <div className="w-full">
      {playerError && (
        <div className="mb-4 rounded-xl border border-amber-200 bg-amber-50 p-4 text-amber-800 text-sm shadow-sm flex items-start space-x-2.5">
          <AlertCircle className="w-4 h-4 text-amber-600 flex-shrink-0 mt-0.5" />
          <div>
            <p className="font-semibold mb-0.5">Playback Restriction Notice</p>
            <p>{playerError}</p>
          </div>
        </div>
      )}

      {/* Two-column responsive layout: video left (~73%), panel right (~27%) */}
      <div className="flex flex-col lg:flex-row gap-5 items-start w-full">
        {/* Video Player — 73% on desktop, full width on mobile */}
        <div className="w-full lg:w-[73%] flex flex-col space-y-2">
          <div className="relative w-full aspect-video rounded-xl overflow-hidden shadow-md bg-black">
            <div ref={playerContainerRef} className="absolute inset-0 w-full h-full" />
          </div>

          <div className="flex items-center justify-between px-1 text-sm text-slate-500">
            <div className="flex items-center space-x-2">
              <span
                className={`inline-block w-2.5 h-2.5 rounded-full ${
                  currentStatus === 'Watching'
                    ? 'bg-emerald-500 animate-pulse'
                    : currentStatus === 'Paused'
                    ? 'bg-amber-400'
                    : currentStatus === 'Tab Inactive'
                    ? 'bg-indigo-400'
                    : 'bg-slate-300'
                }`}
              />
              <span className="font-semibold text-slate-700">Status: {currentStatus}</span>
            </div>
            <div className="text-xs font-mono text-slate-400">
              Synced every 5s
            </div>
          </div>
        </div>

        {/* Information Panel — 27% on desktop, full width on mobile */}
        <div className="w-full lg:w-[27%] bg-white rounded-xl border border-slate-200 shadow-sm p-4 space-y-4">
          <div className="border-b border-slate-100 pb-3 flex items-center justify-between">
            <h3 className="text-sm font-bold uppercase tracking-wider text-slate-900 flex items-center space-x-1.5">
              <Activity className="w-4 h-4 text-blue-600" />
              <span>Tracking Panel</span>
            </h3>
            <span
              className={`text-xs font-bold px-2 py-0.5 rounded-full ${
                currentStatus === 'Watching'
                  ? 'bg-emerald-50 text-emerald-700'
                  : currentStatus === 'Paused'
                  ? 'bg-amber-50 text-amber-700'
                  : currentStatus === 'Tab Inactive'
                  ? 'bg-indigo-50 text-indigo-700'
                  : 'bg-slate-100 text-slate-600'
              }`}
            >
              {currentStatus}
            </span>
          </div>

          {/* Video Information */}
          <div className="space-y-2">
            <div className="text-[11px] font-bold uppercase tracking-wider text-slate-400 flex items-center space-x-1">
              <Video className="w-3 h-3" />
              <span>Video Information</span>
            </div>

            <div className="grid grid-cols-2 gap-2">
              <div className="bg-slate-50 p-2.5 rounded-lg border border-slate-100">
                <div className="text-[11px] text-slate-500 font-medium">Total Duration</div>
                <div className="text-base font-bold text-slate-900 mt-0.5 tabular-nums">
                  {displayDuration > 0 ? formatDuration(displayDuration) : '—'}
                </div>
              </div>

              <div className="bg-slate-50 p-2.5 rounded-lg border border-slate-100">
                <div className="text-[11px] text-slate-500 font-medium">Content Watched</div>
                <div className="text-base font-bold text-slate-900 mt-0.5 tabular-nums">
                  {formatDuration(displayContentWatched)}
                </div>
              </div>
            </div>

            {/* Progress Bar */}
            <div className="space-y-1 pt-1">
              <div className="flex items-center justify-between text-xs">
                <span className="text-slate-500">Completion:</span>
                <span className="font-bold text-blue-700 tabular-nums">{completionPercent}%</span>
              </div>
              <div className="w-full bg-slate-100 h-2 rounded-full overflow-hidden">
                <div
                  className="bg-blue-600 h-full rounded-full transition-all duration-300"
                  style={{ width: `${completionPercent}%` }}
                />
              </div>
            </div>
          </div>

          {/* Watch Activity Breakdown */}
          <div className="space-y-2 pt-2 border-t border-slate-100">
            <div className="text-[11px] font-bold uppercase tracking-wider text-slate-400 flex items-center space-x-1">
              <Clock className="w-3 h-3" />
              <span>Watch Activity</span>
            </div>

            <div className="space-y-1.5">
              {/* Actual Watched Time — primary metric, highlighted */}
              <div className="flex items-center justify-between py-1.5 px-2.5 bg-blue-50/70 rounded-lg">
                <span className="text-sm font-semibold text-slate-700 flex items-center space-x-1.5">
                  <Activity className="w-3.5 h-3.5 text-blue-600" />
                  <span>Actual Watched:</span>
                </span>
                <span className="text-base font-bold text-blue-900 tabular-nums font-mono">
                  {formatDuration(displayTotalWatch)}
                </span>
              </div>

              {/* Foreground */}
              <div className="flex items-center justify-between py-1 px-2.5 text-slate-600">
                <span className="flex items-center space-x-1.5 text-sm text-slate-500">
                  <Eye className="w-3.5 h-3.5 text-slate-400" />
                  <span>Foreground:</span>
                </span>
                <span className="text-sm font-semibold text-slate-800 tabular-nums font-mono">
                  {formatDuration(displayForegroundWatch)}
                </span>
              </div>

              {/* Pause */}
              <div className="flex items-center justify-between py-1 px-2.5 text-slate-600">
                <span className="flex items-center space-x-1.5 text-sm text-slate-500">
                  <Pause className="w-3.5 h-3.5 text-slate-400" />
                  <span>Pause Time:</span>
                </span>
                <span className="text-sm font-semibold text-slate-800 tabular-nums font-mono">
                  {formatDuration(displayPause)}
                </span>
              </div>

              {/* Tab Inactive */}
              <div className="flex items-center justify-between py-1 px-2.5 text-slate-600">
                <span className="flex items-center space-x-1.5 text-sm text-slate-500">
                  <Layers className="w-3.5 h-3.5 text-slate-400" />
                  <span>Tab Inactive:</span>
                </span>
                <span className="text-sm font-semibold text-slate-800 tabular-nums font-mono">
                  {formatDuration(displayTabInactive)}
                </span>
              </div>

              {/* Muted */}
              <div className="flex items-center justify-between py-1 px-2.5 text-slate-600">
                <span className="flex items-center space-x-1.5 text-sm text-slate-500">
                  <VolumeX className="w-3.5 h-3.5 text-slate-400" />
                  <span>Muted Time:</span>
                </span>
                <span className="text-sm font-semibold text-slate-800 tabular-nums font-mono">
                  {formatDuration(displayMuted)}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
