<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { convertFileSrc } from "@tauri-apps/api/core";
import HighlightsPanel from "./HighlightsPanel.vue";
import type { TimestampedEvent, GameHistoryItem, HighlightClip, HighlightSettings } from "../types/timeline";
import {
  getGameResult,
  formatDuration,
  formatNumber,
  getChampionImageUrl,
  getQueueDisplayName,
  getChampionName,
  getQueueType,
  getQueueId,
  getItemImageUrl,
  getResultColor,
  getLpChange,
  formatLpDelta,
  formatRank,
  computeHighlights,
  DEFAULT_HIGHLIGHT_SETTINGS,
  getHighlightTypeColor,
  getGameVersion,
} from "../types/timeline";
import { getDdragonVersion } from "../types/ddragon";

// Props
const props = defineProps<{
  game: GameHistoryItem;
}>();

// Emits
const emit = defineEmits<{
  (e: "back"): void;
}>();

// DDragon version: use the game's recorded version if available, otherwise latest
const gameVersion = computed(() => getGameVersion(props.game) || getDdragonVersion());

// Video state
const videoRef = ref<HTMLVideoElement | null>(null);
const videoPath = ref<string | null>(null);
const videoError = ref<string | null>(null);
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const volume = ref(1);
const isMuted = ref(false);
const playbackRate = ref(1);

// Timeline state
const selectedEvent = ref<TimestampedEvent | null>(null);
const hoveredEvent = ref<TimestampedEvent | null>(null);

// Clip editing state
const clipStart = ref<number | null>(null);
const clipEnd = ref<number | null>(null);
const isExporting = ref(false);
const exportProgress = ref(0);
const exportMessage = ref<string | null>(null);

// Highlights mode state
const highlightsMode = ref(false);
const highlightSettings = ref<HighlightSettings>({ ...DEFAULT_HIGHLIGHT_SETTINGS });
const playingHighlightId = ref<number | null>(null);
const exportingHighlightId = ref<number | null>(null);

// Computed highlights from timeline events
const highlights = computed(() => {
  return computeHighlights(
    props.game.events,
    duration.value,
    localPlayer.value?.riotIdGameName || null,
    highlightSettings.value,
  );
});

// Handle highlight settings changes (re-compute is automatic via computed)
function onHighlightSettingsChanged(settings: HighlightSettings) {
  highlightSettings.value = { ...settings };
}

// Seek to a highlight clip
function seekToHighlight(time: number) {
  seekTo(time);
}

// Play a specific highlight clip
function playHighlightClip(clip: HighlightClip) {
  playingHighlightId.value = clip.id;
  seekTo(clip.start_time);
  if (videoRef.value) {
    videoRef.value.play();
  }
}

// Play all highlights sequentially
function playAllHighlights() {
  if (highlights.value.length === 0) return;
  playingHighlightId.value = highlights.value[0].id;
  seekTo(highlights.value[0].start_time);
  if (videoRef.value) {
    videoRef.value.play();
  }
}

// Export a single highlight clip
async function exportHighlightClip(clip: HighlightClip) {
  if (!videoPath.value) return;

  exportingHighlightId.value = clip.id;
  isExporting.value = true;
  exportMessage.value = "Exporting highlight...";

  try {
    const result = await invoke<string>("export_clip", {
      videoPath: videoPath.value,
      startTime: clip.start_time,
      endTime: clip.end_time,
      outputName: `highlight_${props.game.recording_id}_${clip.highlight_type}_${clip.id}`,
    });

    exportMessage.value = `Exported: ${result}`;
  } catch (error) {
    exportMessage.value = `Export failed: ${error}`;
  } finally {
    isExporting.value = false;
    exportingHighlightId.value = null;
  }
}

// Export all highlight clips
async function exportAllHighlights() {
  if (!videoPath.value || highlights.value.length === 0) return;

  isExporting.value = true;
  exportMessage.value = `Exporting ${highlights.value.length} highlights...`;

  let exported = 0;
  let failed = 0;

  for (const clip of highlights.value) {
    exportingHighlightId.value = clip.id;
    try {
      await invoke<string>("export_clip", {
        videoPath: videoPath.value,
        startTime: clip.start_time,
        endTime: clip.end_time,
        outputName: `highlight_${props.game.recording_id}_${clip.highlight_type}_${clip.id}`,
      });
      exported++;
    } catch {
      failed++;
    }
  }

  exportMessage.value = `Exported ${exported} highlights${failed > 0 ? ` (${failed} failed)` : ""}`;
  isExporting.value = false;
  exportingHighlightId.value = null;
}

// Watch video time to auto-advance through highlights
watch(() => currentTime.value, (time) => {
  if (playingHighlightId.value === null || !highlightsMode.value) return;

  const currentClip = highlights.value.find(h => h.id === playingHighlightId.value);
  if (!currentClip) return;

  // If we've passed the end of the current clip, jump to the next one
  if (time > currentClip.end_time + 0.5) {
    const currentIndex = highlights.value.findIndex(h => h.id === playingHighlightId.value);
    if (currentIndex < highlights.value.length - 1) {
      const nextClip = highlights.value[currentIndex + 1];
      playingHighlightId.value = nextClip.id;
      seekTo(nextClip.start_time);
    } else {
      // Last clip finished
      playingHighlightId.value = null;
      if (videoRef.value) {
        videoRef.value.pause();
      }
    }
  }
});

