@extends('layouts.app')
@section('main_class', 'video-view-page')
@section('title', ($video->title ?? 'Match Video') . ' | ' . config('app.name'))

@push('head')
<meta property="og:title"       content="{{ $video->title }}">
<meta property="og:description" content="{{ Str::limit(strip_tags($video->description ?? config('app.name') . ' — watch now'), 200) }}">
<meta property="og:image"        content="{{ route('videos.ogImage', $video) }}">
<meta property="og:image:width"  content="1200">
<meta property="og:image:height" content="630">
<meta property="og:url"         content="{{ $video->share_url }}">
<meta property="og:type"        content="video.other">
<meta property="og:site_name"   content="{{ config('app.name') }}">
<meta name="twitter:card"       content="summary_large_image">
<meta name="twitter:title"      content="{{ $video->title }}">
<meta name="twitter:description" content="{{ Str::limit(strip_tags($video->description ?? ''), 200) }}">
<meta name="twitter:image"      content="{{ route('videos.ogImage', $video) }}">
@endpush

@section('extra_styles')
    <style>
        /* ===== Video Section ===== */
        .yt-video-section {
            flex: 1;
            min-width: 0;
        }

        /* ===== Sidebar (copied from music.blade.php) ===== */
        .yt-sidebar-container {
            width: 400px;
            flex-shrink: 0;
        }

        .sidebar-video-card {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
            cursor: pointer;
        }

        .sidebar-thumb {
            width: 168px;
            aspect-ratio: 16/9;
            border-radius: 8px;
            overflow: hidden;
            background: #1a1a1a;
            flex-shrink: 0;
        }

        .sidebar-thumb img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .sidebar-info {
            flex: 1;
            min-width: 0;
        }

        .sidebar-title {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .sidebar-meta {
            font-size: 12px;
            color: var(--text-secondary);
        }

        /* ===== Video Player ===== */
        .video-container {
            position: relative;
            aspect-ratio: 16/9;
            background: #000;
            border-radius: 12px;
            overflow: hidden;
            max-height: 70vh;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
        }

        .video-container.portrait,
        .video-container.square,
        .video-container.ultrawide {
            margin: 0 auto;
            width: auto;
        }

        .video-container.portrait {
            aspect-ratio: 9/16;
            max-width: 50vh;
        }

        .video-container.square {
            aspect-ratio: 1/1;
            max-width: 70vh;
        }

        .video-container.ultrawide {
            aspect-ratio: 21/9;
            max-width: 100%;
        }

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

        /* Coach note overlay (subtitle-style) */
        .coach-note-overlay {
            position: absolute;
            left: 50%;
            bottom: 48px;
            transform: translateX(-50%);
            max-width: min(80%, 900px);
            width: fit-content;
            padding: 10px 14px;
            border-radius: 8px;
            background: rgba(0, 0, 0, 0.68);
            color: #fff;
            font-size: 16px;
            font-weight: 600;
            line-height: 1.35;
            text-align: center;
            z-index: 14;
            box-shadow: 0 6px 22px rgba(0, 0, 0, 0.35);
            border: 1px solid rgba(255, 255, 255, 0.18);
            display: none;
            pointer-events: none;
            backdrop-filter: blur(3px);
        }

        .coach-note-overlay.show {
            display: block;
        }

        /* Match Highlights Toggle Button */
        .match-highlights-toggle {
            position: absolute;
            top: 8px;
            right: 8px;
            background: rgba(0, 0, 0, 0.85);
            border: 1px solid rgba(255, 255, 255, 0.15);
            border-radius: 16px;
            width: 64px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            z-index: 15;
            transition: all 0.2s ease;
            backdrop-filter: blur(12px);
            font-size: 9px;
            font-weight: 600;
            letter-spacing: 0.2px;
            padding: 0 6px;
        }

        .match-highlights-toggle:hover {
            background: rgba(255, 255, 255, 0.12);
            border-color: rgba(255, 255, 255, 0.3);
            transform: translateY(-1px);
        }

        /* No rotation animation */

        /* Hide sidebar by default */
        .events-sidebar {
            display: none;
        }

        .events-sidebar.show {
            display: flex;
        }

        /* ===== Playlist Navigation Controls ===== */
        .playlist-controls {
            position: absolute;
            bottom: 60px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            align-items: center;
            gap: 12px;
            background: rgba(0, 0, 0, 0.8);
            padding: 8px 16px;
            border-radius: 24px;
            z-index: 10;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .video-container:hover .playlist-controls,
        .playlist-controls.visible {
            opacity: 1;
        }

        .playlist-nav-btn {
            background: transparent;
            border: none;
            color: white;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: background 0.2s ease;
        }

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

        .playlist-nav-btn:disabled {
            opacity: 0.3;
            cursor: not-allowed;
        }

        .playlist-nav-btn:disabled:hover {
            background: transparent;
        }

        .playlist-nav-btn i {
            font-size: 20px;
        }

        .playlist-nav-label {
            font-size: 12px;
            color: #aaa;
            max-width: 120px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* ===== Autoplay Toggle ===== */
        .autoplay-toggle {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 0 8px;
            border-left: 1px solid rgba(255, 255, 255, 0.2);
        }

        .autoplay-toggle label {
            font-size: 12px;
            color: #aaa;
            cursor: pointer;
            white-space: nowrap;
        }

        .autoplay-switch {
            position: relative;
            width: 36px;
            height: 20px;
        }

        .autoplay-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .autoplay-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #666;
            transition: 0.3s;
            border-radius: 20px;
        }

        .autoplay-slider:before {
            position: absolute;
            content: "";
            height: 14px;
            width: 14px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.3s;
            border-radius: 50%;
        }

        .autoplay-switch input:checked+.autoplay-slider {
            background-color: var(--brand-red);
        }

        .autoplay-switch input:checked+.autoplay-slider:before {
            transform: translateX(16px);
        }

        /* ===== Keyboard Hint ===== */
        .keyboard-hint {
            position: absolute;
            bottom: 10px;
            right: 10px;
            font-size: 10px;
            color: rgba(255, 255, 255, 0.5);
            background: rgba(0, 0, 0, 0.6);
            padding: 4px 8px;
            border-radius: 4px;
        }

        /* ===== Video Info ===== */
        .video-title {
            font-size: 20px;
            font-weight: 500;
            margin: 16px 0 8px;
            line-height: 1.3;
        }

        .video-stats-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-color);
            flex-wrap: wrap;
            gap: 12px;
        }

        .video-stats-left {
            display: flex;
            align-items: center;
            gap: 16px;
            color: var(--text-secondary);
        }

        .video-actions {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        /* ===== Channel Row ===== */
        .channel-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 16px 0;
        }

        .channel-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .channel-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: #555;
        }

        .channel-name {
            font-size: 16px;
            font-weight: 500;
        }

        .channel-subs {
            font-size: 14px;
            color: var(--text-secondary);
        }

        .subscribe-btn {
            border: none;
            border-radius: 8px;
            padding: 8px 14px;
            font-size: 0.82rem;
            font-weight: 500;
            cursor: pointer;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s ease;
            white-space: nowrap;
        }

        .subscribe-btn:hover {
            background: var(--border-color);
            transform: translateY(-1px);
        }

        .mobile-action-dropdown {
            display: none;
            position: relative;
        }

        .mobile-action-dropdown .dropdown-menu {
            right: 0;
            left: auto;
            min-width: 200px;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: 10px;
            padding: 6px 0;
            z-index: 1200;
        }

        .mobile-action-dropdown .dropdown-item {
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            padding: 8px 12px;
            background: transparent;
            border: none;
            width: 100%;
            text-align: left;
        }

        .mobile-action-dropdown .dropdown-item:hover {
            background: var(--border-color);
        }

        /* ===== Event Header ===== */
        .event-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-top: 16px;
            padding: 12px 0;
        }

        .event-header-left {
            display: flex;
            align-items: flex-start;
            gap: 12px;
            min-width: 0;
            flex: 1;
        }

        .event-logo {
            width: 56px;
            height: 56px;
            border-radius: 14px;
            overflow: hidden;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .event-logo img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .event-text {
            display: flex;
            flex-direction: column;
            gap: 4px;
            min-width: 0;
            flex: 1;
        }

        .event-text .title {
            font-size: 1.4rem;
            margin: 0;
            line-height: 1.3;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
        }

        .event-text .title .trophy-icon {
            color: #ef4444;
            font-size: 1.2rem;
        }

        .event-text .title a {
            color: inherit;
            text-decoration: none;
        }

        .event-text .title a:hover {
            text-decoration: underline;
            opacity: 0.85;
        }

        .event-text .meta-link {
            font-size: 0.85rem;
            color: var(--text-secondary);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            text-decoration: none;
            cursor: pointer;
            transition: color 0.2s ease;
        }

        .event-text .meta-link:hover {
            color: var(--brand-red);
        }

        .event-text .meta-link a {
            color: inherit;
            font-weight: bold;
            text-decoration: none;
        }

        .event-text .meta-link a:hover {
            text-decoration: underline;
        }

        .event-header-actions {
            display: flex;
            align-items: center;
            gap: 8px;
            flex-shrink: 0;
        }

        .event-header-actions .action-btn {
            border: none;
            border-radius: 8px;
            padding: 8px 14px;
            font-size: 0.82rem;
            font-weight: 500;
            cursor: pointer;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s ease;
        }

        .event-header-actions .action-btn:hover {
            background: var(--border-color);
            transform: translateY(-1px);
        }

        .event-header-actions .action-btn:active {
            transform: translateY(0);
        }

        .event-header-actions .action-btn svg,
        .event-header-actions .action-btn i {
            flex-shrink: 0;
        }

        .event-header-actions .action-btn.liked {
            color: var(--brand-red);
        }

        .action-btn,
        .action-btn a,
        .comment-section .action-btn {
            border: none;
            border-radius: 8px;
            padding: 8px 14px;
            font-size: 0.82rem;
            font-weight: 500;
            cursor: pointer;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s ease;
            text-decoration: none;
        }

        .action-btn:hover,
        .action-btn a:hover,
        .comment-section .action-btn:hover {
            background: var(--border-color);
            transform: translateY(-1px);
            text-decoration: none;
        }

        .action-btn:active,
        .comment-section .action-btn:active {
            transform: translateY(0);
        }

        .action-btn svg,
        .action-btn i,
        .comment-section .action-btn svg,
        .comment-section .action-btn i {
            flex-shrink: 0;
        }

        .action-btn.comment-btn {
            background: var(--brand-red);
            color: white;
            border-color: var(--brand-red);
        }

        .event-header-actions .action-btn.disliked {
            color: #ef4444;
            background: rgba(239, 68, 68, 0.15);
            border-color: #ef4444;
        }

        .event-header-actions .action-btn.saved {
            color: #f59e0b;
            background: rgba(245, 158, 11, 0.15);
            border-color: #f59e0b;
        }

        .event-header-actions .action-btn.subscribed {
            color: #ffffff;
            background: #6b7280;
            border-color: #6b7280;
        }

        /* Video Owner Badge */
        .video-owner-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 0.85rem;
            color: var(--text-secondary);
            margin-top: 4px;
        }

        .video-owner-badge .owner-avatar {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            object-fit: cover;
        }

        .video-owner-badge .owner-name {
            color: var(--text-primary);
            font-weight: 500;
        }

        /* ===== Description Panel ===== */
        .description-panel {
            margin-top: 16px;
            border-radius: 12px;
            padding: 8px 10px 10px;
        }

        .description-toggle {
            width: 100%;
            border: none;
            background: transparent;
            color: var(--text-primary);
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 0.85rem;
            cursor: pointer;
            padding: 4px 0;
        }

        .description-toggle:hover {
            color: #ffffff;
        }

        .description-body {
            margin-top: 6px;
            display: none;
        }

        .description-body.open {
            display: block;
        }

        /* ===== Match Card ===== */
        .match-card {
            margin-top: 16px;
            padding: 16px 18px;
            border-radius: 14px;
            border: 1px solid var(--border-color);
            background: var(--bg-secondary);
        }

        .match-header {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-bottom: 12px;
        }

        .match-label {
            font-size: 1.2rem;
            text-transform: uppercase;
            letter-spacing: 0.16em;
            color: var(--text-primary);
            text-align: center;
            font-weight: 600;
        }

        .fighters-row {
            display: grid;
            grid-template-columns: 1.1fr 0.8fr 1.1fr;
            align-items: stretch;
            gap: 16px;
        }

        .fighter-card {
            border-radius: 14px;
            padding: 10px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }

        .fighter-top {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            width: 100%;
        }

        .fighter-photo {
            width: 110px;
            height: 145px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 0 1px var(--bg-primary);
            flex-shrink: 0;
        }

        .fighter-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .fighter-logo {
            width: 64px;
            height: 64px;
            border-radius: 20px;
            overflow: hidden;
            background: var(--bg-primary);
        }

        .fighter-logo img {
            width: 100%;
            height: 100%;
            object-fit: contain;
        }

        .fighter-badge {
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.12em;
            padding: 3px 8px;
            border-radius: 999px;
            border: 1px solid #404040;
            color: var(--text-primary);
        }

        .fighter-badge.blue {
            background: rgba(37, 99, 235, 0.15);
            border-color: #1d4ed8;
        }

        .fighter-badge.red {
            background: rgba(239, 68, 68, 0.14);
            border-color: #b91c1c;
        }

        .fighter-name.blue-corner {
            color: #2563eb;
            font-weight: bold;
        }

        .fighter-name.red-corner {
            color: #ef4444;
            font-weight: bold;
        }

        .fighter-name a {
            color: inherit;
            text-decoration: none;
        }

        .fighter-name a:hover {
            text-decoration: underline;
        }

        .fighter-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
            width: 100%;
            text-align: center;
            font-size: 0.8rem;
        }

        .fighter-name {
            font-weight: 600;
            font-size: 0.95rem;
        }

        .fighter-team {
            color: var(--text-secondary);
        }

        .fighter-team a {
            color: inherit;
            text-decoration: none;
        }

        .fighter-team a:hover {
            text-decoration: underline;
        }

        .fighter-country {
            display: inline-flex;
            justify-content: center;
            align-items: center;
            gap: 4px;
            color: var(--text-secondary);
            margin-top: 2px;
        }

        .fighter-country-flag { display: inline-flex; align-items: center; }
        .fighter-country-flag .fi { width: 22px; height: 16px; border-radius: 2px; }

        .match-center {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
        }

        .score-pill {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 6px 12px;
            border-radius: 999px;
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
        }

        .score-number {
            font-size: 2rem;
            font-weight: 700;
        }

        .score-label {
            font-size: 0.75rem;
            color: var(--text-secondary);
        }

        .referee-block {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
        }

        .referee-photo {
            width: 80px;
            height: 115px;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 0 1px var(--bg-primary);
            flex-shrink: 0;
        }

        .referee-photo img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .referee-block a {
            color: inherit;
            text-decoration: none;
        }

        .referee-block a:hover {
            text-decoration: underline;
        }

        .ref-label {
            font-size: 0.7rem;
            color: var(--text-secondary);
        }

        .match-footer {
            margin-top: 12px;
            font-size: 0.8rem;
            color: #666666;
            text-align: center;
        }

        .hall-link {
            color: #e61e1e;
            font-weight: 600;
            text-decoration: none;
            cursor: pointer;
            transition: color 0.2s ease;
        }

        .hall-link:hover {
            color: #ff4757;
            text-decoration: underline;
        }

        /* ===== Markdown Body ===== */
        .markdown-body {
            font-size: 0.95rem;
            line-height: 1.6;
            margin-top: 16px;
        }

        .markdown-body h2 {
            font-size: 1.05rem;
            margin-top: 14px;
        }

        .description-text {
            font-size: 14px;
            line-height: 1.5;
            color: var(--text-primary);
        }

        .description-text p {
            margin-bottom: 8px;
        }

        .description-text a {
            color: #3ea6ff;
        }

        /* ===== Sidebar ===== */
        .yt-sidebar-container {
            width: 400px;
            flex-shrink: 0;
        }

        /* ===== Match Events Sidebar ===== */
        .events-sidebar {
            background: var(--bg-secondary);
            border-radius: 12px;
            overflow: hidden;
            width: 400px;
            flex-shrink: 0;
            height: var(--sidebar-height, 400px);
            display: none !important;
            flex-direction: column;
        }

        .events-sidebar.show {
            display: flex !important;
        }

        .events-sidebar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .events-sidebar-header h3 {
            font-size: 16px;
            font-weight: 600;
            margin: 0;
        }

        .close-btn {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            font-size: 24px;
            cursor: pointer;
            padding: 0;
            line-height: 1;
        }

        .close-btn:hover {
            color: var(--text-primary);
        }

        .tab-header {
            display: flex;
            border-bottom: 1px solid var(--border-color);
        }

        .tab-button {
            flex: 1;
            padding: 12px 16px;
            background: transparent;
            border: none;
            color: var(--text-secondary);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            border-bottom: 2px solid transparent;
        }

        .tab-button:hover {
            color: var(--text-primary);
            background: rgba(255, 255, 255, 0.05);
        }

        .tab-button.active {
            color: var(--brand-red);
            border-bottom-color: var(--brand-red);
        }

        .tab-panels {
            height: 100%;
            overflow-y: auto;
            flex: 1;
        }

        /* Custom Scrollbar for Match Highlights */
        .tab-panels::-webkit-scrollbar {
            width: 6px;
        }

        .tab-panels::-webkit-scrollbar-track {
            background: var(--bg-primary);
            border-radius: 3px;
        }

        .tab-panels::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 3px;
        }

        .tab-panels::-webkit-scrollbar-thumb:hover {
            background: var(--text-secondary);
        }

        .tab-panels::-webkit-scrollbar-corner {
            background: var(--bg-primary);
        }

        .tab-panel {
            display: none;
            padding: 16px;
        }

        .tab-panel.active {
            display: block;
        }

        .section-label {
            font-size: 12px;
            color: var(--text-secondary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: 500;
        }

        .btn-icon {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 14px;
        }

        .btn-icon:hover {
            background: var(--border-color);
            color: var(--text-primary);
        }


        .event-list {
            margin-top: 12px;
        }

        .round-marker {
            font-size: 11px;
            font-weight: 600;
            color: var(--text-secondary);
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-top: 8px;
            margin-bottom: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .round-marker:first-child {
            border-top: none;
            margin-top: 0;
        }

        .round-badge {
            background-color: #fbbf24;
            color: #000000;
            font-weight: 700;
            padding: 4px 12px;
            border-radius: 6px;
            font-size: 12px;
            display: inline-block;
        }

        .round-actions {
            display: flex;
            gap: 4px;
        }

        .round-action-btn {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
        }

        .round-action-btn:hover {
            background: var(--border-color);
            color: var(--text-primary);
        }

        .event-item {
            display: flex;
            gap: 12px;
            padding: 10px;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.2s ease;
            margin-bottom: 4px;
            position: relative;
        }

        .event-item:hover {
            background: var(--border-color);
        }

        .event-item:hover .event-actions {
            opacity: 1;
        }

        .event-actions {
            position: absolute;
            right: 8px;
            top: 8px;
            display: flex;
            gap: 4px;
            opacity: 0;
            transition: opacity 0.2s ease;
        }

        .event-action-btn {
            background: var(--bg-primary);
            border: none;
            color: var(--text-secondary);
            cursor: pointer;
            padding: 4px 6px;
            border-radius: 4px;
            font-size: 10px;
        }

        .event-action-btn:hover {
            background: var(--border-color);
            color: var(--text-primary);
        }

        .event-action-btn.delete:hover {
            color: var(--brand-red);
        }

        .event-time {
            font-size: 12px;
            color: #3ea6ff;
            font-weight: 500;
            min-width: 55px;
            text-align: center;
        }

        .event-label {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;
        }

        .event-meta {
            font-size: 12px;
            color: var(--text-secondary);
            line-height: 1.4;
        }

        .pill {
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .pill-blue {
            background: #3b82f6;
            color: white;
        }

        .pill-red {
            background: #ef4444;
            color: white;
        }

        /* ===== Coach Review Tab Specific Styles ===== */
        #tab-review .event-item {
            position: relative;
            display: block;
            padding: 10px;
            margin-bottom: 4px;
            border-radius: 8px;
            background: transparent;
            border: none;
            transition: background 0.2s ease;
        }

        #tab-review .event-item:hover {
            background: var(--border-color);
            transform: none;
            box-shadow: none;
        }

        .review-primary-row {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 4px;
            padding: 0;
            background: transparent;
            border: none;
            border-radius: 0;
        }

        .review-primary-row .emoji {
            font-size: 16px;
            line-height: 1;
            flex-shrink: 0;
        }

        .review-time {
            font-size: 12px;
            font-weight: 500;
            color: #3ea6ff;
            line-height: 1.2;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .review-content {
            margin-left: 0;
        }

        .review-note-title {
            color: var(--text-primary);
            font-size: 14px;
            font-weight: 700;
            line-height: 1.35;
            margin: 0;
        }

        .review-author-bar {
            margin-top: 4px;
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--text-secondary);
            font-size: 12px;
            line-height: 1.3;
        }

        .review-author-avatar {
            width: 14px;
            height: 14px;
            border-radius: 50%;
            object-fit: cover;
            border: 1px solid rgba(255, 255, 255, 0.25);
            flex-shrink: 0;
        }

        .review-author-name {
            color: var(--text-primary);
            font-size: 12px;
            font-weight: 500;
        }

        .review-note-text {
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 400;
        }

        #tab-review .event-item .event-actions {
            top: 8px;
            right: 8px;
        }

        /* ===== Match Modal Styles ===== */
        .match-modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.85);
            backdrop-filter: blur(8px);
            z-index: 9999;
            align-items: center;
            justify-content: center;
        }

        .match-modal-overlay.active {
            display: flex;
        }

        .match-modal-content {
            background: linear-gradient(145deg, rgba(30, 30, 38, 0.95), rgba(24, 24, 31, 0.96));
            border-radius: 16px;
            padding: 18px;
            width: 92%;
            max-width: 420px;
            max-height: 85vh;
            overflow-y: auto;
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 14px 36px rgba(0, 0, 0, 0.45);
        }

        .match-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .match-modal-header h3 {
            font-size: 16px;
            font-weight: 700;
            margin: 0;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #f8fafc;
            background: none;
            -webkit-text-fill-color: initial;
        }

        .modal-title-icon {
            width: 22px;
            height: 22px;
            border-radius: 999px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            background: rgba(239, 68, 68, 0.16);
            color: #fda4af;
            border: 1px solid rgba(239, 68, 68, 0.35);
        }

        .match-modal-close {
            background: transparent;
            border: none;
            color: var(--text-secondary);
            font-size: 24px;
            cursor: pointer;
            padding: 0;
            line-height: 1;
        }

        .match-modal-close:hover {
            color: var(--text-primary);
        }

        .match-form-group {
            margin-bottom: 16px;
        }

        .match-form-group label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 6px;
            color: var(--text-primary);
        }

        .match-form-group input,
        .match-form-group select,
        .match-form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: var(--bg-primary);
            color: var(--text-primary);
            font-size: 14px;
        }

        .match-form-group input:focus,
        .match-form-group select:focus,
        .match-form-group textarea:focus {
            outline: none;
            border-color: var(--brand-red);
        }

        .match-form-row {
            display: flex;
            gap: 8px;
            margin-bottom: 10px;
        }

        .match-form-row .match-form-group {
            flex: 1;
        }

        .match-form-row .form-group {
            flex: 1;
        }

        .match-form-row .form-group label {
            display: block;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 5px;
            color: #d1d5db;
            letter-spacing: 0.2px;
        }

        .match-form-row .form-group input,
        .match-form-row .form-group select,
        .match-form-row .form-group textarea {
            width: 100%;
            padding: 9px 11px;
            border: 1px solid rgba(255, 255, 255, 0.14);
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.04);
            color: var(--text-primary);
            font-size: 13px;
            transition: all 0.2s ease;
            box-sizing: border-box;
            backdrop-filter: blur(8px);
        }

        .match-form-row .form-group input:hover,
        .match-form-row .form-group select:hover,
        .match-form-row .form-group textarea:hover {
            border-color: rgba(255, 255, 255, 0.2);
            background: rgba(255, 255, 255, 0.06);
        }

        .match-form-row .form-group input:focus,
        .match-form-row .form-group select:focus,
        .match-form-row .form-group textarea:focus {
            outline: none;
            border-color: var(--brand-red);
            box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.12);
            background: rgba(255, 255, 255, 0.08);
        }

        /* Premium form input styles */
        .match-form-group input,
        .match-form-group select,
        .match-form-group textarea {
            width: 100%;
            padding: 9px 11px;
            border: 1px solid rgba(255, 255, 255, 0.14);
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.04);
            color: var(--text-primary);
            font-size: 13px;
            transition: all 0.2s ease;
            box-sizing: border-box;
            backdrop-filter: blur(8px);
        }

        .match-form-group input:hover,
        .match-form-group select:hover,
        .match-form-group textarea:hover {
            border-color: rgba(255, 255, 255, 0.15);
            background: rgba(255, 255, 255, 0.05);
            transform: translateY(-1px);
        }

        .match-form-group input:focus,
        .match-form-group select:focus,
        .match-form-group textarea:focus {
            outline: none;
            border-color: var(--brand-red);
            box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.15),
                0 8px 25px rgba(239, 68, 68, 0.1);
            background: rgba(255, 255, 255, 0.08);
            transform: translateY(-2px);
        }

        .match-form-group textarea {
            resize: vertical;
            min-height: 72px;
            font-family: inherit;
        }

        .match-form-group label {
            display: block;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 5px;
            color: #d1d5db;
            letter-spacing: 0.2px;
        }

        /* Emoji option buttons (coach notes modal) */
        .emoji-options {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .emoji-option-btn {
            border: 1px solid rgba(255, 255, 255, 0.18);
            background: rgba(255, 255, 255, 0.05);
            color: #fff;
            border-radius: 10px;
            padding: 8px 10px;
            font-size: 18px;
            line-height: 1;
            cursor: pointer;
            transition: all 0.2s ease;
            min-width: 42px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .emoji-option-btn:hover {
            border-color: rgba(248, 113, 113, 0.55);
            background: rgba(239, 68, 68, 0.12);
            transform: translateY(-1px);
        }

        .emoji-option-btn.active {
            border-color: rgba(248, 113, 113, 0.7);
            background: rgba(239, 68, 68, 0.2);
            box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.15);
        }

        /* Comment timestamp badge */
        .comment-time-badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 2px 7px;
            border-radius: 999px;
            background: rgba(62, 166, 255, 0.15);
            border: 1px solid rgba(62, 166, 255, 0.4);
            color: #7dd3fc;
            font-weight: 600;
            font-size: 12px;
            line-height: 1.2;
            cursor: pointer;
            text-decoration: none;
            user-select: none;
            margin: 0 2px;
            transition: all 0.2s ease;
        }

        .comment-time-badge:hover {
            background: rgba(62, 166, 255, 0.26);
            border-color: rgba(125, 211, 252, 0.8);
            color: #e0f2fe;
            transform: translateY(-1px);
        }

        /* Custom scrollbar for modals - blended & subtle */
        .match-modal-content::-webkit-scrollbar {
            width: 4px;
        }

        .match-modal-content::-webkit-scrollbar-track {
            background: transparent;
            border-radius: 2px;
        }

        .match-modal-content::-webkit-scrollbar-thumb {
            background: rgba(255, 255, 255, 0.2);
            border-radius: 2px;
        }

        .match-modal-content::-webkit-scrollbar-thumb:hover {
            background: rgba(255, 255, 255, 0.35);
        }

        /* Hide scrollbar for Firefox */
        .match-modal-content {
            scrollbar-width: thin;
            scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
        }

        /* Modal responsive */
        @media (max-width: 500px) {
            .match-modal-content {
                width: calc(100% - 16px);
                max-width: none;
                padding: 14px;
                border-radius: 14px;
            }

            .match-modal-header h3 {
                font-size: 15px;
            }

            .match-form-row {
                flex-direction: column;
                gap: 6px;
                margin-bottom: 8px;
            }

            .match-form-group {
                margin-bottom: 10px;
            }

            .match-modal-actions {
                gap: 6px;
                margin-top: 10px;
                padding-top: 8px;
            }

            .match-btn-cancel,
            .match-btn-save {
                font-size: 11px;
                padding: 8px 10px;
            }
        }

        .match-modal-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 20px;
        }

        .match-modal-actions {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
            margin-top: 14px;
            padding-top: 10px;
            border-top: 1px solid rgba(255, 255, 255, 0.08);
        }

        .match-btn-cancel {
            background: rgba(255, 255, 255, 0.06);
            border: 1px solid rgba(255, 255, 255, 0.18);
            color: #e5e7eb;
            padding: 8px 12px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.2s ease;
            line-height: 1;
        }

        .match-btn-cancel:hover {
            background: rgba(255, 255, 255, 0.11);
            border-color: rgba(255, 255, 255, 0.24);
        }

        .match-btn-save {
            background: linear-gradient(135deg, #ef4444, #f87171);
            border: 1px solid rgba(248, 113, 113, 0.5);
            color: #fff;
            padding: 8px 13px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 700;
            transition: all 0.2s ease;
            line-height: 1;
            box-shadow: 0 6px 16px rgba(239, 68, 68, 0.25);
        }

        .match-btn-save:hover {
            filter: brightness(1.04);
            transform: translateY(-1px);
        }

        .match-btn-delete {
            background: rgba(239, 68, 68, 0.1);
            border: 2px solid var(--brand-red);
            color: var(--brand-red);
            padding: 14px 28px;
            border-radius: 14px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.3s ease;
            flex: 1;
            max-width: 140px;
        }

        .match-btn-delete:hover {
            background: var(--brand-red);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(239, 68, 68, 0.3);
        }

        .delete-confirm-message {
            color: var(--text-primary);
            font-size: 14px;
            line-height: 1.5;
            margin-bottom: 6px;
        }

        .delete-confirm-sub {
            color: var(--text-secondary);
            font-size: 12px;
            margin-bottom: 2px;
        }

        /* ===== Responsive ===== */
        @media (max-width: 1300px) {
            .yt-sidebar-container {
                width: 300px;
            }

            .events-sidebar {
                width: 300px;
            }
        }

        @media (max-width: 991px) {
            .yt-main {
                margin-left: 0;
                flex-direction: column;
            }

            .yt-sidebar-container,
            .events-sidebar {
                width: 100%;
            }

            .sidebar-video-card {
                flex-direction: column;
            }

            .sidebar-thumb {
                width: 100%;
            }

            .video-layout-container {
                flex-direction: column !important;
            }

            .yt-video-section {
                width: 100% !important;
                flex: none !important;
            }

            .yt-sidebar-container {
                width: 100% !important;
                margin-top: 16px;
            }

            .fighters-row {
                grid-template-columns: 1fr !important;
            }

            .match-center {
                order: -1;
            }

            .event-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .event-header-actions {
                align-self: flex-end;
                width: 100%;
                justify-content: flex-end;
            }
        }

        @media (max-width: 576px) {
            .video-stats-row {
                flex-direction: column;
                align-items: flex-start;
            }

            .video-actions {
                width: 100%;
                overflow-x: auto;
                justify-content: flex-start;
            }

            .video-container {
                max-height: 50vh !important;
                border-radius: 0 !important;
            }

            .video-container video {
                object-fit: contain !important;
            }

            .video-title {
                font-size: 16px !important;
                margin: 12px 0 6px !important;
            }

            .channel-row {
                flex-direction: column;
                align-items: flex-start !important;
                gap: 12px;
            }

            .channel-info {
                width: 100%;
            }

            .subscribe-btn {
                width: 100%;
            }

            .description-panel {
                padding: 8px !important;
            }

            .match-card {
                padding: 12px !important;
            }

            .event-header {
                padding: 8px 0;
            }

            .event-text .title {
                font-size: 1.1rem;
            }

            .event-header-actions {
                gap: 4px;
            }

            .event-header-actions .action-btn {
                padding: 6px 10px;
                font-size: 0.75rem;
            }
        }
    </style>
@endsection

@section('content')
    @php
        // ===== DUMMY DATA FALLBACKS =====
        $blueFighter =
            $blueFighter ??
            (object) [
                'name' => 'Sami Al Manea',
                'flag' => 'bh',
                'photo' => 'https://takeone-dev.innovator.bh/storage/images/profiles/profile_5.png?v=1773157950',
                'team' => 'Emperor TaeKwonDo Academy',
                'country' => 'Bahrain',
                'logo' => 'https://takeone-dev.innovator.bh/storage/clubs/1/branding/logo_1771488666.png',
                'member_id' => 5,
                'club_url' => 'https://takeone-dev.innovator.bh/mobile/eta',
            ];
        $redFighter =
            $redFighter ??
            (object) [
                'name' => 'Hassan Al Shallan',
                'flag' => 'bh',
                'photo' => 'https://takeone-dev.innovator.bh/storage/images/profiles/profile_11.png?t=1773268056907',
                'team' => 'Legend TaeKwonDo Academy',
                'country' => 'Bahrain',
                'logo' => 'https://takeone-dev.innovator.bh/storage/clubs/logos/logo_1773267551.png',
                'member_id' => 11,
                'club_url' => 'https://takeone-dev.innovator.bh/clubs/legend-taekwondo-academy',
            ];
        $match =
            $match ??
            (object) [
                'number' => '103',
                'court' => '2',
                'weight_category' => 'U18',
                'score_blue' => 7,
                'score_red' => 5,
                'features' =>
                    'Electronic scoring system (PSS & head‑gear) • Video replay available for head kicks and gam-jeom appeals',
            ];
        $referee =
            $referee ??
            (object) [
                'name' => 'Ghassan Yusuf',
                'flag' => 'bh',
                'photo' => 'https://takeone-dev.innovator.bh/storage/images/profiles/profile_8.png?t=1773267305519',
                'member_id' => 4,
            ];
        $championship =
            $championship ??
            (object) [
                'name' => 'Championship 2026',
                'url' => '/championship/2026',
            ];
        $venue =
            $venue ??
            (object) [
                'name' => 'Manama Sports Hall',
                'map_link' => 'https://maps.google.com/?q=Manama+Sports+Hall+Bahrain',
            ];
    @endphp

    <!-- Video Layout Container -->
    <div class="video-layout-container" style="display: flex; gap: 24px; max-width: 1800px; margin: 0 auto;">
        <!-- Video Section -->
        <div class="yt-video-section">
            <!-- Video Player -->
            <x-video-player :video="$video"
                :next-video="$nextVideo ?? null"
                :previous-video="$previousVideo ?? null"
                :playlist="$playlist ?? null"
                :playlist-videos="$playlistVideos ?? null">
                <x-slot:overlay>
                    {{-- Match highlights toggle --}}
                    <button class="match-highlights-toggle" id="matchHighlightsToggle" title="Toggle Match Highlights">
                        <span>Highlights</span>
                    </button>
                    {{-- Coach note overlay (subtitle-style) --}}
                    <div class="coach-note-overlay" id="coachNoteOverlay"></div>
                </x-slot:overlay>
            </x-video-player>

            <!-- ===== EVENT HEADER ===== -->
            <div class="event-header">
                <div class="event-header-left">
                    <div class="event-logo">
                        <img src="https://picsum.photos/seed/event-logo/200/200" alt="Event logo">
                    </div>
                    <div class="event-text">
                        <!-- Title with Trophy Icon BEFORE "Taekwondo Finals" -->
                        <h1 class="title">
                            <i class="bi bi-trophy trophy-icon" title="Match Type"></i>
                            <span>{{ $video->title }} –</span>
                            <span style="color: #2563eb; font-weight: bold">
                                <span class="fi fi-{{ $blueFighter->flag ?? 'bh' }}" style="width:20px;height:15px;border-radius:2px;display:inline-block;vertical-align:middle;"></span>
                                <a href="https://takeone-dev.innovator.bh/member/{{ $blueFighter->member_id ?? 5 }}"
                                    title="View {{ $blueFighter->name ?? 'Sami Al Manea' }}'s profile">
                                    {{ $blueFighter->name ?? 'Sami Al Manea' }}
                                </a>
                            </span>
                            <span>vs</span>
                            <span style="color: #ef4444; font-weight: bold">
                                <span class="fi fi-{{ $redFighter->flag ?? 'bh' }}" style="width:20px;height:15px;border-radius:2px;display:inline-block;vertical-align:middle;"></span>
                                <a href="https://takeone-dev.innovator.bh/member/{{ $redFighter->member_id ?? 11 }}"
                                    title="View {{ $redFighter->name ?? 'Hassan Al Shallan' }}'s profile">
                                    {{ $redFighter->name ?? 'Hassan Al Shallan' }}
                                </a>
                            </span>
                            <span>({{ $match->weight_category ?? 'U18' }})</span>
                        </h1>

                        <!-- Meta: Championship Link • Match# • Court • Referee (all inline) -->
                        <a class="meta-link" href="{{ $championship->url ?? '/championship/2026' }}"
                            style="white-space: nowrap; display: inline-flex; align-items: center; gap: 4px; flex-wrap: wrap; line-height: 1.4;">
                            <span
                                style="color: #ffffff; font-weight: bold; font-size: 0.85rem;">{{ $championship->name ?? 'Championship 2026' }}</span>
                            <span style="color: var(--text-secondary);">•</span>
                            <span style="color: #ff00dd; font-weight: bold; font-size: 0.85rem;">Match#
                                {{ $match->number ?? '103' }}</span>
                            <span style="color: var(--text-secondary);">•</span>
                            <span style="color: #00af09; font-weight: bold; font-size: 0.85rem;">Court
                                {{ $match->court ?? '2' }}</span>
                            <span style="color: var(--text-secondary);">•</span>
                            <span
                                style="color: #ffd900; font-weight: bold; font-size: 0.85rem; display: inline-flex; align-items: center; gap: 2px;">
                                <span class="fi fi-{{ $referee->flag ?? 'bh' }}" style="width:20px;height:15px;border-radius:2px;display:inline-block;vertical-align:middle;"></span> {{ $referee->name ?? 'Ghassan Yusuf' }}
                            </span>
                            <span
                                style="color: var(--text-secondary); font-weight: bold; font-size: 0.85rem; display: inline-flex; align-items: center; gap: 2px;">
                                - {{ number_format($video->view_count) }} views •
                                {{ $video->created_at->format('M d, Y') }}</span>
                        </a>
                    </div>
                </div>

                <x-video-actions :video="$video" />
            </div>
            <!-- ===== END EVENT HEADER ===== -->

            @include('videos.partials.description-box', ['video' => $video])

            {{-- ---- legacy match description panel (kept for reference, hidden) ---- --}}
            @if (false && isset($video) && $video->description)
                @php
                    $fullDescription = $video->description;
                    $shortDescription = Str::limit($fullDescription, 200);
                    $needsExpand = strlen($fullDescription) > 200;
                @endphp

                <section class="description-panel">
                    <button class="description-toggle" type="button" id="toggleDescription">
                        <span id="descriptionToggleLabel">
                            {{ $needsExpand ? 'Show description' : 'Hide description' }}
                        </span>
                        <span id="descriptionToggleIcon">{{ $needsExpand ? '▼' : '▲' }}</span>
                    </button>

                    <div class="description-body {{ $needsExpand ? '' : 'open' }}" id="descriptionBody">
                        <!-- Match Card -->
                        <section class="match-card">
                            <div class="match-header">
                                <div class="match-label">Final • Male -63kg division</div>
                            </div>

                            <div class="fighters-row">
                                <!-- Blue Fighter (Sami Al Manea) -->
                                <article class="fighter-card">
                                    <div class="fighter-top">
                                        <!-- Fighter Photo - Links to Member Profile -->
                                        <a href="https://takeone-dev.innovator.bh/member/{{ $blueFighter->member_id ?? 5 }}"
                                            title="View {{ $blueFighter->name ?? 'Sami Al Manea' }}'s profile"
                                            style="text-decoration: none; color: inherit;">
                                            <div class="fighter-photo">
                                                <img src="{{ $blueFighter->photo ?? 'https://picsum.photos/seed/blue-competitor/200/260' }}"
                                                    alt="{{ $blueFighter->name ?? 'Blue fighter' }}">
                                            </div>
                                        </a>
                                        <div style="display: flex; flex-direction: column; align-items: center; gap: 8px;">
                                            <!-- Fighter Logo - Links to Club Page -->
                                            <a href="{{ $blueFighter->club_url ?? 'https://takeone-dev.innovator.bh/mobile/eta' }}"
                                                title="View {{ $blueFighter->team ?? 'Emperor TaeKwonDo Academy' }}"
                                                style="text-decoration: none; color: inherit;">
                                                <div class="fighter-logo">
                                                    <img src="{{ $blueFighter->logo ?? 'https://picsum.photos/seed/blue-logo/160/160' }}"
                                                        alt="{{ $blueFighter->team ?? 'Blue team' }} logo">
                                                </div>
                                            </a>
                                            <span class="fighter-badge blue">Blue</span>
                                        </div>
                                    </div>
                                    <div class="fighter-info">
                                        <!-- Fighter Name - Links to Member Profile -->
                                        <div class="fighter-name blue-corner">
                                            <a href="https://takeone-dev.innovator.bh/member/{{ $blueFighter->member_id ?? 5 }}"
                                                title="View {{ $blueFighter->name ?? 'Sami Al Manea' }}'s profile">
                                                {{ $blueFighter->name ?? 'Sami Al Manea' }}
                                            </a>
                                        </div>
                                        <!-- Fighter Team - Links to Club Page -->
                                        <div class="fighter-team">
                                            <a href="{{ $blueFighter->club_url ?? 'https://takeone-dev.innovator.bh/mobile/eta' }}"
                                                title="View {{ $blueFighter->team ?? 'Emperor TaeKwonDo Academy' }}">
                                                {{ $blueFighter->team ?? 'Emperor TaeKwonDo Academy' }}
                                            </a>
                                        </div>
                                        <div class="fighter-country">
                                            <span class="fighter-country-flag"><span class="fi fi-{{ $blueFighter->flag ?? 'bh' }}" style="width:20px;height:15px;border-radius:2px;display:inline-block;vertical-align:middle;"></span></span>
                                            <span>{{ $blueFighter->country ?? 'Bahrain' }}</span>
                                        </div>
                                    </div>
                                </article>

                                <!-- Score & Referee Center -->
                                <div class="match-center">
                                    <div class="score-pill">
                                        <span class="score-number">{{ $match->score_blue ?? 7 }}</span>
                                        <span class="score-label">Final score</span>
                                        <span class="score-number">{{ $match->score_red ?? 5 }}</span>
                                    </div>
                                    <div class="referee-block">
                                        <!-- Referee Photo - Links to Member Profile -->
                                        <a href="https://takeone-dev.innovator.bh/member/{{ $referee->member_id ?? 4 }}"
                                            title="View {{ $referee->name ?? 'Ghassan Yusuf' }}'s profile"
                                            style="text-decoration: none; color: inherit;">
                                            <div class="referee-photo">
                                                <img src="{{ $referee->photo ?? 'https://picsum.photos/seed/referee/200/260' }}"
                                                    alt="Referee">
                                            </div>
                                        </a>
                                        <div style="color: #ffd900; font-weight: bold">
                                            <a href="https://takeone-dev.innovator.bh/member/{{ $referee->member_id ?? 4 }}"
                                                style="color: inherit; text-decoration: none;"
                                                title="View {{ $referee->name ?? 'Ghassan Yusuf' }}'s profile">
                                                {{ $referee->name ?? 'Ghassan Yusuf' }}
                                            </a>
                                        </div>
                                        <div class="ref-label">Center Referee</div>
                                    </div>
                                </div>

                                <!-- Red Fighter (Hassan Al Shallan) -->
                                <article class="fighter-card">
                                    <div class="fighter-top">
                                        <div style="display: flex; flex-direction: column; align-items: center; gap: 8px;">
                                            <!-- Fighter Logo - Links to Club Page -->
                                            <a href="{{ $redFighter->club_url ?? 'https://takeone-dev.innovator.bh/clubs/legend-taekwondo-academy' }}"
                                                title="View {{ $redFighter->team ?? 'Legend TaeKwonDo Academy' }}"
                                                style="text-decoration: none; color: inherit;">
                                                <div class="fighter-logo">
                                                    <img src="{{ $redFighter->logo ?? 'https://picsum.photos/seed/red-logo/160/160' }}"
                                                        alt="{{ $redFighter->team ?? 'Red team' }} logo">
                                                </div>
                                            </a>
                                            <span class="fighter-badge red">Red</span>
                                        </div>
                                        <!-- Fighter Photo - Links to Member Profile -->
                                        <a href="https://takeone-dev.innovator.bh/member/{{ $redFighter->member_id ?? 11 }}"
                                            title="View {{ $redFighter->name ?? 'Hassan Al Shallan' }}'s profile"
                                            style="text-decoration: none; color: inherit;">
                                            <div class="fighter-photo">
                                                <img src="{{ $redFighter->photo ?? 'https://picsum.photos/seed/red-competitor/200/260' }}"
                                                    alt="{{ $redFighter->name ?? 'Red fighter' }}">
                                            </div>
                                        </a>
                                    </div>
                                    <div class="fighter-info">
                                        <!-- Fighter Name - Links to Member Profile -->
                                        <div class="fighter-name red-corner">
                                            <a href="https://takeone-dev.innovator.bh/member/{{ $redFighter->member_id ?? 11 }}"
                                                title="View {{ $redFighter->name ?? 'Hassan Al Shallan' }}'s profile">
                                                {{ $redFighter->name ?? 'Hassan Al Shallan' }}
                                            </a>
                                        </div>
                                        <!-- Fighter Team - Links to Club Page -->
                                        <div class="fighter-team">
                                            <a href="{{ $redFighter->club_url ?? 'https://takeone-dev.innovator.bh/clubs/legend-taekwondo-academy' }}"
                                                title="View {{ $redFighter->team ?? 'Legend TaeKwonDo Academy' }}">
                                                {{ $redFighter->team ?? 'Legend TaeKwonDo Academy' }}
                                            </a>
                                        </div>
                                        <div class="fighter-country">
                                            <span class="fighter-country-flag"><span class="fi fi-{{ $redFighter->flag ?? 'bh' }}" style="width:20px;height:15px;border-radius:2px;display:inline-block;vertical-align:middle;"></span></span>
                                            <span>{{ $redFighter->country ?? 'Bahrain' }}</span>
                                        </div>
                                    </div>
                                </article>
                            </div>

                            <div class="match-footer">
                                <a class="hall-link" id="hallLink" title="View venue details"
                                    href="{{ $venue->map_link ?? 'https://maps.google.com/?q=Manama+Sports+Hall+Bahrain' }}"
                                    target="_blank" rel="noopener noreferrer">
                                    📍 {{ $venue->name ?? 'Manama Sports Hall' }}
                                </a>
                                @if (isset($match->features))
                                    • {{ $match->features }}
                                @endif
                            </div>
                        </section>

                        <!-- Match Overview -->
                        <section class="markdown-body">
                            <div
                                style="display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px;">
                                <h2 style="font-size: 1.05rem; margin: 0;">Match Overview</h2>
                                @if (isset($video) && $video->user)
                                    <div class="video-owner-badge"
                                        style="display: flex; align-items: center; gap: 6px; font-size: 0.8rem; color: var(--text-secondary);">
                                        <img src="{{ $video->user->avatar_url }}" class="owner-avatar"
                                            style="width: 20px; height: 20px; border-radius: 50%; object-fit: cover;"
                                            alt="{{ $video->user->name }}">
                                        <span class="owner-name"
                                            style="color: var(--text-primary); font-weight: 500;">{{ $video->user->name }}</span>
                                        <span>• {{ number_format($video->user->subscriber_count ?? 0) }} subscribers</span>
                                    </div>
                                @endif
                            </div>
                            <div class="description-text">
                                {!! Str::markdown($fullDescription) !!}
                            </div>
                        </section>
                    </div>
                </section>

            @endif

            {{-- Match Highlights toggle handler. MUST live OUTSIDE the disabled
                 @if(false ...) legacy panel above — otherwise the button never gets
                 its click listener and the Highlights pane can't be opened. --}}
            <script>
                // Match Highlights Toggle with localStorage persistence
                document.addEventListener('DOMContentLoaded', function() {
                    const toggleBtn = document.getElementById('matchHighlightsToggle');
                    const sidebar = document.querySelector('.events-sidebar');
                    // NOTE: emit videoId with the json Blade directive (raw), never with
                    // escaped echo braces — those HTML-escape the quotes and crash the script.
                    const videoId = @json(isset($video) ? $video->getRouteKey() : '');

                    if (toggleBtn && sidebar) {
                        // Load saved state on page load
                        const savedState = localStorage.getItem(`highlights_${videoId}`);
                        if (savedState === 'open') {
                            sidebar.classList.add('show');
                            toggleBtn.classList.add('expanded');
                            toggleBtn.textContent = 'Highlights';
                        }

                        toggleBtn.addEventListener('click', function() {
                            const isOpen = sidebar.classList.toggle('show');
                            toggleBtn.classList.toggle('expanded');

                            // Save state to localStorage
                            if (isOpen) {
                                localStorage.setItem(`highlights_${videoId}`, 'open');
                                toggleBtn.textContent = 'Highlights';
                            } else {
                                localStorage.removeItem(`highlights_${videoId}`);
                            }
                        });
                    }
                });
            </script>


            <x-video-comments :video="$video" />

        </div>

        <!-- Sidebar - Match Highlights -->
        <div class="yt-sidebar-container" style="display: flex; flex-direction: column; gap: 16px;">
            <aside class="events-sidebar">
                <div class="events-sidebar-header" style="justify-content: center;">
                    <h3>Match Highlights</h3>
                </div>
                <div class="tab-header">
                    <button class="tab-button active" data-tab="official">Points</button>
                    <button class="tab-button" data-tab="review">Coach review</button>
                </div>
                <div class="tab-panels">
                    <!-- Points Tab -->
                    <div class="tab-panel active" id="tab-official">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                            <div>
                                <div class="section-label">Rounds & points</div>
                            </div>
                            @auth
                                @if (isset($video) && Auth::id() === $video->user_id)
                                    <button class="action-btn action-btn-primary" type="button" onclick="openAddRoundModal()">
                                        <span>+</span> Add Round
                                    </button>
                                @endif
                            @endauth
                        </div>
                        <div class="event-list" id="officialEvents">
                            <!-- Round markers and points (unchanged) -->
                            <div class="round-marker" data-round="1">
                                <span class="round-badge">ROUND 1</span>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="round-actions">
                                            <button class="round-action-btn" onclick="openAddPointModal(1)"
                                                title="Add point">+</button>
                                            <button class="round-action-btn" onclick="editRound(1)"
                                                title="Edit round">✏️</button>
                                            <button class="round-action-btn" onclick="deleteRound(1)"
                                                title="Delete round">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="event-item" data-time-start="20" data-round="1" data-id="pt1">
                                <div class="event-time">@00:20</div>
                                <div>
                                    <div class="event-label">
                                        Blue body kick (1 pt)
                                        <span class="pill pill-blue">Blue</span>
                                    </div>
                                    <div class="event-meta">
                                        Round 1 • Score 1 – 0 • Clean contact.
                                    </div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editPoint('pt1')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deletePoint('pt1')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="event-item" data-time-start="45" data-round="1" data-id="pt2">
                                <div class="event-time">@00:45</div>
                                <div>
                                    <div class="event-label">
                                        Blue scores body kick
                                        <span class="pill pill-blue">Blue</span>
                                    </div>
                                    <div class="event-meta">
                                        Round 1 • Score 2 – 0 • Judge: Central.
                                    </div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editPoint('pt2')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deletePoint('pt2')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="round-marker" data-round="2">
                                <span class="round-badge">ROUND 2</span>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="round-actions">
                                            <button class="round-action-btn" onclick="openAddPointModal(2)"
                                                title="Add point">+</button>
                                            <button class="round-action-btn" onclick="editRound(2)"
                                                title="Edit round">✏️</button>
                                            <button class="round-action-btn" onclick="deleteRound(2)"
                                                title="Delete round">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="event-item" data-time-start="90" data-round="2" data-id="pt3">
                                <div class="event-time">@01:30</div>
                                <div>
                                    <div class="event-label">
                                        Red head kick (3 pts)
                                        <span class="pill pill-red">Red</span>
                                    </div>
                                    <div class="event-meta">
                                        Round 2 • Score 2 – 3 • Video replay requested.
                                    </div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editPoint('pt3')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deletePoint('pt3')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="round-marker" data-round="3">
                                <span class="round-badge">ROUND 3</span>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="round-actions">
                                            <button class="round-action-btn" onclick="openAddPointModal(3)"
                                                title="Add point">+</button>
                                            <button class="round-action-btn" onclick="editRound(3)"
                                                title="Edit round">✏️</button>
                                            <button class="round-action-btn" onclick="deleteRound(3)"
                                                title="Delete round">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="event-item" data-time-start="150" data-round="3" data-id="pt4">
                                <div class="event-time">@02:30</div>
                                <div>
                                    <div class="event-label">
                                        Blue spinning backfist (2 pts)
                                        <span class="pill pill-blue">Blue</span>
                                    </div>
                                    <div class="event-meta">
                                        Round 3 • Score 4 – 3 • Close round.
                                    </div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editPoint('pt4')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deletePoint('pt4')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="event-item" data-time-start="180" data-round="3" data-id="pt5">
                                <div class="event-time">@03:00</div>
                                <div>
                                    <div class="event-label">
                                        Red leg kick (1 pt)
                                        <span class="pill pill-red">Red</span>
                                    </div>
                                    <div class="event-meta">
                                        Round 3 • Score 4 – 4 • Tied!
                                    </div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editPoint('pt5')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deletePoint('pt5')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                        </div>
                    </div>

                    <!-- Coach Review Tab -->
                    <div class="tab-panel" id="tab-review">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
                            <div class="section-label">Private notes</div>
                            @auth
                                @if (isset($video) && Auth::id() === $video->user_id)
                                    <button class="action-btn action-btn-primary" type="button" onclick="openAddReviewModal()">
                                        <span>+</span> Add Note
                                    </button>
                                @endif
                            @endauth
                        </div>
                        <div class="event-list" id="reviewEvents">
                            <div class="event-item" data-time-start="32" data-time-end="50" data-id="rev1">
                                <div class="review-primary-row">
                                    <span class="emoji">🔥</span>
                                    <span>@00:32–00:50</span>
                                    <div class="note-text">Good pressure, but guard too low after first kick</div>
                                </div>
                                <div class="review-secondary-row">
                                    <div class="comment-avatar">
                                        <img src="https://picsum.photos/seed/coach-ahmed/80/80" alt="Coach Ahmed">
                                    </div>
                                    <div class="coach-name">Coach Ahmed</div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editReview('rev1')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deleteReview('rev1')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="event-item" data-time-start="125" data-time-end="140" data-id="rev2">
                                <div class="review-primary-row">
                                    <span class="emoji">🤔</span>
                                    <span class="review-time">@02:05-02:20</span>
                                </div>
                                <div class="review-content">
                                    <h4 class="review-note-title">Missed counter opportunity</h4>
                                    <div class="review-author-bar">
                                        <img class="review-author-avatar"
                                            src="https://picsum.photos/seed/coach-sara/80/80" alt="Coach Sara">
                                        <span class="review-author-name">Coach Sara</span>
                                        <span>•</span>
                                        <span class="review-note-text">Great angle, but no follow up.</span>
                                    </div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editReview('rev2')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deleteReview('rev2')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                            <div class="event-item" data-time-start="205" data-id="rev3">
                                <div class="review-primary-row">
                                    <span class="emoji">😄</span>
                                    <span class="review-time">@03:25</span>
                                </div>
                                <div class="review-content">
                                    <h4 class="review-note-title">Excellent angle change and follow-up</h4>
                                    <div class="review-author-bar">
                                        <img class="review-author-avatar"
                                            src="https://picsum.photos/seed/coach-ahmed/80/80" alt="Coach Ahmed">
                                        <span class="review-author-name">Coach Ahmed</span>
                                        <span>•</span>
                                        <span class="review-note-text">Ideal example of exit and re-entry.</span>
                                    </div>
                                </div>
                                @auth
                                    @if (isset($video) && Auth::id() === $video->user_id)
                                        <div class="event-actions">
                                            <button class="event-action-btn" onclick="editReview('rev3')"
                                                title="Edit">✏️</button>
                                            <button class="event-action-btn delete" onclick="deleteReview('rev3')"
                                                title="Delete">🗑️</button>
                                        </div>
                                    @endif
                                @endauth
                            </div>
                        </div>
                    </div>
                </div>
            </aside>

            <!-- Sidebar - Up Next / Recommendations -->
            <div class="yt-sidebar-container">
                @if ($playlist && $playlistVideos && $playlistVideos->count() > 0)
                    <h3 style="font-size: 16px; font-weight: 500; margin-bottom: 8px;">
                        <i class="bi bi-collection-play" style="margin-right: 8px;"></i>
                        {{ $playlist->name }}
                        <span
                            style="font-weight: 400; color: var(--text-secondary); font-size: 14px;">({{ $playlistVideos->count() }}
                            videos)</span>
                    </h3>

                    {{-- Playlist controls --}}
                    <div class="pl-controls-bar">
                        <button class="pl-ctrl-btn" id="plPrevBtn" title="Previous" onclick="window.plPrev()">
                            <i class="bi bi-skip-start-fill"></i>
                        </button>
                        <button class="pl-ctrl-btn" id="plNextBtn" title="Next" onclick="window.plNext()">
                            <i class="bi bi-skip-end-fill"></i>
                        </button>
                        <div class="pl-ctrl-divider"></div>
                        <button class="pl-ctrl-btn" id="plShuffleBtn" title="Shuffle" onclick="plToggleShuffle()">
                            <i class="bi bi-shuffle"></i>
                        </button>
                        <button class="pl-ctrl-btn" id="plLoopBtn" title="Loop" onclick="plToggleLoop()">
                            <i class="bi bi-repeat"></i>
                        </button>
                        <button class="pl-ctrl-btn pl-ctrl-autoplay" id="plAutoplayBtn" title="Autoplay" onclick="plToggleAutoplay()">
                            <i class="bi bi-play-circle"></i>
                            <span class="pl-autoplay-label">Autoplay</span>
                        </button>
                        <div class="pl-ctrl-divider"></div>
                        <button class="pl-ctrl-btn" id="plShareBtn" title="Share playlist"
                            onclick="openShareModal('{{ route('playlists.showByToken', $playlist->share_token) }}','{{ addslashes($playlist->name) }}','{{ route('playlists.recordShare', $playlist) }}','','')">
                            <i class="bi bi-share"></i>
                        </button>
                    </div>

                    <script>
                    (function () {
                    var PL_ID      = '{{ $playlist->share_token }}';
                    var PL_CURRENT = {{ $video->id }};
                    var PL_VIDEOS  = {!! $playlistVideos->map(fn($v) => ['id' => $v->id, 'url' => route('videos.show', $v).'?playlist='.$playlist->share_token])->values()->toJson() !!};

                    function plGet(k,d){ var v=localStorage.getItem('pl_'+k+'_'+PL_ID); return v!==null?v:d; }
                    function plSet(k,v){ localStorage.setItem('pl_'+k+'_'+PL_ID,v); }

                    var plAutoplay   = plGet('autoplay','1');
                    var plLoop       = plGet('loop','off');
                    var plShuffle    = plGet('shuffle','0');
                    var plTransiting = false;

                    function plShuffleOrder(){ var o=PL_VIDEOS.map(function(_,i){return i;}); for(var i=o.length-1;i>0;i--){var j=Math.floor(Math.random()*(i+1));var t=o[i];o[i]=o[j];o[j]=t;} localStorage.setItem('pl_shuffleOrder_'+PL_ID,JSON.stringify(o)); return o; }
                    function plGetOrder(){ var r=localStorage.getItem('pl_shuffleOrder_'+PL_ID); if(r){try{return JSON.parse(r);}catch(e){}} return null; }

                    function plAdj(curId) {
                        var idx=PL_VIDEOS.findIndex(function(v){ return v.id===curId; });
                        if(plShuffle==='1'){
                            var ord=plGetOrder()||plShuffleOrder();
                            var pos=ord.indexOf(idx);
                            var pp=pos>0?pos-1:(plLoop==='all'?ord.length-1:-1);
                            var np=pos<ord.length-1?pos+1:(plLoop==='all'?0:-1);
                            return { prev:pp>=0?PL_VIDEOS[ord[pp]].url:'', next:np>=0?PL_VIDEOS[ord[np]].url:'' };
                        }
                        return {
                            prev: idx>0?PL_VIDEOS[idx-1].url:'',
                            next: idx<PL_VIDEOS.length-1?PL_VIDEOS[idx+1].url:(plLoop==='all'?PL_VIDEOS[0].url:'')
                        };
                    }

                    function plFmt(s){ var m=Math.floor(s/60),ss=Math.floor(s%60); return m+':'+(ss<10?'0':'')+ss; }

                    async function plTransitionTo(url, pushHist) {
                        if(!url||plTransiting) return;
                        plTransiting=true;
                        if(window._spaScrollToVideo) window._spaScrollToVideo();
                        try {
                            var m=url.match(/\/videos\/([^/?#]+)/);
                            if(!m){ window.location.href=url; return; }
                            var qs=url.indexOf('?')!==-1?url.substring(url.indexOf('?')):'';
                            var resp;
                            try { resp=await fetch('/videos/'+m[1]+'/player-data'+qs); }
                            catch(e){ window.location.href=url; return; }
                            if(!resp.ok){ window.location.href=url; return; }
                            var d;
                            try { d=await resp.json(); }
                            catch(e){ window.location.href=url; return; }

                            // Different player type? Hard-nav so the correct view loads.
                            if (d.type && d.type !== 'match') { window.location.href = url; return; }

                            try { if(window._ytpLoadSource) window._ytpLoadSource(d.hls_url, d.stream_url); }
                            catch(e){ console.warn('_ytpLoadSource', e); }

                            var pl=document.getElementById('ytpPlayed'),sc=document.getElementById('ytpScrubber');
                            var cu=document.getElementById('ytpCurrent'),dr=document.getElementById('ytpDuration');
                            if(pl) pl.style.width='0%'; if(sc) sc.style.left='0%';
                            if(cu) cu.textContent='0:00'; if(dr&&d.duration) dr.textContent=plFmt(d.duration);

                            var ts=document.querySelector('.video-title span');
                            if(ts) ts.textContent=d.title;
                            document.title=d.title+' | {{ config("app.name") }}';

                            var vid=document.getElementById('videoPlayer');
                            if(vid) vid.loop=(plLoop==='one');

                            PL_CURRENT=d.id;
                            try { plRender(); plHighlight(d.id, true); } catch(e){ console.warn('plRender', e); }
                            if(pushHist!==false) history.pushState({plVideoId:d.id,url:url},'',url);

                            plSwapContent(url);
                        } catch(e){
                            console.warn('plTransitionTo',e);
                        } finally {
                            plTransiting=false;
                        }
                    }

                    async function plSwapContent(url) {
                        try {
                            var resp=await fetch(url,{headers:{'Accept':'text/html','X-Requested-With':'XMLHttpRequest'}});
                            var html=await resp.text();
                            var doc=new DOMParser().parseFromString(html,'text/html');

                            var nv=doc.getElementById('vdbWrap'),ov=document.getElementById('vdbWrap');
                            if(nv&&ov){ov.innerHTML=nv.innerHTML;if(window._vdbCheckOverflow)_vdbCheckOverflow();}

                            var nc=doc.querySelector('.channel-row'),oc=document.querySelector('.channel-row');
                            if(nc&&oc) oc.innerHTML=nc.innerHTML;

                            var ny=doc.getElementById('ytcSection'),oy=document.getElementById('ytcSection');
                            if(ny&&oy){
                                oy.innerHTML=ny.innerHTML;
                                var ytcScript=Array.from(doc.querySelectorAll('script')).find(function(s){return s.textContent.includes('const YTC =');});
                                if(ytcScript){
                                    var ns=document.createElement('script');
                                    ns.textContent=ytcScript.textContent;
                                    document.body.appendChild(ns);
                                    document.body.removeChild(ns);
                                }
                            }
                        } catch(e){ console.warn('plSwapContent',e); }
                    }

                    function plHighlight(activeId, scroll){
                        document.querySelectorAll('.sidebar-video-card[data-pl-id]').forEach(function(c){
                            c.classList.toggle('current-video',parseInt(c.dataset.plId)===activeId);
                        });
                        if(scroll){ var a=document.querySelector('.sidebar-video-card.current-video'); if(a) a.scrollIntoView({behavior:'smooth',block:'nearest'}); }
                    }

                    function plRender(){
                        var adj=plAdj(PL_CURRENT);
                        var sb=document.getElementById('plShuffleBtn'),lb=document.getElementById('plLoopBtn');
                        var ab=document.getElementById('plAutoplayBtn'),nb=document.getElementById('plNextBtn'),pb=document.getElementById('plPrevBtn');
                        if(sb){ sb.classList.toggle('pl-ctrl-active',plShuffle==='1'); sb.title='Shuffle: '+(plShuffle==='1'?'On':'Off'); }
                        if(lb){
                            lb.classList.remove('pl-ctrl-active');
                            if(plLoop==='all'){ lb.classList.add('pl-ctrl-active'); lb.innerHTML='<i class="bi bi-repeat"></i>'; lb.title='Loop: All'; }
                            else if(plLoop==='one'){ lb.classList.add('pl-ctrl-active'); lb.innerHTML='<i class="bi bi-repeat-1"></i>'; lb.title='Loop: One'; }
                            else { lb.innerHTML='<i class="bi bi-repeat"></i>'; lb.title='Loop: Off'; }
                        }
                        if(ab){ ab.classList.toggle('pl-ctrl-active',plAutoplay==='1'); ab.title='Autoplay: '+(plAutoplay==='1'?'On':'Off'); }
                        if(nb) nb.disabled=!adj.next;
                        if(pb) pb.disabled=!adj.prev;
                    }

                    window.plGoTo       = function(url){ if(url) plTransitionTo(url); };
                    window.plNext       = function(){ var a=plAdj(PL_CURRENT); if(a.next) plTransitionTo(a.next); };
                    window.plPrev       = function(){ var a=plAdj(PL_CURRENT); if(a.prev) plTransitionTo(a.prev); };
                    window.plToggleShuffle  = function(){ plShuffle=plShuffle==='1'?'0':'1'; plSet('shuffle',plShuffle); if(plShuffle==='1') plShuffleOrder(); else localStorage.removeItem('pl_shuffleOrder_'+PL_ID); plRender(); };
                    window.plToggleLoop     = function(){ var s=['off','all','one']; var i=s.indexOf(plLoop); plLoop=s[(i+1)%s.length]; plSet('loop',plLoop); plRender(); var v=document.getElementById('videoPlayer'); if(v) v.loop=(plLoop==='one'); };
                    window.plToggleAutoplay = function(){ plAutoplay=plAutoplay==='1'?'0':'1'; plSet('autoplay',plAutoplay); plRender(); };

                    window._ytpNavOverride = {
                        next: function(_url){ window.plNext(); },
                        prev: function(_url){ window.plPrev(); }
                    };
                    window._plOnVideoEnd = function(){ if(plLoop==='one') return; if(plAutoplay==='1') window.plNext(); };

                    window.addEventListener('popstate',function(e){ if(e.state&&e.state.url) plTransitionTo(e.state.url,false); });

                    function plInit(){
                        var v=document.getElementById('videoPlayer');
                        if(v&&plLoop==='one') v.loop=true;
                        plRender();
                        plHighlight(PL_CURRENT, false);
                    }
                    if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',plInit); else plInit();
                    })();
                    </script>

                    <div class="recommended-videos-list">
                        @foreach ($playlistVideos as $index => $playlistVideo)
                            @php $isCurrentTrack = $playlistVideo->id === $video->id; @endphp
                            <div class="sidebar-video-card{{ $isCurrentTrack ? ' current-video' : '' }}"
                                data-pl-id="{{ $playlistVideo->id }}"
                                onclick="plGoTo('{{ route('videos.show', $playlistVideo) }}?playlist={{ $playlist->share_token }}')"
                                style="cursor:pointer;">
                                <div class="sidebar-thumb" style="position: relative;">
                                    @if ($playlistVideo->thumbnail)
                                        <img src="{{ route('media.thumbnail', $playlistVideo->thumbnail) }}"
                                            alt="{{ $playlistVideo->title }}">
                                    @else
                                        <img src="https://picsum.photos/seed/{{ $playlistVideo->id }}/320/180"
                                            alt="{{ $playlistVideo->title }}">
                                    @endif
                                    @if ($playlistVideo->duration)
                                        <span
                                            class="yt-video-duration">{{ gmdate('i:s', $playlistVideo->duration) }}</span>
                                    @endif
                                    @if ($playlistVideo->is_shorts)
                                        <span class="yt-shorts-badge"
                                            style="position: absolute; top: 8px; left: 8px; font-size: 10px; padding: 2px 6px;">
                                            <i class="bi bi-collection-play-fill"></i> SHORTS
                                        </span>
                                    @endif
                                    <!-- Playlist position indicator -->
                                    <span
                                        style="position: absolute; bottom: 4px; left: 4px; background: rgba(0,0,0,0.8); color: white; padding: 2px 6px; border-radius: 4px; font-size: 12px; font-weight: 500;">
                                        {{ $index + 1 }}
                                    </span>
                                </div>
                                <div class="sidebar-info">
                                    <div class="sidebar-title">
                                        <i class="bi {{ match ($playlistVideo->type) {'music' => 'bi-music-note','match' => 'bi-trophy',default => 'bi-film'} }}"
                                            style="color: #ef4444; margin-right: 4px; font-size: 12px;"></i>
                                        {{ Str::limit($playlistVideo->title, 60) }}
                                    </div>
                                    <div class="sidebar-meta">
                                        <div>{{ $playlistVideo->user->name ?? 'Unknown' }}</div>
                                        <div>{{ number_format($playlistVideo->view_count) }} views •
                                            {{ $playlistVideo->created_at->diffForHumans() }}</div>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                    @if ($playlist->canEdit(Auth::user()))
                        <a href="{{ route('playlists.show', $playlist->id) }}" class="action-btn" style="margin-top: 12px;">
                            <i class="bi bi-pencil"></i> <span>Edit Playlist</span>
                        </a>
                    @endif
                @else
                    {{-- Up Next header + autoplay toggle --}}
                    <div style="display:flex; align-items:center; justify-content:space-between; margin-bottom:10px;">
                        <h3 style="font-size:16px; font-weight:500; margin:0;">
                            <i class="bi bi-collection-play" style="margin-right:6px;"></i>Up Next
                        </h3>
                        <div class="pl-controls-bar" style="margin-bottom:0; flex-shrink:0;">
                            <button class="pl-ctrl-btn pl-ctrl-autoplay" id="recAutoplayBtn"
                                title="Autoplay" onclick="recToggleAutoplay()">
                                <i class="bi bi-play-circle"></i>
                                <span class="pl-autoplay-label">Autoplay</span>
                            </button>
                        </div>
                    </div>

                    @if ($recommendedVideos && $recommendedVideos->count() > 0)
                        <div class="recommended-videos-list" id="recList">
                            @foreach ($recommendedVideos as $recVideo)
                                <div class="sidebar-video-card"
                                    data-rec-url="{{ route('videos.show', $recVideo) }}"
                                    onclick="recGoTo('{{ route('videos.show', $recVideo) }}')"
                                    style="cursor:pointer;">
                                    <div class="sidebar-thumb" style="position: relative;">
                                        @if ($recVideo->thumbnail)
                                            <img src="{{ route('media.thumbnail', $recVideo->thumbnail) }}"
                                                alt="{{ $recVideo->title }}">
                                        @else
                                            <img src="https://picsum.photos/seed/{{ $recVideo->id }}/320/180"
                                                alt="{{ $recVideo->title }}">
                                        @endif
                                        @if ($recVideo->duration)
                                            <span
                                                class="yt-video-duration">{{ gmdate('i:s', $recVideo->duration) }}</span>
                                        @endif
                                        @if ($recVideo->is_shorts)
                                            <span class="yt-shorts-badge"
                                                style="position: absolute; top: 8px; left: 8px; font-size: 10px; padding: 2px 6px;">
                                                <i class="bi bi-collection-play-fill"></i> SHORTS
                                            </span>
                                        @endif
                                    </div>
                                    <div class="sidebar-info">
                                        <div class="sidebar-title">
                                            @php $recFlag = \App\Data\Languages::flag($recVideo->language); @endphp
                                            <i class="bi {{ match ($recVideo->type) {'music' => 'bi-music-note','match' => 'bi-trophy',default => 'bi-film'} }}"
                                                style="color: #ef4444; margin-right: 4px; font-size: 12px;"></i>
                                            @if($recFlag)<span class="fi fi-{{ $recFlag }}" style="display:inline-block;width:16px;height:12px;border-radius:2px;vertical-align:middle;margin-right:4px;"></span>@endif
                                            {{ Str::limit($recVideo->title, 60) }}
                                        </div>
                                        <div class="sidebar-meta">
                                            <div>{{ $recVideo->user->name ?? 'Unknown' }}</div>
                                            <div>{{ number_format($recVideo->view_count) }} views •
                                                {{ $recVideo->created_at->diffForHumans() }}</div>
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <div class="text-secondary" id="recList">No recommendations available yet. Check back later!</div>
                    @endif

                    <script>
                    (function () {
                    var recTransiting = false;
                    var recAutoplay   = localStorage.getItem('ytpAutoplay_solo') !== '0';

                    // persists across sidebar swaps so already-autoplayed videos are not repeated
                    window._recWatched = window._recWatched || new Set();

                    function recFmt(s){ var m=Math.floor(s/60),ss=Math.floor(s%60); return m+':'+(ss<10?'0':'')+ss; }

                    function recNextUnwatched() {
                        var cards = document.querySelectorAll('#recList .sidebar-video-card[data-rec-url]');
                        for (var i = 0; i < cards.length; i++) {
                            if (!window._recWatched.has(cards[i].dataset.recUrl)) return cards[i];
                        }
                        return null;
                    }

                    function recRender() {
                        var btn = document.getElementById('recAutoplayBtn');
                        if (!btn) return;
                        btn.classList.toggle('pl-ctrl-active', recAutoplay);
                        btn.title = 'Autoplay: ' + (recAutoplay ? 'On' : 'Off');
                        // highlight the first unwatched card as "next up"
                        var cards = document.querySelectorAll('#recList .sidebar-video-card');
                        var nextUp = recNextUnwatched() || cards[0];
                        cards.forEach(function(c){ c.style.opacity = ''; c.classList.remove('rec-next-up'); });
                        if (recAutoplay && nextUp) { nextUp.style.opacity = '1'; nextUp.classList.add('rec-next-up'); }
                    }

                    window.recToggleAutoplay = function() {
                        recAutoplay = !recAutoplay;
                        localStorage.setItem('ytpAutoplay_solo', recAutoplay ? '1' : '0');
                        recRender();
                    };

                    async function recTransitionTo(url, pushHist) {
                        if (!url || recTransiting) return;
                        recTransiting = true;
                        if (window._spaScrollToVideo) window._spaScrollToVideo();
                        try {
                            var m = url.match(/\/videos\/([^/?#]+)/);
                            if (!m) { window.location.href = url; return; }
                            var resp = await fetch('/videos/' + m[1] + '/player-data');
                            if (!resp.ok) { window.location.href = url; return; }
                            var d = await resp.json();

                            // Different player type? Hard-nav so the correct view loads.
                            if (d.type && d.type !== 'match') { window.location.href = url; return; }

                            if (window._ytpLoadSource) window._ytpLoadSource(d.hls_url, d.stream_url);

                            var pl=document.getElementById('ytpPlayed'),sc=document.getElementById('ytpScrubber');
                            var cu=document.getElementById('ytpCurrent'),dr=document.getElementById('ytpDuration');
                            if(pl) pl.style.width='0%'; if(sc) sc.style.left='0%';
                            if(cu) cu.textContent='0:00'; if(dr&&d.duration) dr.textContent=recFmt(d.duration);

                            var ts = document.querySelector('.video-title span');
                            if (ts) ts.textContent = d.title;
                            document.title = d.title + ' | {{ config("app.name") }}';

                            if (pushHist !== false) history.pushState({recUrl: url}, '', url);

                            recSwapContent(url);
                        } catch(e) {
                            console.warn('recTransitionTo', e);
                            window.location.href = url;
                        } finally {
                            recTransiting = false;
                        }
                    }

                    async function recSwapContent(url) {
                        try {
                            var resp = await fetch(url, {headers:{'Accept':'text/html','X-Requested-With':'XMLHttpRequest'}});
                            var html = await resp.text();
                            var doc  = new DOMParser().parseFromString(html, 'text/html');

                            var nv=doc.getElementById('vdbWrap'),ov=document.getElementById('vdbWrap');
                            if(nv&&ov){ov.innerHTML=nv.innerHTML;if(window._vdbCheckOverflow)_vdbCheckOverflow();}

                            var nc=doc.querySelector('.channel-row'),oc=document.querySelector('.channel-row');
                            if(nc&&oc) oc.innerHTML=nc.innerHTML;

                            var ny=doc.getElementById('ytcSection'),oy=document.getElementById('ytcSection');
                            if(ny&&oy){
                                oy.innerHTML=ny.innerHTML;
                                var ytcScript=Array.from(doc.querySelectorAll('script')).find(function(s){return s.textContent.includes('const YTC =');});
                                if(ytcScript){
                                    var ns=document.createElement('script');
                                    ns.textContent=ytcScript.textContent;
                                    document.body.appendChild(ns);
                                    document.body.removeChild(ns);
                                }
                            }

                            var nSide=doc.querySelector('.yt-sidebar-container');
                            var oSide=document.querySelector('.yt-sidebar-container');
                            if(nSide&&oSide){
                                oSide.innerHTML=nSide.innerHTML;
                                Array.from(oSide.querySelectorAll('script')).forEach(function(s){
                                    var ns=document.createElement('script'); ns.textContent=s.textContent; document.body.appendChild(ns); document.body.removeChild(ns);
                                });
                            }
                        } catch(e){ console.warn('recSwapContent', e); }
                    }

                    // user manually picks a video — reset watch history so next autoplay starts fresh
                    window.recGoTo = function(url) {
                        if (!url) return;
                        window._recWatched = new Set();
                        recTransitionTo(url);
                    };

                    // autoplay: mark current video watched, then play first unwatched rec card
                    window._plOnVideoEnd = function() {
                        if (!recAutoplay) return;
                        window._recWatched.add(window.location.href);
                        var next = recNextUnwatched();
                        if (next) {
                            recTransitionTo(next.dataset.recUrl);
                        } else {
                            // all recommendations watched — notify and restart the cycle
                            showToast('All recommendations watched — starting over', 'info');
                            window._recWatched = new Set();
                            var first = document.querySelector('#recList .sidebar-video-card[data-rec-url]');
                            if (first) recTransitionTo(first.dataset.recUrl);
                        }
                    };

                    window.addEventListener('popstate', function(e){ if(e.state&&e.state.recUrl) recTransitionTo(e.state.recUrl,false); });

                    if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',recRender); else recRender();
                    })();
                    </script>
                @endif
            </div>

        </div>
    </div>

    <!-- Modals -->
    @include('layouts.partials.edit-video-modal')

    <!-- Add Round Modal -->
    <div class="match-modal-overlay" id="addRoundModal">
        <div class="match-modal-content">
            <div class="match-modal-header">
                <h3><span class="modal-title-icon">➕</span> Add New Round</h3>
                <button class="match-modal-close" onclick="closeModal('addRoundModal')">×</button>
            </div>
            <form id="addRoundForm">
                <div class="match-form-row">
                    <div class="match-form-group">
                        <label>Round Number</label>
                        <input type="number" id="roundNumber" min="1" required>
                    </div>
                    <div class="form-group">
                        <label>Round Name (optional)</label>
                        <input type="text" id="roundName" placeholder="e.g., ROUND 1">
                    </div>
                </div>
                <div class="match-form-group">
                    <label>Start Time (mm.ss, optional)</label>
                    <input type="text" id="roundStartTime" inputmode="decimal" placeholder="e.g., 1.30 = 1m 30s">
                </div>
                <div class="match-modal-actions">
                    <button type="button" class="match-btn-cancel" onclick="closeModal('addRoundModal')">Cancel</button>
                    <button type="submit" class="match-btn-save">Add Round</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Point Modal -->
    <div class="match-modal-overlay" id="pointModal">
        <div class="match-modal-content">
            <div class="match-modal-header">
                <h3 id="pointModalTitle">Add Point</h3>
                <button class="match-modal-close" onclick="closeModal('pointModal')">×</button>
            </div>
            <form id="pointForm">
                <input type="hidden" id="pointId">
                <input type="hidden" id="pointRoundId">
                <div class="match-form-row">
                    <div class="match-form-group">
                        <label for="pointTimestamp">Timestamp (mm.ss)</label>
                        <input type="text" id="pointTimestamp" inputmode="decimal" placeholder="e.g., 0.45 = 45s"
                            required>
                    </div>
                    <div class="match-form-group">
                        <label for="pointRoundSelect">Round</label>
                        <select id="pointRoundSelect">
                            <option value="1">Round 1</option>
                            <option value="2">Round 2</option>
                            <option value="3">Round 3</option>
                            <option value="4">Round 4</option>
                            <option value="5">Round 5</option>
                        </select>
                    </div>
                </div>
                <div class="match-form-group">
                    <label for="pointAction">Action Description</label>
                    <input type="text" id="pointAction" placeholder="e.g., Blue body kick" required>
                </div>
                <div class="match-form-row">
                    <div class="match-form-group">
                        <label for="pointValue">Points</label>
                        <input type="number" id="pointValue" min="1" value="1">
                    </div>
                    <div class="match-form-group">
                        <label for="pointCompetitor">Competitor</label>
                        <select id="pointCompetitor">
                            <option value="blue">Blue</option>
                            <option value="red">Red</option>
                        </select>
                    </div>
                </div>
                <div class="match-form-group">
                    <label for="pointNotes">Notes</label>
                    <textarea id="pointNotes" rows="3" placeholder="Optional notes (e.g., Clean contact, Judge: Central)"></textarea>
                </div>
                <div class="match-modal-actions">
                    <button type="button" class="match-btn-delete" id="deletePointBtn" onclick="confirmDeletePoint()"
                        style="display: none;">
                        Delete Point
                    </button>
                    <button type="button" class="match-btn-cancel" onclick="closeModal('pointModal')">
                        Cancel
                    </button>
                    <button type="submit" class="match-btn-save">
                        Save Point
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Round Modal -->
    <div class="match-modal-overlay" id="editRoundModal">
        <div class="match-modal-content">
            <div class="match-modal-header">
                <h3><span class="modal-title-icon">✏️</span> Edit Round</h3>
                <button class="match-modal-close" onclick="closeModal('editRoundModal')">×</button>
            </div>
            <form id="editRoundForm">
                <input type="hidden" id="editRoundId">
                <div class="match-form-group">
                    <label>Round Number</label>
                    <input type="number" id="editRoundNumber" min="1" required>
                </div>
                <div class="match-form-group">
                    <label>Round Name</label>
                    <input type="text" id="editRoundName" placeholder="e.g., ROUND 1" required>
                </div>
                <div class="match-form-group">
                    <label>Start Time (mm.ss, optional)</label>
                    <input type="text" id="editRoundStartTime" inputmode="decimal" placeholder="e.g., 2.05 = 2m 5s">
                </div>
                <div class="match-modal-actions">
                    <button type="button" class="match-btn-cancel"
                        onclick="closeModal('editRoundModal')">Cancel</button>
                    <button type="button" class="match-btn-save" onclick="confirmDeleteRound()">Delete Round</button>
                    <button type="submit" class="match-btn-save">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Review Modal -->
    <div class="match-modal-overlay" id="reviewModal">
        <div class="match-modal-content">
            <div class="match-modal-header">
                <h3 id="reviewModalTitle"><span class="modal-title-icon">📝</span> Add Coach Note</h3>
                <button class="match-modal-close" onclick="closeModal('reviewModal')">×</button>
            </div>
            <form id="reviewForm">
                <input type="hidden" id="reviewId">
                <div class="match-form-row">
                    <div class="match-form-group">
                        <label>Start Time (mm.ss)</label>
                        <input type="text" id="reviewStartTime" inputmode="decimal" placeholder="e.g., 0.32 = 32s"
                            required>
                    </div>
                    <div class="match-form-group">
                        <label>End Time (mm.ss)</label>
                        <input type="text" id="reviewEndTime" inputmode="decimal" placeholder="e.g., 0.50 = 50s">
                    </div>
                </div>
                <div class="match-form-group">
                    <label>Note</label>
                    <textarea id="reviewNote" rows="3" placeholder="Coach's observation..." required></textarea>
                </div>
                <div class="match-form-group">
                    <label>Coach Name</label>
                    <input type="text" id="reviewCoach" placeholder="e.g., Coach Ahmed" required>
                </div>
                <div class="match-form-group">
                    <label>Emoji</label>
                    <input type="hidden" id="reviewEmoji" value="🔥">
                    <div class="emoji-options" id="reviewEmojiOptions">
                        <button type="button" class="emoji-option-btn active" data-emoji="🔥"
                            onclick="setReviewEmoji('🔥', this)">🔥</button>
                        <button type="button" class="emoji-option-btn" data-emoji="🤔"
                            onclick="setReviewEmoji('🤔', this)">🤔</button>
                        <button type="button" class="emoji-option-btn" data-emoji="😄"
                            onclick="setReviewEmoji('😄', this)">😄</button>
                        <button type="button" class="emoji-option-btn" data-emoji="💪"
                            onclick="setReviewEmoji('💪', this)">💪</button>
                        <button type="button" class="emoji-option-btn" data-emoji="⚠️"
                            onclick="setReviewEmoji('⚠️', this)">⚠️</button>
                    </div>
                </div>
                <div class="match-modal-actions">
                    <button type="button" class="match-btn-delete" id="deleteReviewBtn"
                        onclick="requestDelete('review', document.getElementById('reviewId').value)"
                        style="display: none;">Delete</button>
                    <button type="button" class="match-btn-cancel" onclick="closeModal('reviewModal')">Cancel</button>
                    <button type="submit" class="match-btn-save">Save Note</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="match-modal-overlay" id="deleteConfirmModal">
        <div class="match-modal-content">
            <div class="match-modal-header">
                <h3><span class="modal-title-icon">🗑️</span> Confirm Delete</h3>
                <button class="match-modal-close" onclick="closeModal('deleteConfirmModal')">×</button>
            </div>
            <div class="delete-confirm-message" id="deleteConfirmMessage">
                Are you sure you want to delete this item?
            </div>
            <div class="delete-confirm-sub" id="deleteConfirmSub">
                This action cannot be undone.
            </div>
            <div class="match-modal-actions">
                <button type="button" class="match-btn-cancel"
                    onclick="closeModal('deleteConfirmModal')">Cancel</button>
                <button type="button" class="match-btn-delete" onclick="executeDelete()">Delete</button>
            </div>
        </div>
    </div>

    @if (Session::has('openEditModal') && Session::get('openEditModal'))
        @auth
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    openEditVideoModal('{{ isset($video) ? $video->getRouteKey() : '' }}');
                });
            </script>
        @endauth
    @endif

    <script>
        // Subscribe Toggle Function
        function toggleSubscribe(userId) {
            if (!userId) return;
            fetch(`/users/${userId}/toggle-subscribe`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    }
                });
        }

        // NOTE: emit these with the json Blade directive (raw output). Escaped echo
        // braces HTML-escape the quotes (videoId becomes an entity-encoded string) and
        // crash this whole block — which loads match data, switches tabs, drives CRUD.
        const videoId = @json(isset($video) ? $video->getRouteKey() : '');
        const isOwner = @json(Auth::check() && isset($video) && Auth::id() === $video->user_id);

        document.addEventListener('DOMContentLoaded', function() {
            loadMatchData();
        });

        async function loadMatchData() {
            try {
                const response = await fetch(`/videos/${videoId}/match-data`);
                const data = await response.json();
                if (data.success) {
                    renderMatchData(data.rounds || [], data.reviews || []);
                } else {
                    console.warn('No match data:', data.message);
                    renderStaticData();
                }
            } catch (error) {
                console.error('Failed to load match data:', error);
                // Try to use server-side data first
                if (window.matchRounds && window.matchReviews) {
                    renderMatchData(window.matchRounds, window.matchReviews);
                } else {
                    renderStaticData();
                }
            }
        }

        // Pass server-side data to JS if available
        window.matchRounds = @json($video->matchRounds ?? []);
        window.matchReviews = @json($video->coachReviews ?? []);
        if (window.matchRounds.length > 0) {
            renderMatchData(window.matchRounds, window.matchReviews);
        }

        function renderStaticData() {
            // No static demo data - empty state
            const pointsContainer = document.getElementById('officialEvents');
            const reviewsContainer = document.getElementById('reviewEvents');
            if (pointsContainer) pointsContainer.innerHTML =
                '<div style="text-align: center; padding: 40px; color: var(--text-secondary);">No match data yet. <button class="action-btn action-btn-primary" onclick="openAddRoundModal()">+ Add Round</button></div>';
            if (reviewsContainer) reviewsContainer.innerHTML =
                '<div style="text-align: center; padding: 40px; color: var(--text-secondary);">No coach notes yet. <button class="action-btn action-btn-primary" onclick="openAddReviewModal()">+ Add Note</button></div>';
        }

        function renderMatchData(rounds, reviews) {
            if (!rounds || rounds.length === 0) return;
            const pointsContainer = document.getElementById('officialEvents');
            const reviewsContainer = document.getElementById('reviewEvents');
            let pointsHtml = '';
            let reviewsHtml = '';

            rounds.forEach(round => {
                const safeRoundName = String(round.name || '').replace(/'/g, "\\'");
                const roundStart = (round.start_time_seconds !== null && round.start_time_seconds !== undefined) ?
                    Number(round.start_time_seconds) : '';
                pointsHtml += `
        <div class="round-marker" data-round="${round.round_number}" data-round-id="${round.id}" data-start-time="${roundStart}">
            <span class="round-badge" data-start-time="${roundStart}" title="Jump to ${roundStart !== '' ? formatTime(roundStart) : 'start'}">${round.name}</span>
            ${isOwner ? `
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    <div class="round-actions">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        <button class="round-action-btn" onclick="openAddPointModal(${round.round_number}, ${round.id})" title="Add point">+</button>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        <button class="round-action-btn" onclick="editRound(${round.round_number}, ${round.id}, '${safeRoundName}', ${roundStart === '' ? 'null' : roundStart})" title="Edit round">✏️</button>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        <button class="round-action-btn" onclick="deleteRound(${round.id})" title="Delete round">🗑️</button>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    </div>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    ` : ''}
        </div>`;

                if (round.points) {
                    round.points.forEach(point => {
                        const competitorClass = point.competitor === 'blue' ? 'pill-blue' : 'pill-red';
                        const competitorLabel = point.competitor === 'blue' ? 'Blue' : 'Red';
                        const timeStr = formatTime(point.timestamp_seconds);
                        pointsHtml += `
                <div class="event-item" data-time-start="${point.timestamp_seconds}" data-round="${round.round_number}" data-id="${point.id}">
                    <div class="event-time">@${timeStr}</div>
                    <div>
                        <div class="event-label">
                            ${point.action} (${point.points} pt)
                            <span class="pill ${competitorClass}">${competitorLabel}</span>
                        </div>
                        <div class="event-meta">
                            ${round.name} • Score ${point.score_blue} – ${point.score_red}${point.notes ? ' • ' + point.notes : ''}
                        </div>
                    </div>
                    ${isOwner ? `
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            <div class="event-actions">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                <button class="event-action-btn" onclick="editPoint(${point.id})" title="Edit">✏️</button>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                <button class="event-action-btn delete" onclick="deletePoint(${point.id})" title="Delete">🗑️</button>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            </div>` : ''}
                </div>`;
                    });
                }
            });

            if (reviews) {
                reviews.forEach(review => {
                    const timeStart = formatTime(review.start_time_seconds);
                    const timeEnd = review.end_time_seconds ? '–' + formatTime(review.end_time_seconds) : '';
                    const timeDisplay = timeStart + timeEnd;
                    reviewsHtml += `
            <div class="event-item" data-time-start="${review.start_time_seconds}" data-time-end="${review.end_time_seconds || ''}" data-id="${review.id}">
                <div class="review-primary-row">
                    <span class="emoji">${review.emoji}</span>
                    <span class="review-time">@${timeDisplay}</span>
                </div>
                <div class="review-content">
                    <h4 class="review-note-title">${review.note}</h4>
                    <div class="review-author-bar">
                        <img class="review-author-avatar" src="https://picsum.photos/seed/${review.coach_name}/80/80" alt="${review.coach_name}">
                        <span class="review-author-name">${review.coach_name}</span>
                    </div>
                </div>
                ${isOwner ? `
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                <div class="event-actions">
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    <button class="event-action-btn" onclick="editReview(${review.id})" title="Edit">✏️</button>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    <button class="event-action-btn delete" onclick="deleteReview(${review.id})" title="Delete">🗑️</button>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                </div>` : ''}
            </div>`;
                });
            }

            if (pointsContainer) pointsContainer.innerHTML = pointsHtml;
            if (reviewsContainer) reviewsContainer.innerHTML = reviewsHtml;
            attachEventListeners();
        }

        function formatTime(seconds) {
            const mins = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
        }

        function parseMinuteSecondInput(value) {
            if (value === null || value === undefined) return null;
            const raw = String(value).trim();
            if (!raw) return null;

            // allow plain integer seconds too
            if (/^\d+$/.test(raw)) return parseInt(raw, 10);

            // expected mm.ss (dot as separator)
            const m = raw.match(/^(\d+)\.(\d{1,2})$/);
            if (!m) return null;

            const minutes = parseInt(m[1], 10);
            const secPart = m[2].padStart(2, '0');
            const secs = parseInt(secPart, 10);

            if (Number.isNaN(minutes) || Number.isNaN(secs) || secs > 59) return null;
            return (minutes * 60) + secs;
        }

        function toMinuteSecondInput(totalSeconds) {
            if (totalSeconds === null || totalSeconds === undefined || totalSeconds === '') return '';
            const s = Math.max(0, Math.floor(Number(totalSeconds)));
            const mins = Math.floor(s / 60);
            const secs = s % 60;
            return `${mins}.${secs.toString().padStart(2, '0')}`;
        }

        function requireValidTimeInput(value, fieldLabel) {
            const parsed = parseMinuteSecondInput(value);
            if (parsed === null) {
                showToast(`${fieldLabel} must be in mm.ss format (example: 1.30 for 1m 30s) or plain seconds.`, 'error');
                return null;
            }
            return parsed;
        }

        // Sync sidebar height to video player height
        function initSidebarHeightSync() {
            const wrap = document.getElementById('ytpWrap');
            if (!wrap) return;
            const apply = () => {
                const h = wrap.getBoundingClientRect().height;
                if (h > 0) document.documentElement.style.setProperty('--sidebar-height', h + 'px');
            };
            apply();
            new ResizeObserver(apply).observe(wrap);
        }
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initSidebarHeightSync);
        } else {
            initSidebarHeightSync();
        }

        document.addEventListener('DOMContentLoaded', function() {
            const tabButtons = document.querySelectorAll('.tab-button');
            const tabPanels = document.querySelectorAll('.tab-panel');
            tabButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const targetTab = this.getAttribute('data-tab');
                    tabButtons.forEach(btn => btn.classList.remove('active'));
                    tabPanels.forEach(panel => panel.classList.remove('active'));
                    this.classList.add('active');
                    document.getElementById('tab-' + targetTab).classList.add('active');
                });
            });
            attachEventListeners();
            document.getElementById('addRoundForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                storeRound(
                    document.getElementById('roundNumber').value,
                    document.getElementById('roundName').value || 'ROUND ' + document.getElementById(
                        'roundNumber').value,
                    document.getElementById('roundStartTime').value
                );
            });
            document.getElementById('pointForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                savePoint();
            });
            document.getElementById('editRoundForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                updateRound();
            });
            document.getElementById('reviewForm')?.addEventListener('submit', function(e) {
                e.preventDefault();
                saveReview();
            });
        });

        let reviewPlaybackStopHandler = null;
        let reviewPlaybackEndTime = null;

        function showCoachNoteOverlay(text) {
            const overlay = document.getElementById('coachNoteOverlay');
            if (!overlay) return;
            overlay.textContent = text || '';
            overlay.classList.add('show');
        }

        function hideCoachNoteOverlay() {
            const overlay = document.getElementById('coachNoteOverlay');
            if (!overlay) return;
            overlay.classList.remove('show');
            overlay.textContent = '';
        }

        function clearReviewPlaybackHandler(videoPlayer) {
            if (videoPlayer && reviewPlaybackStopHandler) {
                videoPlayer.removeEventListener('timeupdate', reviewPlaybackStopHandler);
            }
            reviewPlaybackStopHandler = null;
            reviewPlaybackEndTime = null;
        }

        function attachEventListeners() {
            document.querySelectorAll('.event-item').forEach(item => {
                item.addEventListener('click', function(e) {
                    if (e.target.closest('.event-actions')) return;

                    const timeStart = parseFloat(this.getAttribute('data-time-start'));
                    const timeEndAttr = this.getAttribute('data-time-end');
                    const timeEnd = timeEndAttr === null || timeEndAttr === '' ? null : parseFloat(
                        timeEndAttr);

                    if (timeStart || timeStart === 0) {
                        const videoPlayer = document.getElementById('videoPlayer');
                        if (videoPlayer) {
                            const isReviewItem = this.closest('#tab-review') !== null;

                            // clear any previous stop watcher
                            clearReviewPlaybackHandler(videoPlayer);
                            hideCoachNoteOverlay();

                            if (isReviewItem) {
                                const noteText = this.querySelector('.review-note-title')?.textContent
                                    ?.trim() ||
                                    this.querySelector('.event-label')?.textContent?.trim() || '';
                                if (noteText) {
                                    showCoachNoteOverlay(noteText);
                                }

                                // start exactly from review start time
                                videoPlayer.currentTime = Math.max(0, timeStart);

                                // if review has end time, stop playback at end and hide overlay
                                if (timeEnd !== null && !Number.isNaN(timeEnd) && timeEnd > timeStart) {
                                    reviewPlaybackEndTime = timeEnd;
                                    reviewPlaybackStopHandler = function() {
                                        if (videoPlayer.currentTime >= reviewPlaybackEndTime) {
                                            videoPlayer.pause();
                                            videoPlayer.currentTime = reviewPlaybackEndTime;
                                            hideCoachNoteOverlay();
                                            clearReviewPlaybackHandler(videoPlayer);
                                        }
                                    };
                                    videoPlayer.addEventListener('timeupdate', reviewPlaybackStopHandler);
                                }
                            } else {
                                // non-review items keep previous behavior
                                videoPlayer.currentTime = Math.max(0, timeStart - 1.0);
                            }

                            videoPlayer.play();
                        }
                    }
                });
            });

            const mainVideoPlayer = document.getElementById('videoPlayer');
            if (mainVideoPlayer && !mainVideoPlayer.dataset.reviewOverlayBound) {
                mainVideoPlayer.addEventListener('seeking', function() {
                    if (!reviewPlaybackStopHandler) return;
                    if (reviewPlaybackEndTime !== null && this.currentTime > reviewPlaybackEndTime + 0.15) {
                        hideCoachNoteOverlay();
                        clearReviewPlaybackHandler(this);
                    }
                });

                mainVideoPlayer.addEventListener('ended', function() {
                    hideCoachNoteOverlay();
                    clearReviewPlaybackHandler(this);
                });

                mainVideoPlayer.dataset.reviewOverlayBound = '1';
            }

            document.querySelectorAll('.round-badge').forEach(badge => {
                badge.style.cursor = 'pointer';
                badge.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (e.target.closest('.round-actions')) return;

                    const marker = this.closest('.round-marker');
                    const startAttr = this.getAttribute('data-start-time') ?? marker?.getAttribute(
                        'data-start-time');
                    const startTime = startAttr === '' || startAttr === null ? 0 : parseFloat(startAttr);

                    if (!Number.isNaN(startTime)) {
                        const videoPlayer = document.getElementById('videoPlayer');
                        if (videoPlayer) {
                            videoPlayer.currentTime = Math.max(0, startTime);
                            videoPlayer.play();
                        }
                    }
                });
            });
        }

        function openModal(modalId) {
            document.getElementById(modalId).classList.add('active');
        }

        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }

        let pendingDeleteAction = null;
        let pendingDeleteId = null;

        function requestDelete(type, id) {
            if (!id) return;
            pendingDeleteAction = type;
            pendingDeleteId = id;

            const message = document.getElementById('deleteConfirmMessage');
            const sub = document.getElementById('deleteConfirmSub');
            if (message) {
                message.textContent = `Delete this ${type}?`;
            }
            if (sub) {
                sub.textContent = 'This action cannot be undone.';
            }

            openModal('deleteConfirmModal');
        }

        function executeDelete() {
            if (!pendingDeleteAction || !pendingDeleteId) {
                closeModal('deleteConfirmModal');
                return;
            }

            if (pendingDeleteAction === 'round') {
                performDeleteRound(pendingDeleteId);
            } else if (pendingDeleteAction === 'point') {
                performDeletePoint(pendingDeleteId);
            } else if (pendingDeleteAction === 'review') {
                performDeleteReview(pendingDeleteId);
            }

            pendingDeleteAction = null;
            pendingDeleteId = null;
            closeModal('deleteConfirmModal');
        }
        document.querySelectorAll('.match-modal-overlay').forEach(modal => {
            modal.addEventListener('click', function(e) {
                if (e.target === this) this.classList.remove('active');
            });
        });

        const csrfToken = '{{ Auth::check() ? csrf_token() : '' }}';
        const isDemoMode = !{{ Auth::check() ? 'true' : 'false' }};

        // Round/Point/Review functions (abbreviated for brevity)
        function openAddRoundModal() {
            if (isDemoMode || !csrfToken) {
                showToast('Demo Mode: Requires authentication', 'info');
                return;
            }
            document.getElementById('roundNumber').value = '';
            document.getElementById('roundName').value = '';
            document.getElementById('roundStartTime').value = '';
            openModal('addRoundModal');
        }
        async function storeRound(roundNumber, roundName, roundStartTime) {
            if (!csrfToken) return;
            try {
                const res = await fetch(`/videos/${videoId}/rounds`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken
                    },
                    body: JSON.stringify({
                        round_number: parseInt(roundNumber),
                        name: roundName,
                        start_time_seconds: roundStartTime !== '' ? parseMinuteSecondInput(
                            roundStartTime) : null
                    })
                });
                const data = await res.json();
                if (data.success) {
                    closeModal('addRoundModal');
                    loadMatchData();
                } else showToast(data.message || 'Error', 'error');
            } catch (e) {
                showToast('Error: ' + e.message, 'error');
            }
        }

        function editRound(roundNumber, roundId, currentName, currentStartTime = null) {
            if (isDemoMode || !csrfToken) {
                showToast('Demo Mode', 'info');
                return;
            }

            // Fallback to DOM values if params are missing
            if (!roundId) {
                const marker = document.querySelector(`.round-marker[data-round="${roundNumber}"]`);
                if (marker) {
                    roundId = marker.getAttribute('data-round-id') || roundId;
                    currentStartTime = marker.getAttribute('data-start-time') ?? currentStartTime;
                    currentName = marker.querySelector('.round-badge')?.textContent?.trim() || currentName;
                }
            }

            document.getElementById('editRoundId').value = roundId || '';
            document.getElementById('editRoundNumber').value = roundNumber || '';
            document.getElementById('editRoundName').value = currentName || '';
            document.getElementById('editRoundStartTime').value = (currentStartTime === null || currentStartTime ===
                undefined || currentStartTime === '') ? '' : toMinuteSecondInput(currentStartTime);
            openModal('editRoundModal');
        }
        async function updateRound() {
            if (!csrfToken) return;
            const roundId = document.getElementById('editRoundId').value;
            const roundNumber = document.getElementById('editRoundNumber').value;
            const roundName = document.getElementById('editRoundName').value;
            const roundStartTime = document.getElementById('editRoundStartTime').value;

            try {
                // Use method spoofing to avoid servers/proxies that block true PUT and return HTML error pages
                const payload = new URLSearchParams();
                payload.append('_method', 'PUT');
                payload.append('round_number', parseInt(roundNumber));
                payload.append('name', roundName);
                if (roundStartTime !== '') {
                    const parsedRoundStart = requireValidTimeInput(roundStartTime, 'Round start time');
                    if (parsedRoundStart === null) return;
                    payload.append('start_time_seconds', parsedRoundStart);
                }

                const res = await fetch(`/rounds/${roundId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'X-CSRF-TOKEN': csrfToken,
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: payload.toString()
                });

                let data;
                const contentType = res.headers.get('content-type') || '';
                if (contentType.includes('application/json')) {
                    data = await res.json();
                } else {
                    const text = await res.text();
                    throw new Error(`Server returned non-JSON response (status ${res.status}). ${text.slice(0, 180)}`);
                }

                if (res.ok && data.success) {
                    closeModal('editRoundModal');
                    loadMatchData();
                } else {
                    throw new Error(data.message || `Update failed (status ${res.status})`);
                }
            } catch (e) {
                console.error('updateRound error:', e);
                showToast('Error updating round: ' + e.message, 'error');
            }
        }
        async function deleteRound(roundId) {
            requestDelete('round', roundId);
        }

        async function performDeleteRound(roundId) {
            if (!csrfToken) return;
            try {
                const res = await fetch(`/rounds/${roundId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    }
                });
                const data = await res.json();
                if (data.success) loadMatchData();
                else showToast(data.message || 'Error', 'error');
            } catch (e) {
                showToast('Error: ' + e.message, 'error');
            }
        }

        function openAddPointModal(roundNumber, roundId) {
            if (isDemoMode || !csrfToken) {
                showToast('Demo Mode', 'info');
                return;
            }
            document.getElementById('pointModalTitle').textContent = 'Add Point';
            document.getElementById('pointId').value = '';
            document.getElementById('pointRoundId').value = roundId || '';
            document.getElementById('pointTimestamp').value = '';
            document.getElementById('pointRoundSelect').value = roundNumber || '1';
            document.getElementById('pointAction').value = '';
            document.getElementById('pointValue').value = '1';
            document.getElementById('pointCompetitor').value = 'blue';
            document.getElementById('pointNotes').value = '';
            document.getElementById('deletePointBtn').style.display = 'none';
            openModal('pointModal');
        }

        function editPoint(pointId) {
            const el = document.querySelector(`.event-item[data-id="${pointId}"]`);
            if (!el) return;
            document.getElementById('pointModalTitle').textContent = 'Edit Point';
            document.getElementById('pointId').value = pointId;
            document.getElementById('pointTimestamp').value = toMinuteSecondInput(el.dataset.timeStart || '');
            document.getElementById('pointRoundSelect').value = el.dataset.round || '1';
            document.getElementById('pointAction').value = el.querySelector('.event-label')?.textContent.split('(')[0]
                .trim() || '';
            document.getElementById('pointValue').value = '1';
            document.getElementById('pointCompetitor').value = el.querySelector('.pill')?.classList.contains('pill-blue') ?
                'blue' : 'red';
            document.getElementById('pointNotes').value = el.querySelector('.event-meta')?.textContent.split('•').slice(2)
                .join('').trim() || '';
            document.getElementById('deletePointBtn').style.display = (isDemoMode || !csrfToken) ? 'none' : 'block';
            openModal('pointModal');
        }
        async function savePoint() {
            if (!csrfToken) {
                closeModal('pointModal');
                return;
            }
            const pointId = document.getElementById('pointId').value;
            const roundId = document.getElementById('pointRoundId').value;
            const timestamp = document.getElementById('pointTimestamp').value;
            const round = document.getElementById('pointRoundSelect').value;
            const action = document.getElementById('pointAction').value;
            const value = document.getElementById('pointValue').value;
            const competitor = document.getElementById('pointCompetitor').value;
            const notes = document.getElementById('pointNotes').value;
            const parsedPointTimestamp = requireValidTimeInput(timestamp, 'Point timestamp');
            if (parsedPointTimestamp === null) return;

            try {
                if (pointId) {
                    const res = await fetch(`/points/${pointId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken
                        },
                        body: JSON.stringify({
                            timestamp_seconds: parsedPointTimestamp,
                            action,
                            points: parseInt(value),
                            competitor,
                            notes
                        })
                    });
                    const data = await res.json();
                    if (data.success) {
                        closeModal('pointModal');
                        loadMatchData();
                    } else showToast(data.message || 'Error', 'error');
                } else {
                    const res = await fetch(`/videos/${videoId}/points`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken
                        },
                        body: JSON.stringify({
                            round_id: roundId,
                            timestamp_seconds: parseInt(timestamp),
                            action,
                            points: parseInt(value),
                            competitor,
                            notes
                        })
                    });
                    const data = await res.json();
                    if (data.success) {
                        closeModal('pointModal');
                        loadMatchData();
                    } else showToast(data.message || 'Error', 'error');
                }
            } catch (e) {
                showToast('Error: ' + e.message, 'error');
            }
        }
        async function deletePoint(pointId) {
            requestDelete('point', pointId);
        }

        async function performDeletePoint(pointId) {
            if (!csrfToken) return;
            try {
                const res = await fetch(`/points/${pointId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    }
                });
                const data = await res.json();
                if (data.success) {
                    closeModal('pointModal');
                    loadMatchData();
                } else showToast(data.message || 'Error', 'error');
            } catch (e) {
                showToast('Error: ' + e.message, 'error');
            }
        }

        function setReviewEmoji(emoji, btnEl = null) {
            const emojiInput = document.getElementById('reviewEmoji');
            if (emojiInput) emojiInput.value = emoji;

            const optionsWrap = document.getElementById('reviewEmojiOptions');
            if (optionsWrap) {
                optionsWrap.querySelectorAll('.emoji-option-btn').forEach(b => b.classList.remove('active'));
            }

            if (btnEl) {
                btnEl.classList.add('active');
            } else if (optionsWrap) {
                const target = optionsWrap.querySelector(`.emoji-option-btn[data-emoji="${emoji}"]`);
                if (target) target.classList.add('active');
            }
        }

        function openAddReviewModal() {
            if (isDemoMode || !csrfToken) {
                showToast('Demo Mode', 'info');
                return;
            }
            const titleEl = document.getElementById('reviewModalTitle');
            if (titleEl) {
                titleEl.innerHTML = '<span class="modal-title-icon">📝</span> Add Coach Note';
            }
            document.getElementById('reviewId').value = '';
            document.getElementById('reviewStartTime').value = '';
            document.getElementById('reviewEndTime').value = '';
            document.getElementById('reviewNote').value = '';
            document.getElementById('reviewCoach').value = '';
            setReviewEmoji('🔥');
            document.getElementById('deleteReviewBtn').style.display = 'none';
            openModal('reviewModal');
        }

        function editReview(reviewId) {
            // scope strictly to coach review tab to avoid picking points items with same data-id
            const el = document.querySelector(`#tab-review .event-item[data-id="${reviewId}"]`);
            if (!el) return;

            const titleEl = document.getElementById('reviewModalTitle');
            if (titleEl) {
                titleEl.innerHTML = '<span class="modal-title-icon">📝</span> Edit Coach Note';
            }

            document.getElementById('reviewId').value = reviewId;
            document.getElementById('reviewStartTime').value = toMinuteSecondInput(el.dataset.timeStart || '');
            document.getElementById('reviewEndTime').value = toMinuteSecondInput(el.dataset.timeEnd || '');

            // support both old and new review item markup
            const noteText = el.querySelector('.review-note-title')?.textContent?.trim() ||
                el.querySelector('.event-label')?.textContent?.trim() || '';
            const coachName = el.querySelector('.review-author-name')?.textContent?.trim() ||
                el.querySelector('.coach-name')?.textContent?.trim() || '';
            const emojiText = el.querySelector('.review-primary-row .emoji')?.textContent?.trim() ||
                el.querySelector('.event-time-container .emoji')?.textContent?.trim() || '🔥';

            document.getElementById('reviewNote').value = noteText;
            document.getElementById('reviewCoach').value = coachName;
            setReviewEmoji(emojiText || '🔥');

            document.getElementById('deleteReviewBtn').style.display = (isDemoMode || !csrfToken) ? 'none' : 'block';
            openModal('reviewModal');
        }
        async function saveReview() {
            if (!csrfToken) return;
            const reviewId = document.getElementById('reviewId').value;
            const startTime = document.getElementById('reviewStartTime').value;
            const endTime = document.getElementById('reviewEndTime').value;
            const note = document.getElementById('reviewNote').value;
            const coach = document.getElementById('reviewCoach').value;
            const emoji = document.getElementById('reviewEmoji').value;
            const parsedReviewStart = requireValidTimeInput(startTime, 'Review start time');
            if (parsedReviewStart === null) return;
            const parsedReviewEnd = endTime ? requireValidTimeInput(endTime, 'Review end time') : null;
            if (endTime && parsedReviewEnd === null) return;

            try {
                if (reviewId) {
                    const res = await fetch(`/reviews/${reviewId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken
                        },
                        body: JSON.stringify({
                            start_time_seconds: parsedReviewStart,
                            end_time_seconds: parsedReviewEnd,
                            note,
                            coach_name: coach,
                            emoji
                        })
                    });
                    const data = await res.json();
                    if (data.success) {
                        closeModal('reviewModal');
                        loadMatchData();
                    } else showToast(data.message || 'Error', 'error');
                } else {
                    const res = await fetch(`/videos/${videoId}/reviews`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': csrfToken
                        },
                        body: JSON.stringify({
                            start_time_seconds: parsedReviewStart,
                            end_time_seconds: parsedReviewEnd,
                            note,
                            coach_name: coach,
                            emoji
                        })
                    });
                    const data = await res.json();
                    if (data.success) {
                        closeModal('reviewModal');
                        loadMatchData();
                    } else showToast(data.message || 'Error', 'error');
                }
            } catch (e) {
                showToast('Error: ' + e.message, 'error');
            }
        }
        async function deleteReview(reviewId) {
            requestDelete('review', reviewId);
        }

        async function performDeleteReview(reviewId) {
            if (!csrfToken) return;
            try {
                const res = await fetch(`/reviews/${reviewId}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': csrfToken
                    }
                });
                const data = await res.json();
                if (data.success) {
                    closeModal('reviewModal');
                    loadMatchData();
                } else showToast(data.message || 'Error', 'error');
            } catch (e) {
                showToast('Error: ' + e.message, 'error');
            }
        }

    </script>
@endsection