// Get video URL for playback using Tauri's convertFileSrc
const videoUrl = computed(() => {
  if (videoPath.value) {
    return convertFileSrc(videoPath.value);
  }
  return null;
});

// Events sorted by timestamp
const sortedEvents = computed(() => {
  return [...props.game.events]
    .filter(e => e.event_type !== "unknown")
    .sort((a, b) => {
      const aTime = a.video_timestamp[0] + a.video_timestamp[1] / 1e9;
      const bTime = b.video_timestamp[0] + b.video_timestamp[1] / 1e9;
      return aTime - bTime;
    });
});

// Get event position on timeline (0-100%)
function getEventPosition(event: TimestampedEvent): number {
  if (duration.value === 0) return 0;
  const time = event.video_timestamp[0] + event.video_timestamp[1] / 1e9;
  return (time / duration.value) * 100;
}

// Get event time in seconds
function getEventTime(event: TimestampedEvent): number {
  return event.video_timestamp[0] + event.video_timestamp[1] / 1e9;
}

// Format event time
function formatEventTime(event: TimestampedEvent): string {
  return formatDuration(getEventTime(event));
}

// Get event type color
function getEventColor(event: TimestampedEvent): string {
  switch (event.event_type) {
    case "game_end":
      return "#4ade80"; // green
    case "phase_change":
      return "#60a5fa"; // blue
    case "kill":
      return getKillEventColor(event);
    case "objective":
      return "#fbbf24"; // yellow
    case "lp_change":
      return "#a78bfa"; // purple
    default:
      return "#9ca3af"; // gray
  }
}

// Get kill event color based on player involvement
function getKillEventColor(event: TimestampedEvent): string {
  const rawData = event.raw_data as { KillerName?: string; VictimName?: string; Assisters?: string[] } | null;
  
  if (!rawData) return "#9ca3af"; // gray for unknown
  
  const killer = rawData.KillerName;
  const victim = rawData.VictimName;
  const assisters = rawData.Assisters || [];
  
  // Get local player's summoner name
  const localPlayerName = localPlayer.value?.riotIdGameName;
  
  if (!localPlayerName) {
    return "#9ca3af"; // gray if we can't determine local player
  }
  
  // Player got a kill
  if (killer === localPlayerName) {
    return "#4ade80"; // green for kills by player
  }
  
  // Player died
  if (victim === localPlayerName) {
    return "#ef4444"; // red for deaths (player was killed)
  }
  
  // Player assisted
  if (assisters.includes(localPlayerName)) {
    return "#a78bfa"; // purple for assists
  }
  
  // Player not involved
  return "#9ca3af"; // gray for neutral kills
}

// Player stats from end game data
interface PlayerData {
  puuid: string;
  championName: string;
  championId: number;
  riotIdGameName: string;
  riotIdTagLine: string;
  teamId: number;
  isLocalPlayer: boolean;
  stats: {
    kills: number;
    deaths: number;
    assists: number;
    goldEarned: number;
    totalDamageDealtToChampions: number;
    totalDamageTaken: number;
    minionsKilled: number;
    visionScore: number;
    level: number;
  };
  items: number[];
  spell1Id: number;
  spell2Id: number;
}

// Extract all players from end game stats
const allPlayers = computed((): PlayerData[] => {
  const stats = props.game.raw_end_game_stats as any;
  if (!stats?.teams) return [];
  
  const players: PlayerData[] = [];
  
  for (const team of stats.teams) {
    if (!team.players) continue;
    
    for (const player of team.players) {
      players.push({
        puuid: player.puuid || "",
        championName: player.championName || "Unknown",
        championId: player.championId || 0,
        riotIdGameName: player.riotIdGameName || "",
        riotIdTagLine: player.riotIdTagLine || "",
        teamId: player.teamId,
        isLocalPlayer: player.isLocalPlayer || false,
        stats: {
          kills: player.stats?.CHAMPIONS_KILLED || 0,
          deaths: player.stats?.NUM_DEATHS || 0,
          assists: player.stats?.ASSISTS || 0,
          goldEarned: player.stats?.GOLD_EARNED || 0,
          totalDamageDealtToChampions: player.stats?.TOTAL_DAMAGE_DEALT_TO_CHAMPIONS || 0,
          totalDamageTaken: player.stats?.TOTAL_DAMAGE_TAKEN || 0,
          minionsKilled: player.stats?.MINIONS_KILLED || 0,
          visionScore: player.stats?.VISION_SCORE || 0,
          level: player.stats?.LEVEL || 1,
        },
        items: player.items || [],
        spell1Id: player.spell1Id || 0,
        spell2Id: player.spell2Id || 0,
      });
    }
  }
  
  return players;
});

// Local player data
const localPlayer = computed(() => {
  return allPlayers.value.find(p => p.isLocalPlayer);
});

// Team players (local player's team)
const teamPlayers = computed(() => {
  const localTeamId = localPlayer.value?.teamId;
  return allPlayers.value.filter(p => p.teamId === localTeamId);
});

// Enemy players
const enemyPlayers = computed(() => {
  const localTeamId = localPlayer.value?.teamId;
  return allPlayers.value.filter(p => p.teamId !== localTeamId);
});

// Selected player is always the local player
const selectedPlayer = computed(() => localPlayer.value);

// Video controls
function togglePlay() {
  if (!videoRef.value) return;
  
  if (isPlaying.value) {
    videoRef.value.pause();
  } else {
    videoRef.value.play();
  }
}

function seekTo(time: number) {
  if (!videoRef.value) return;
  videoRef.value.currentTime = time;
  currentTime.value = time;
}

function seekToEvent(event: TimestampedEvent) {
  const time = getEventTime(event);
  seekTo(time);
  selectedEvent.value = event;
}

function seekRelative(delta: number) {
  if (!videoRef.value) return;
  const newTime = Math.max(0, Math.min(duration.value, currentTime.value + delta));
  seekTo(newTime);
}

function toggleMute() {
  if (!videoRef.value) return;
  isMuted.value = !isMuted.value;
  videoRef.value.muted = isMuted.value;
}

function setVolume(val: number) {
  if (!videoRef.value) return;
  volume.value = val;
  videoRef.value.volume = val;
}

function setPlaybackRate(rate: number) {
  if (!videoRef.value) return;
  playbackRate.value = rate;
  videoRef.value.playbackRate = rate;
}

function toggleFullscreen() {
  if (!videoRef.value) return;
  
  if (document.fullscreenElement) {
    document.exitFullscreen();
  } else {
    videoRef.value.requestFullscreen();
  }
}

// Timeline click handler
function onTimelineClick(event: MouseEvent) {
  const target = event.currentTarget as HTMLElement;
  const rect = target.getBoundingClientRect();
  const percent = (event.clientX - rect.left) / rect.width;
  const time = percent * duration.value;
  seekTo(time);
}

// Clip editing
function setClipStartPoint() {
  clipStart.value = currentTime.value;
  if (clipEnd.value !== null && clipEnd.value <= clipStart.value) {
    clipEnd.value = null;
  }
}

function setClipEndPoint() {
  clipEnd.value = currentTime.value;
  if (clipStart.value !== null && clipStart.value >= clipEnd.value) {
    clipStart.value = null;
  }
}

function clearClipPoints() {
  clipStart.value = null;
  clipEnd.value = null;
}

const clipDuration = computed(() => {
  if (clipStart.value !== null && clipEnd.value !== null) {
    return clipEnd.value - clipStart.value;
  }
  return null;
});

// Export clip using ffmpeg
async function exportClip() {
  if (clipStart.value === null || clipEnd.value === null || !videoPath.value) {
    return;
  }
  
  isExporting.value = true;
  exportProgress.value = 0;
  exportMessage.value = "Starting export...";
  
  try {
    const result = await invoke<string>("export_clip", {
      videoPath: videoPath.value,
      startTime: clipStart.value,
      endTime: clipEnd.value,
      outputName: `clip_${props.game.recording_id}_${Math.floor(clipStart.value)}s`,
    });
    
    exportMessage.value = `Exported: ${result}`;
  } catch (error) {
    exportMessage.value = `Export failed: ${error}`;
  } finally {
    isExporting.value = false;
  }
}

// Load video path
async function loadVideoPath() {
  try {
    const recordingsDir = await invoke<string>("get_recordings_dir");
    
    // Try to find the video file
    const path = await invoke<string | null>("find_video_file", {
      recordingsDir,
      filename: props.game.video_file,
    });
    
    if (path) {
      videoPath.value = path;
    } else {
      videoError.value = `Video file not found: ${props.game.video_file}`;
    }
  } catch (error) {
    videoError.value = `Failed to load video: ${error}`;
  }
}

// Video event handlers
function onVideoLoaded() {
  if (videoRef.value) {
    duration.value = videoRef.value.duration;
  }
}

function onVideoTimeUpdate() {
  if (videoRef.value) {
    currentTime.value = videoRef.value.currentTime;
  }
}

function onVideoPlay() {
  isPlaying.value = true;
}

function onVideoPause() {
  isPlaying.value = false;
}

function onVideoEnded() {
  isPlaying.value = false;
}

function onVideoError() {
  videoError.value = "Failed to load video";
}

// Keyboard shortcuts
function handleKeydown(event: KeyboardEvent) {
  // Ignore if typing in input
  if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
    return;
  }
  
  switch (event.key) {
    case " ":
      event.preventDefault();
      togglePlay();
      break;
    case "ArrowLeft":
      event.preventDefault();
      seekRelative(-5);
      break;
    case "ArrowRight":
      event.preventDefault();
      seekRelative(5);
      break;
    case "ArrowUp":
      event.preventDefault();
      seekRelative(30);
      break;
    case "ArrowDown":
      event.preventDefault();
      seekRelative(-30);
      break;
    case "m":
      toggleMute();
      break;
    case "f":
      toggleFullscreen();
      break;
    case "i":
      setClipStartPoint();
      break;
    case "o":
      setClipEndPoint();
      break;
    case "h":
      highlightsMode.value = !highlightsMode.value;
      break;
    case "n":
      if (highlightsMode.value && highlights.value.length > 0) {
        // Jump to next highlight
        const nextHl = highlights.value.find(h => h.start_time > currentTime.value + 1);
        if (nextHl) {
          seekToHighlight(nextHl.start_time);
        } else {
          // Wrap to first
          seekToHighlight(highlights.value[0].start_time);
        }
      }
      break;
    case "p":
      if (highlightsMode.value && highlights.value.length > 0) {
        // Jump to previous highlight
        const prevHl = [...highlights.value].reverse().find(h => h.end_time < currentTime.value - 1);
        if (prevHl) {
          seekToHighlight(prevHl.start_time);
        } else {
          // Wrap to last
          seekToHighlight(highlights.value[highlights.value.length - 1].start_time);
        }
      }
      break;
    case "Escape":
      if (clipStart.value !== null || clipEnd.value !== null) {
        clearClipPoints();
      } else if (highlightsMode.value) {
        highlightsMode.value = false;
      } else {
        emit("back");
      }
      break;
  }
}

// Format player name
function formatPlayerName(player: PlayerData): string {
  if (player.riotIdGameName) {
    return player.riotIdTagLine 
      ? `${player.riotIdGameName}#${player.riotIdTagLine}`
      : player.riotIdGameName;
  }
  return player.championName;
}

// Calculate KDA for player
function calculatePlayerKDA(player: PlayerData): string {
  const { kills, deaths, assists } = player.stats;
  if (deaths === 0) {
    return (kills + assists).toFixed(1);
  }
  return ((kills + assists) / deaths).toFixed(1);
}

// Lifecycle
onMounted(() => {
  loadVideoPath();
  window.addEventListener("keydown", handleKeydown);
  
});

onUnmounted(() => {
  window.removeEventListener("keydown", handleKeydown);
});
</script>

<template>
  <div class="game-review">
    <!-- Header -->
    <header class="review-header">
      <button class="back-btn" @click="emit('back')">
        <span class="back-icon">←</span>
        <span>Back to History</span>
      </button>
      
      <!-- Highlights Mode Toggle -->
      <button
        class="highlights-toggle"
        :class="{ active: highlightsMode }"
        @click="highlightsMode = !highlightsMode"
        title="Toggle Highlights mode"
      >
        <span class="toggle-icon">🎬</span>
        <span class="toggle-label">Highlights</span>
        <span v-if="highlights.length > 0" class="toggle-badge">{{ highlights.length }}</span>
      </button>
      
      <div class="header-info">
        <div class="header-champion">
          <img
            :src="getChampionImageUrl(getChampionName(game), 'square', gameVersion)"
            :alt="getChampionName(game) || 'Champion'"
            class="header-champion-img"
          />
          <div class="header-details">
            <h1>{{ getChampionName(game) || 'Unknown Champion' }}</h1>
            <div class="header-meta">
              <span class="queue-type">{{ getQueueDisplayName(getQueueType(game), getQueueId(game)) }}</span>
              <span class="duration">{{ formatDuration(game.duration_secs) }}</span>
              <span class="result" :style="{ color: getResultColor(getGameResult(game)) }">
                {{ getGameResult(game) }}
              </span>
              <span
                v-if="getLpChange(game)"
                class="lp-change-badge"
                :class="{ gain: getLpChange(game)!.leaguePointsDelta > 0, loss: getLpChange(game)!.leaguePointsDelta < 0 }"
              >
                {{ formatLpDelta(getLpChange(game)!.leaguePointsDelta) }} LP
              </span>
            </div>
            <div v-if="getLpChange(game)" class="header-rank">
              {{ formatRank(getLpChange(game)!.tier, getLpChange(game)!.division) }}
              · {{ getLpChange(game)!.leaguePoints }} LP
              <span v-if="getLpChange(game)!.inPromos" class="promo-badge">In Promos</span>
            </div>
          </div>
        </div>
      </div>
      
    </header>

    <!-- Main Content -->
    <div class="review-content">
      <!-- Video Section -->
      <div class="video-section with-sidebar">
        <div class="video-wrapper">
          <!-- Video Player -->
          <div class="video-container">
            <div v-if="videoError" class="video-error">
              <div class="error-icon">⚠️</div>
              <p>{{ videoError }}</p>
            </div>
            
            <video
              v-else-if="videoUrl"
              ref="videoRef"
              class="video-player"
              @loadedmetadata="onVideoLoaded"
              @timeupdate="onVideoTimeUpdate"
              @play="onVideoPlay"
              @pause="onVideoPause"
              @ended="onVideoEnded"
              @error="onVideoError"
            >
              <source :src="videoUrl" type="video/mp4" />
              Your browser does not support the video tag.
            </video>
            
            <div v-else class="video-loading">
              <div class="spinner"></div>
              <p>Loading video...</p>
            </div>
            
            <!-- Video Overlay Controls -->
            <div class="video-overlay" v-if="videoUrl && !videoError">
              <!-- Play/Pause Overlay -->
              <div class="play-overlay" @click="togglePlay">
                <div class="play-btn-large" v-if="!isPlaying">
                  <span>▶</span>
                </div>
              </div>
            </div>
          </div>

          <!-- Video Controls -->
          <div class="video-controls" v-if="videoUrl && !videoError">
            <!-- Timeline with events -->
            <div class="timeline-container">
              <div class="timeline-bar" @click="onTimelineClick">
                <!-- Progress bar -->
                <div class="timeline-progress" :style="{ width: `${(currentTime / duration) * 100}%` }"></div>
                
                <!-- Clip selection region -->
                <div
                  v-if="clipStart !== null && clipEnd !== null"
                  class="clip-region"
                  :style="{
                    left: `${(clipStart / duration) * 100}%`,
                    width: `${((clipEnd - clipStart) / duration) * 100}%`
                  }"
                ></div>
                
                <!-- Highlight regions (shown in highlights mode) -->
                <div
                  v-if="highlightsMode"
                  v-for="clip in highlights"
                  :key="'hl-' + clip.id"
                  class="highlight-region"
                  :class="{ active: playingHighlightId === clip.id }"
                  :style="{
                    left: `${(clip.start_time / duration) * 100}%`,
                    width: `${((clip.end_time - clip.start_time) / duration) * 100}%`,
                    backgroundColor: getHighlightTypeColor(clip.highlight_type),
                  }"
                  @click.stop="seekToHighlight(clip.start_time)"
                  :title="`${clip.title} (${formatDuration(clip.end_time - clip.start_time)})`"
                ></div>
                
                <!-- Event markers -->
                <div
                  v-for="(event, idx) in sortedEvents"
                  :key="idx"
                  class="event-marker"
                  :style="{
                    left: `${getEventPosition(event)}%`,
                    backgroundColor: getEventColor(event)
                  }"
                  :title="`${formatEventTime(event)} - ${event.event_type}: ${event.description}`"
                  @click.stop="seekToEvent(event)"
                  @mouseenter="hoveredEvent = event"
                  @mouseleave="hoveredEvent = null"
                ></div>
                
                <!-- Current time indicator -->
                <div class="time-indicator" :style="{ left: `${(currentTime / duration) * 100}%` }"></div>
              </div>
              
              <!-- Event tooltip -->
              <div
                v-if="hoveredEvent"
                class="event-tooltip"
                :style="{ left: `${getEventPosition(hoveredEvent)}%` }"
              >
                <div class="tooltip-time">{{ formatEventTime(hoveredEvent) }}</div>
                <div class="tooltip-type">{{ hoveredEvent.event_type }}</div>
                <div class="tooltip-desc">{{ hoveredEvent.description }}</div>
              </div>
            </div>
            
            <!-- Control buttons -->
            <div class="controls-row">
              <div class="controls-left">
                <button class="control-btn" @click="togglePlay" :title="isPlaying ? 'Pause (Space)' : 'Play (Space)'">
                  <span v-if="isPlaying">⏸</span>
                  <span v-else>▶</span>
                </button>
                
                <button class="control-btn" @click="seekRelative(-10)" title="Back 10s (←)">
                  <span>⏪</span>
                </button>
                
                <button class="control-btn" @click="seekRelative(10)" title="Forward 10s (→)">
                  <span>⏩</span>
                </button>
                
                <div class="time-display">
                  <span>{{ formatDuration(currentTime) }}</span>
                  <span class="time-sep">/</span>
                  <span>{{ formatDuration(duration) }}</span>
                </div>
              </div>
              
              <div class="controls-center">
                <!-- Clip editing -->
                <div class="clip-controls">
                  <button
                    class="clip-btn"
                    :class="{ active: clipStart !== null }"
                    @click="setClipStartPoint"
                    title="Set clip start (I)"
                  >
                    [I] Start
                  </button>
                  <button
                    class="clip-btn"
                    :class="{ active: clipEnd !== null }"
                    @click="setClipEndPoint"
                    title="Set clip end (O)"
                  >
                    [O] End
                  </button>
                  <span v-if="clipDuration" class="clip-duration">
                    {{ formatDuration(clipDuration) }}
                  </span>
                  <button
                    v-if="clipStart !== null || clipEnd !== null"
                    class="clip-btn clear"
                    @click="clearClipPoints"
                  >
                    Clear
                  </button>
                  <button
                    v-if="clipStart !== null && clipEnd !== null"
                    class="clip-btn export"
                    @click="exportClip"
                    :disabled="isExporting"
                  >
                    {{ isExporting ? 'Exporting...' : 'Export Clip' }}
                  </button>
                </div>
              </div>
              
              <div class="controls-right">
                <!-- Playback speed -->
                <select
                  class="speed-select"
                  :value="playbackRate"
                  @change="setPlaybackRate(parseFloat(($event.target as HTMLSelectElement).value))"
                >
                  <option value="0.25">0.25x</option>
                  <option value="0.5">0.5x</option>
                  <option value="0.75">0.75x</option>
                  <option value="1">1x</option>
                  <option value="1.25">1.25x</option>
                  <option value="1.5">1.5x</option>
                  <option value="2">2x</option>
                </select>
                
                <!-- Volume -->
                <div class="volume-control">
                  <button class="control-btn" @click="toggleMute" :title="isMuted ? 'Unmute (M)' : 'Mute (M)'">
                    <span v-if="isMuted || volume === 0">🔇</span>
                    <span v-else-if="volume < 0.5">🔉</span>
                    <span v-else>🔊</span>
                  </button>
                  <input
                    type="range"
                    class="volume-slider"
                    min="0"
                    max="1"
                    step="0.1"
                    :value="isMuted ? 0 : volume"
                    @input="setVolume(parseFloat(($event.target as HTMLInputElement).value))"
                  />
                </div>
                
                <button class="control-btn" @click="toggleFullscreen" title="Fullscreen (F)">
                  <span>⛶</span>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Export message -->
        <div v-if="exportMessage" class="export-message" :class="{ error: exportMessage.includes('failed') }">
          {{ exportMessage }}
          <button @click="exportMessage = null">×</button>
        </div>
      </div>

      <!-- Stats Sidebar (shown when NOT in highlights mode) -->
      <div v-if="!highlightsMode" class="stats-sidebar">
        <!-- Player Stats Panel -->
        <div class="stats-panel">
          <h3>Your Stats</h3>
          
          <!-- Player details -->
          <div v-if="selectedPlayer" class="selected-player-details">
            <div class="player-header">
              <img :src="getChampionImageUrl(selectedPlayer.championName, 'square', gameVersion)" class="player-champion-img" />
              <div class="player-info">
                <div class="player-name-large">{{ selectedPlayer.championName }}</div>
                <div class="player-riot-id">{{ formatPlayerName(selectedPlayer) }}</div>
              </div>
            </div>
            
            <div class="player-kda">
              <div class="kda-values">
                {{ selectedPlayer.stats.kills }} / {{ selectedPlayer.stats.deaths }} / {{ selectedPlayer.stats.assists }}
              </div>
              <div class="kda-ratio">
                {{ calculatePlayerKDA(selectedPlayer) }} KDA
              </div>
            </div>
            
            <div class="player-stats-grid">
              <div class="stat-item">
                <span class="stat-value">{{ formatNumber(selectedPlayer.stats.goldEarned) }}</span>
                <span class="stat-label">Gold</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ selectedPlayer.stats.minionsKilled }}</span>
                <span class="stat-label">CS</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ formatNumber(selectedPlayer.stats.totalDamageDealtToChampions) }}</span>
                <span class="stat-label">Damage</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ formatNumber(selectedPlayer.stats.totalDamageTaken) }}</span>
                <span class="stat-label">Taken</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ selectedPlayer.stats.visionScore.toFixed(1) }}</span>
                <span class="stat-label">Vision</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ selectedPlayer.stats.level }}</span>
                <span class="stat-label">Level</span>
              </div>
            </div>
            
            <!-- Items -->
            <div class="player-items">
              <div class="items-label">Items:</div>
              <div class="items-row">
                <div v-for="(itemId, idx) in selectedPlayer.items.slice(0, 6)" :key="idx" class="item-slot">
                  <img v-if="itemId" :src="getItemImageUrl(itemId, gameVersion)" :alt="`Item ${itemId}`" />
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Team Stats Panel -->
        <div class="stats-panel team-panel">
          <h3>Team Overview</h3>
          
          <div class="team-table">
            <div class="team-header">
              <span>Champion</span>
              <span>K/D/A</span>
              <span>Gold</span>
              <span>Damage</span>
            </div>
            
            <div
              v-for="player in teamPlayers"
              :key="player.puuid"
              class="team-row"
              :class="{ local: player.isLocalPlayer }"
            >
              <div class="team-champion">
                <img :src="getChampionImageUrl(player.championName, 'square', gameVersion)" :alt="player.championName" />
                <span>{{ player.championName }}</span>
              </div>
              <div class="team-kda">
                {{ player.stats.kills }}/{{ player.stats.deaths }}/{{ player.stats.assists }}
              </div>
              <div class="team-gold">{{ formatNumber(player.stats.goldEarned) }}</div>
              <div class="team-damage">{{ formatNumber(player.stats.totalDamageDealtToChampions) }}</div>
            </div>
          </div>
          
          <h4 class="enemy-header">Enemy Team</h4>
          
          <div class="team-table enemy-table">
            <div
              v-for="player in enemyPlayers"
              :key="player.puuid"
              class="team-row enemy"
            >
              <div class="team-champion">
                <img :src="getChampionImageUrl(player.championName, 'square', gameVersion)" :alt="player.championName" />
                <span>{{ player.championName }}</span>
              </div>
              <div class="team-kda">
                {{ player.stats.kills }}/{{ player.stats.deaths }}/{{ player.stats.assists }}
              </div>
              <div class="team-gold">{{ formatNumber(player.stats.goldEarned) }}</div>
              <div class="team-damage">{{ formatNumber(player.stats.totalDamageDealtToChampions) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Highlights Sidebar (shown when in highlights mode) -->
      <div v-else class="stats-sidebar highlights-sidebar">
        <HighlightsPanel
          :highlights="highlights"
          :current-video-time="currentTime"
          :video-duration="duration"
          :is-playing="isPlaying"
          :is-exporting="isExporting"
          :exporting-clip-id="exportingHighlightId"
          @seek-to="seekToHighlight"
          @play-clip="playHighlightClip"
          @play-all="playAllHighlights"
          @export-clip="exportHighlightClip"
          @export-all="exportAllHighlights"
          @settings-changed="onHighlightSettingsChanged"
        />
      </div>
    </div>

  </div>
</template>

<style scoped>
.game-review {
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(180deg, #0a0a13 0%, #0f0f1a 100%);
  color: #fff;
  display: flex;
  flex-direction: column;
}

/* Header */
.review-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  background: rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.15);
}

.back-icon {
  font-size: 1.2rem;
}

/* Highlights Mode Toggle */
.highlights-toggle {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.12);
  color: #94a3b8;
  padding: 0.45rem 0.85rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.85rem;
  font-weight: 500;
}

.highlights-toggle:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #e2e8f0;
}

.highlights-toggle.active {
  background: rgba(249, 115, 22, 0.15);
  border-color: rgba(249, 115, 22, 0.4);
  color: #f97316;
}

.highlights-toggle .toggle-icon {
  font-size: 1rem;
}

.highlights-toggle .toggle-label {
  font-size: 0.85rem;
}

.highlights-toggle .toggle-badge {
  font-size: 0.7rem;
  font-weight: 700;
  background: rgba(249, 115, 22, 0.3);
  color: #f97316;
  padding: 0.1rem 0.4rem;
  border-radius: 8px;
  min-width: 1.2rem;
  text-align: center;
}

.highlights-toggle.active .toggle-badge {
  background: rgba(249, 115, 22, 0.5);
  color: #fff;
}

.header-info {
  display: flex;
  align-items: center;
}

.header-champion {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.header-champion-img {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  object-fit: cover;
}

.header-details h1 {
  font-size: 1.25rem;
  margin: 0;
  font-weight: 600;
}

.header-meta {
  display: flex;
  gap: 1rem;
  font-size: 0.85rem;
  color: #888;
}

.header-meta .result {
  font-weight: 600;
}

.lp-change-badge {
  font-size: 0.8rem;
  font-weight: 700;
  padding: 0.1rem 0.5rem;
  border-radius: 4px;
}

.lp-change-badge.gain {
  color: #4ade80;
  background: rgba(74, 222, 128, 0.15);
}

.lp-change-badge.loss {
  color: #f87171;
  background: rgba(248, 113, 113, 0.15);
}

.header-rank {
  font-size: 0.8rem;
  color: #c8aa6e;
  margin-top: 0.15rem;
}

.promo-badge {
  font-size: 0.65rem;
  font-weight: 700;
  color: #fbbf24;
  background: rgba(251, 191, 36, 0.15);
  padding: 0.1rem 0.35rem;
  border-radius: 3px;
  margin-left: 0.35rem;
  text-transform: uppercase;
}

/* Main Content */
.review-content {
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

/* Video Section */
.video-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  min-height: 0;
  align-items: center;
}

.video-section.with-sidebar {
  max-width: calc(100% - 350px);
}

.video-wrapper {
  width: min(100%, calc(75vh * 16 / 9));
  max-height: calc(75vh + 120px);
  display: flex;
  flex-direction: column;
}

.video-container {
  position: relative;
  background: #000;
  aspect-ratio: 16/9;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: auto;
  cursor: pointer;
}

.play-btn-large {
  width: 80px;
  height: 80px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  transition: all 0.2s;
}

.play-overlay:hover .play-btn-large {
  background: rgba(0, 0, 0, 0.8);
  transform: scale(1.1);
}

.video-loading,
.video-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;
  padding: 2rem;
}

.video-error .error-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #333;
  border-top-color: #c8aa6e;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* Video Controls */
.video-controls {
  background: rgba(0, 0, 0, 0.8);
  padding: 0.75rem 1rem;
}

.timeline-container {
  position: relative;
  margin-bottom: 0.75rem;
}

.timeline-bar {
  position: relative;
  height: 24px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  cursor: pointer;
  overflow: visible;
}

.timeline-progress {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: rgba(200, 170, 110, 0.5);
  border-radius: 4px 0 0 4px;
  pointer-events: none;
}

.clip-region {
  position: absolute;
  top: 0;
  height: 100%;
  background: rgba(74, 222, 128, 0.3);
  border-left: 2px solid #4ade80;
  border-right: 2px solid #4ade80;
  pointer-events: none;
}

/* Highlight regions on timeline */
.highlight-region {
  position: absolute;
  top: 0;
  height: 100%;
  opacity: 0.2;
  border-radius: 2px;
  cursor: pointer;
  transition: opacity 0.2s;
  z-index: 0;
}

.highlight-region:hover {
  opacity: 0.4;
}

.highlight-region.active {
  opacity: 0.45;
}

.event-marker {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 4px;
  height: 16px;
  border-radius: 2px;
  cursor: pointer;
  transition: all 0.15s;
  z-index: 1;
}

.event-marker:hover {
  transform: translate(-50%, -50%) scale(1.5);
  z-index: 2;
}

.time-indicator {
  position: absolute;
  top: 0;
  transform: translateX(-50%);
  width: 3px;
  height: 100%;
  background: #c8aa6e;
  border-radius: 2px;
  pointer-events: none;
  z-index: 3;
}

.event-tooltip {
  position: absolute;
  bottom: 100%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  padding: 0.5rem 0.75rem;
  font-size: 0.75rem;
  white-space: nowrap;
  z-index: 10;
  margin-bottom: 8px;
}

.tooltip-time {
  color: #c8aa6e;
  font-weight: 600;
}

.tooltip-type {
  color: #fff;
  font-weight: 500;
}

.tooltip-desc {
  color: #888;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.controls-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}

.controls-left,
.controls-right {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.controls-center {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.control-btn {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: #fff;
  width: 36px;
  height: 36px;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  transition: all 0.2s;
}

.control-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.time-display {
  font-family: monospace;
  font-size: 0.9rem;
  color: #fff;
  padding: 0 0.5rem;
}

.time-sep {
  color: #666;
  margin: 0 0.25rem;
}

/* Clip Controls */
.clip-controls {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.clip-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 0.35rem 0.75rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  transition: all 0.2s;
}

.clip-btn:hover {
  background: rgba(255, 255, 255, 0.15);
}

.clip-btn.active {
  background: rgba(74, 222, 128, 0.3);
  border-color: #4ade80;
}

.clip-btn.clear {
  border-color: #f87171;
}

.clip-btn.export {
  background: rgba(200, 170, 110, 0.3);
  border-color: #c8aa6e;
}

.clip-btn.export:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.clip-duration {
  font-family: monospace;
  font-size: 0.85rem;
  color: #4ade80;
  padding: 0 0.5rem;
}

/* Volume Control */
.volume-control {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.volume-slider {
  width: 60px;
  height: 4px;
  -webkit-appearance: none;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 2px;
  cursor: pointer;
}

.volume-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 12px;
  height: 12px;
  background: #c8aa6e;
  border-radius: 50%;
  cursor: pointer;
}

/* Speed Select */
.speed-select {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  padding: 0.35rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  cursor: pointer;
}

.speed-select option {
  background: #1a1a2e;
}

/* Export Message */
.export-message {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(74, 222, 128, 0.9);
  color: #000;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 1rem;
  z-index: 100;
}

.export-message.error {
  background: rgba(248, 113, 113, 0.9);
  color: #fff;
}

.export-message button {
  background: none;
  border: none;
  color: inherit;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0;
  line-height: 1;
}

/* Stats Sidebar */
.stats-sidebar {
  width: 350px;
  background: rgba(0, 0, 0, 0.3);
  border-left: 1px solid rgba(255, 255, 255, 0.1);
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* Highlights sidebar delegates scrolling to the panel's internal list */
.stats-sidebar.highlights-sidebar {
  overflow: hidden;
  padding: 0;
}

.stats-panel {
  background: rgba(255, 255, 255, 0.03);
  border-radius: 8px;
  padding: 1rem;
}

.stats-panel h3 {
  margin: 0 0 1rem 0;
  font-size: 1rem;
  color: #c8aa6e;
}

/* Selected Player Details */
.selected-player-details {
  padding-top: 0;
}

.player-header {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 1rem;
}

.player-champion-img {
  width: 48px;
  height: 48px;
  border-radius: 8px;
}

.player-info .player-name-large {
  font-size: 1.1rem;
  font-weight: 600;
}

.player-info .player-riot-id {
  font-size: 0.8rem;
  color: #888;
}

.player-kda {
  text-align: center;
  margin-bottom: 1rem;
  padding: 0.75rem;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
}

.kda-values {
  font-size: 1.5rem;
  font-weight: 700;
  color: #fff;
}

.kda-ratio {
  font-size: 0.9rem;
  color: #c8aa6e;
}

.player-stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0.5rem;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 6px;
}

.stat-value {
  font-size: 1rem;
  font-weight: 600;
  color: #fff;
}

.stat-label {
  font-size: 0.7rem;
  color: #888;
  text-transform: uppercase;
}

.player-items {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  padding-top: 0.75rem;
}

.items-label {
  font-size: 0.75rem;
  color: #888;
  margin-bottom: 0.5rem;
}

.items-row {
  display: flex;
  gap: 4px;
}

.item-slot {
  width: 32px;
  height: 32px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  overflow: hidden;
}

.item-slot img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* Team Panel */
.team-panel {
  flex: 1;
}

.enemy-header {
  margin: 1rem 0 0.5rem 0;
  font-size: 0.85rem;
  color: #f87171;
}

.team-table {
  font-size: 0.8rem;
}

.team-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  gap: 0.5rem;
  padding: 0.5rem;
  color: #888;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.team-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  gap: 0.5rem;
  padding: 0.5rem;
  align-items: center;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

.team-row:hover {
  background: rgba(255, 255, 255, 0.05);
}

.team-row.local {
  background: rgba(200, 170, 110, 0.1);
}

.team-row.enemy {
  cursor: default;
}

.team-champion {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.team-champion img {
  width: 24px;
  height: 24px;
  border-radius: 4px;
}

.team-kda {
  font-family: monospace;
}

.team-gold,
.team-damage {
  font-family: monospace;
  color: #888;
}

/* Responsive */
@media (max-width: 1200px) {
  .video-section.with-sidebar {
    max-width: 100%;
  }
  
  .stats-sidebar {
    position: fixed;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 50;
    transform: translateX(100%);
    transition: transform 0.3s;
  }
  
  .stats-sidebar:not(.hidden) {
    transform: translateX(0);
  }
}
</style>
