<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>{{ filename }}</title>
    <link href="{{ url_for('static', filename='node_modules/video.js/dist/video-js.css')}}" rel="stylesheet">
    <link href="{{ url_for('static', filename='node_modules/videojs-markers/dist/videojs.markers.css')}}"
        rel="stylesheet">

    <style>
        body {
            margin: 0;
            background-color: #1a1a1a;
            min-height: 100vh;
            transition: background-color 0.3s ease;
            padding-top: 60px;
        }



        .header {
            position: fixed;
            top: 0;
            left: 0;
            padding: 15px 20px;
            z-index: 1000;
        }

        .header a {
            color: #fff;
            text-decoration: none;
            font-family: Arial, sans-serif;
            font-size: 24px;
            font-weight: bold;
        }

        .header a:hover {
            color: #4CAF50;
        }

        .video-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;
        }

        /* Make video player responsive */
        #RPlayer {
            width: 100% !important;
            max-width: 1100px;
            height: auto !important;
            aspect-ratio: 16 / 9;
        }

        /* Hide video fallback text by default - Video.js will show its own error */
        .video-fallback {
            display: none;
        }

        /* Show fallback only when Video.js failed to load */
        .vjs-error .video-fallback,
        .video-js-failed .video-fallback {
            display: block;
            color: #fff;
            text-align: center;
            padding: 20px;
        }

        .video-title {
            color: #fff;
            font-family: Arial, sans-serif;
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 15px;
            max-width: 100%;
            word-wrap: break-word;
        }

        .video-meta {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-top: 10px;
            font-family: Arial, sans-serif;
            font-size: 14px;
        }

        .video-author {
            color: #aaa;
        }

        .video-author a {
            color: #4CAF50;
            text-decoration: none;
        }

        .video-author a:hover {
            text-decoration: underline;
        }

        .view-count {
            color: #aaa;
        }

        .video-description {
            color: #888;
            max-width: 600px;
        }

        .comments-section {
            width: 100%;
            max-width: 1280px;
            margin-top: 30px;
            font-family: Arial, sans-serif;
        }

        .comments-title {
            color: #fff;
            font-size: 18px;
            margin-bottom: 20px;
        }

        .comment-form {
            margin-bottom: 30px;
        }

        .comment-form textarea {
            width: 100%;
            min-height: 80px;
            padding: 12px;
            border: 1px solid #444;
            border-radius: 5px;
            background-color: #2a2a2a;
            color: #fff;
            font-size: 14px;
            resize: vertical;
            box-sizing: border-box;
        }

        .comment-form textarea:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .comment-form-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 10px;
        }

        .char-counter {
            color: #888;
            font-size: 12px;
        }

        .btn-comment {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .btn-comment:hover {
            background-color: #45a049;
        }

        .btn-comment:disabled {
            background-color: #444;
            cursor: not-allowed;
        }

        .comment-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .comment-item {
            background-color: #2a2a2a;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 15px;
        }

        .comment-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .comment-author {
            color: #4CAF50;
            font-weight: bold;
            font-size: 14px;
            text-decoration: none;
        }

        .comment-author:hover {
            text-decoration: underline;
        }

        .comment-date {
            color: #888;
            font-size: 12px;
        }

        .comment-actions {
            margin-left: auto;
        }

        .btn-delete {
            background: none;
            border: none;
            color: #888;
            font-size: 12px;
            cursor: pointer;
            padding: 2px 8px;
        }

        .btn-delete:hover {
            color: #ff4444;
        }

        .btn-edit {
            background: none;
            border: none;
            color: #888;
            font-size: 12px;
            cursor: pointer;
            padding: 2px 8px;
        }

        .btn-edit:hover {
            color: #4CAF50;
        }

        .edit-form {
            display: none;
            margin-top: 10px;
        }

        .edit-form.active {
            display: block;
        }

        .edit-form textarea {
            width: 100%;
            min-height: 60px;
            padding: 10px;
            border: 1px solid #444;
            border-radius: 5px;
            background-color: #333;
            color: #fff;
            font-size: 14px;
            resize: vertical;
            box-sizing: border-box;
        }

        .edit-form textarea:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .edit-form-actions {
            display: flex;
            gap: 10px;
            margin-top: 8px;
        }

        .btn-save {
            padding: 6px 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
        }

        .btn-save:hover {
            background-color: #45a049;
        }

        .btn-cancel {
            padding: 6px 12px;
            background-color: #444;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
        }

        .btn-cancel:hover {
            background-color: #555;
        }

        .comment-content {
            color: #ddd;
            font-size: 14px;
            line-height: 1.5;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .comment-content a {
            color: #4CAF50;
            text-decoration: none;
        }

        .comment-content a:hover {
            text-decoration: underline;
        }

        /* Threaded replies */
        .btn-reply {
            background: none;
            border: none;
            color: #888;
            font-size: 12px;
            cursor: pointer;
            padding: 2px 8px;
        }

        .btn-reply:hover {
            color: #4CAF50;
        }

        .reply-form {
            display: none;
            margin-top: 10px;
            padding: 10px;
            background-color: #333;
            border-radius: 5px;
        }

        .reply-form.active {
            display: block;
        }

        .reply-form textarea {
            width: 100%;
            min-height: 60px;
            padding: 10px;
            border: 1px solid #444;
            border-radius: 5px;
            background-color: #2a2a2a;
            color: #fff;
            font-size: 14px;
            resize: vertical;
            box-sizing: border-box;
        }

        .reply-form textarea:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .reply-form-actions {
            display: flex;
            gap: 10px;
            margin-top: 8px;
        }

        /* Comments header with sort selector */
        .comments-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .comments-header .comments-title {
            margin: 0;
        }

        .sort-selector {
            display: flex;
            gap: 5px;
            align-items: center;
        }

        .sort-selector span {
            color: #888;
            font-size: 14px;
            margin-right: 5px;
        }

        .sort-selector button {
            background: none;
            border: none;
            color: #888;
            font-size: 14px;
            cursor: pointer;
            padding: 6px 12px;
            border-radius: 4px;
            transition: all 0.2s;
        }

        .sort-selector button:hover {
            background-color: #333;
            color: #fff;
        }

        .sort-selector button.active {
            color: #fff;
            font-weight: 600;
        }

        /* Replies toggle button - YouTube style */
        .replies-toggle {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            color: #3EA6FF;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            padding: 8px 12px;
            margin: 8px 0 0 -12px;
            background: none;
            border: none;
            border-radius: 20px;
            transition: background-color 0.2s;
        }

        .replies-toggle:hover {
            background-color: rgba(62, 166, 255, 0.1);
        }

        .replies-toggle .toggle-icon {
            display: inline-block;
            transition: transform 0.2s;
            font-size: 10px;
        }

        .replies-toggle.expanded .toggle-icon {
            transform: rotate(180deg);
        }

        /* Replies container with animation */
        .replies-container {
            overflow: hidden;
            max-height: 0;
            transition: max-height 0.3s ease-out;
        }

        .replies-container.expanded {
            max-height: 10000px;
        }

        /* Replies list */
        .replies-list {
            list-style: none;
            padding: 0;
            margin: 0 0 0 24px;
        }

        .reply-item {
            background-color: transparent;
            padding: 12px 0;
            margin-bottom: 0;
            border-bottom: 1px solid #333;
        }

        .reply-item:last-child {
            border-bottom: none;
        }

        /* Deleted/redacted comments - only style direct children, not nested replies */
        .comment-deleted>.comment-header {
            opacity: 0.6;
        }

        .comment-deleted>.comment-content {
            opacity: 0.6;
            color: #888;
            font-style: italic;
        }

        .comment-deleted>.comment-header .comment-author {
            color: #666;
        }

        .no-comments {
            color: #888;
            font-style: italic;
        }

        .login-prompt {
            color: #888;
            font-size: 14px;
        }

        .login-prompt a {
            color: #4CAF50;
            text-decoration: none;
        }

        .login-prompt a:hover {
            text-decoration: underline;
        }

        .flash-message {
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
            font-size: 14px;
        }

        .flash-success {
            background-color: #4CAF50;
            color: white;
        }

        .flash-error {
            background-color: #ff4444;
            color: white;
        }

        .flash-warning {
            background-color: #ff9800;
            color: white;
        }

        .video-actions {
            margin-top: 15px;
        }

        .btn-delete-video {
            padding: 8px 16px;
            background-color: #8B0000;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 13px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .btn-delete-video:hover {
            background-color: #a00000;
        }

        .btn-edit-video {
            padding: 8px 16px;
            background-color: #444;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 13px;
            cursor: pointer;
            transition: background-color 0.2s;
            text-decoration: none;
            display: inline-block;
        }

        .btn-edit-video:hover {
            background-color: #555;
        }

        .share-dropdown {
            position: relative;
            display: inline-block;
        }

        .btn-share {
            padding: 8px 16px;
            background-color: #444;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 13px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .btn-share:hover {
            background-color: #555;
        }

        .btn-share.copied {
            background-color: #4CAF50;
        }

        .share-menu {
            display: none;
            position: absolute;
            bottom: 100%;
            left: 0;
            background-color: #333;
            border-radius: 5px;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.3);
            min-width: 180px;
            z-index: 100;
            margin-bottom: 5px;
        }

        .share-menu.active {
            display: block;
        }

        .share-menu-item {
            display: block;
            width: 100%;
            padding: 10px 15px;
            background: none;
            border: none;
            color: white;
            font-size: 13px;
            text-align: left;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .share-menu-item:hover {
            background-color: #444;
        }

        .share-menu-item:first-child {
            border-radius: 5px 5px 0 0;
        }

        .share-menu-item:last-child {
            border-radius: 0 0 5px 5px;
        }

        .share-menu-item .timestamp-preview {
            color: #aaa;
            font-size: 11px;
            margin-left: 5px;
        }



        .btn-favorite {
            padding: 8px 16px;
            background-color: #444;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 13px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .btn-favorite:hover {
            background-color: #555;
        }

        .btn-favorite.is-favorite {
            background-color: #FFD700;
            color: #000;
        }

        .btn-favorite.is-favorite:hover {
            background-color: #FFC000;
        }

        .btn-playlist {
            padding: 8px 16px;
            background-color: #444;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 13px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .btn-playlist:hover {
            background-color: #555;
        }

        /* Modal styles */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

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

        .modal-content {
            background-color: #2a2a2a;
            border-radius: 8px;
            width: 400px;
            max-width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }

        .playlist-modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #444;
        }

        .playlist-modal-header h3 {
            margin: 0;
            font-size: 18px;
        }

        .playlist-modal-body {
            padding: 15px 20px;
        }

        .playlist-options {
            margin-bottom: 20px;
        }

        .playlist-option {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background-color: #333;
            border-radius: 4px;
            margin-bottom: 8px;
        }

        .playlist-option .playlist-name {
            flex: 1;
        }

        .playlist-option .playlist-name.in-playlist {
            color: #888;
        }

        .playlist-option .already-added {
            color: #4CAF50;
            font-size: 12px;
        }

        .playlist-option .add-form {
            display: flex;
            align-items: center;
            gap: 10px;
            width: 100%;
        }

        .playlist-option .btn-add {
            padding: 6px 12px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
        }

        .playlist-option .btn-add:hover {
            background-color: #45a049;
        }

        .no-playlists {
            color: #888;
            font-style: italic;
            text-align: center;
            padding: 20px;
        }

        .create-new-section {
            border-top: 1px solid #444;
            padding-top: 15px;
        }

        .create-new-section h4 {
            margin: 0 0 10px 0;
            font-size: 14px;
            color: #aaa;
        }

        .create-form {
            display: flex;
            gap: 10px;
        }

        .playlist-name-input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #444;
            border-radius: 4px;
            background-color: #333;
            color: #fff;
            font-size: 14px;
        }

        .playlist-name-input:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .btn-create {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 13px;
            cursor: pointer;
        }

        .btn-create:hover {
            background-color: #45a049;
        }

        .modal-close {
            position: absolute;
            top: 10px;
            right: 15px;
            background: none;
            border: none;
            color: #888;
            font-size: 24px;
            cursor: pointer;
        }

        .modal-close:hover {
            color: #fff;
        }

        /* Two-column watch layout */
        .watch-layout {
            display: flex;
            gap: 24px;
            max-width: 1700px;
            margin: 0 auto;
            padding: 20px;
            width: 100%;
            box-sizing: border-box;
            align-items: flex-start;
        }

        .watch-main {
            flex: 1;
            min-width: 0;
            max-width: 1100px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .watch-sidebar {
            width: 400px;
            flex-shrink: 0;
            position: sticky;
            top: 80px;
            max-height: calc(100vh - 100px);
            overflow-y: auto;
        }

        /* Recommended videos sidebar */
        .recommended-videos {
            background-color: #2a2a2a;
            border-radius: 8px;
            padding: 15px;
        }

        .recommended-videos h3 {
            margin: 0 0 15px 0;
            font-size: 16px;
            font-family: Arial, sans-serif;
            color: #fff;
        }

        .recommended-item {
            display: flex;
            gap: 10px;
            margin-bottom: 12px;
            text-decoration: none;
            color: inherit;
            padding: 8px;
            border-radius: 4px;
            transition: background-color 0.2s;
        }

        .recommended-item:hover {
            background-color: #333;
        }

        .recommended-thumb {
            width: 160px;
            height: 90px;
            object-fit: cover;
            border-radius: 4px;
            background-color: #444;
            flex-shrink: 0;
        }

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

        .recommended-title {
            font-family: Arial, sans-serif;
            font-size: 14px;
            font-weight: 500;
            line-height: 1.3;
            color: #fff;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            margin-bottom: 5px;
        }

        .recommended-meta {
            font-family: Arial, sans-serif;
            font-size: 12px;
            color: #888;
            line-height: 1.4;
        }

        .no-recommendations {
            color: #888;
            font-size: 13px;
            font-family: Arial, sans-serif;
            font-style: italic;
            text-align: center;
            padding: 20px;
        }

        /* Responsive: stack on smaller screens */
        @media (max-width: 1400px) {
            .watch-layout {
                flex-direction: column;
                align-items: center;
            }

            .watch-main {
                max-width: 100%;
            }

            .watch-sidebar {
                width: 100%;
                max-width: 1100px;
                position: static;
                max-height: none;
            }
        }

        /* Theater mode adjustments for layout */
        body.theater-mode .watch-layout {
            max-width: none;
            padding: 0;
        }

        body.theater-mode .watch-sidebar {
            display: none;
        }

        /* Video.js chapter markers customization */
        .blue-marker {
            background-color: #2196F3 !important;
            border-radius: 50% !important;
        }
    </style>
    <script>
        var filename = '{{ filename }}'
        var mymarkers = JSON.parse('{{ markers | tojson }}');
        var startTime = {{ start_time | default (0) }};
        var spriteUrl = '{{ sprite_url }}' !== 'None' ? '{{ sprite_url }}' : null;
        {% if video and current_user.is_authenticated %}
        var videoShortId = '{{ video.short_id }}';
        {% else %}
        var videoShortId = null;
        {% endif %}
    </script>
    <link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='favicon.ico') }}">
    <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.png') }}">

</head>

<body>
    <div class="header">
        <a href="/" style="display: flex; align-items: center;"><img
                src="{{ url_for('static', filename='logo_transparent.png') }}" alt="RTube" height="30"></a>
    </div>
    <div class="watch-layout">
        <div class="watch-main">
            <div class="video-container">
                <h1 class="video-title">{{ filename }}</h1>
                <video-js id="RPlayer" class="vjs-default-skin" controls preload="auto" width="1280" height="720">
                    <source src="{{ video_url }}" type="application/x-mpegURL">
                    {% if video and video.chapters %}
                    <track kind="chapters" src="{{ url_for('videos.chapters_vtt', short_id=video.short_id) }}"
                        srclang="en" label="Chapters" default>
                    {% endif %}
                    <p class="video-fallback">Your browser doesn't support video tag or Video.js failed to load.</p>
                </video-js>
                <div class="video-meta">
                    {% if video and video.owner_username %}
                    <span class="video-author">by <a
                            href="{{ url_for('auth.user_profile', username=video.owner_username) }}">{{
                            video.owner_username }}</a></span>
                    {% endif %}
                    <span class="view-count">{{ view_count }} view{{ 's' if view_count > 1 else '' }}</span>
                    {% if description %}
                    <span class="video-description">{{ description }}</span>
                    {% endif %}
                    <div class="share-dropdown">
                        <button type="button" class="btn-share" onclick="toggleShareMenu(this)">Share</button>
                        <div class="share-menu" id="share-menu">
                            <button type="button" class="share-menu-item" onclick="shareVideo(false)">Copy link</button>
                            <button type="button" class="share-menu-item" onclick="shareVideo(true)">Copy link at <span
                                    id="share-timestamp">0:00</span></button>
                        </div>
                    </div>
                    {% if current_user.is_authenticated and video %}
                    {% if is_favorite %}
                    <form method="post" action="{{ url_for('videos.remove_favorite', v=video.short_id) }}"
                        style="display: inline;">
                        <button type="submit" class="btn-favorite is-favorite">Remove from Favorites</button>
                    </form>
                    {% else %}
                    <form method="post" action="{{ url_for('videos.add_favorite', v=video.short_id) }}"
                        style="display: inline;">
                        <button type="submit" class="btn-favorite">Add to Favorites</button>
                    </form>
                    {% endif %}
                    <button type="button" class="btn-playlist" onclick="openPlaylistModal()">Add to Playlist</button>
                    {% endif %}
                </div>
                {% if current_user.is_authenticated and video and (current_user.is_admin() or video.owner_username ==
                current_user.username) %}
                <div class="video-actions">
                    <a href="{{ url_for('videos.edit_video', v=video.short_id) }}" class="btn-edit-video">Edit Video</a>
                    <form method="post" action="{{ url_for('videos.delete_video', v=video.short_id) }}"
                        style="display: inline;">
                        <button type="submit" class="btn-delete-video"
                            onclick="return confirm('Are you sure you want to delete this video? This action cannot be undone.')">Delete
                            Video</button>
                    </form>
                </div>
                {% endif %}
            </div>

            {% if video %}
            <div class="chapters-section"
                style="width: 100%; max-width: 1280px; margin-top: 30px; font-family: Arial, sans-serif;">
                <h3 class="comments-title">Chapters</h3>

                {% if video.chapters %}
                <ul class="chapters-list" style="list-style: none; padding: 0; margin: 0 0 15px 0;">
                    {% for chapter in video.chapters %}
                    <li
                        style="margin-bottom: 8px; display: flex; align-items: center; gap: 10px; background-color: #2a2a2a; padding: 10px; border-radius: 4px;">
                        <a href="{{ url_for('videos.watch_video', v=video.short_id, t=chapter.start_time) }}"
                            onclick="if(typeof player !== 'undefined') { player.currentTime({{ chapter.start_time }}); player.play(); window.history.pushState({}, '', this.href); event.preventDefault(); }"
                            style="color: #4CAF50; text-decoration: none; font-family: monospace; font-size: 14px; background-color: #1a1a1a; padding: 4px 8px; border-radius: 3px;">
                            {{ chapter.formatted_time() }}
                        </a>
                        <span style="color: #ddd; font-size: 14px;">{{ chapter.title }}</span>

                        {% if current_user.is_authenticated and (current_user.is_admin() or video.owner_username ==
                        current_user.username) %}
                        <div class="chapter-actions" style="margin-left: auto;">
                            <button type="button" class="btn-edit"
                                onclick="toggleChapterEdit({{ chapter.id }})">Edit</button>
                            <form method="post" action="{{ url_for('videos.delete_chapter', v=video.short_id) }}"
                                style="display: inline;">
                                <input type="hidden" name="chapter_id" value="{{ chapter.id }}">
                                <button type="submit" class="btn-delete"
                                    onclick="return confirm('Delete this chapter?')">Delete</button>
                            </form>
                        </div>
                        {% endif %}
                    </li>

                    {% if current_user.is_authenticated and (current_user.is_admin() or video.owner_username ==
                    current_user.username) %}
                    <li id="edit-chapter-form-{{ chapter.id }}"
                        style="display: none; padding: 10px; background-color: #333; border-radius: 4px; margin-bottom: 10px;">
                        <form method="post" action="{{ url_for('videos.edit_chapter', v=video.short_id) }}"
                            style="display: flex; gap: 10px; align-items: center;">
                            <input type="hidden" name="chapter_id" value="{{ chapter.id }}">
                            <input type="text" name="time" value="{{ chapter.formatted_time() }}" placeholder="MM:SS"
                                required
                                style="width: 80px; padding: 6px; border-radius: 4px; border: 1px solid #444; background: #2a2a2a; color: white;">
                            <input type="text" name="title" value="{{ chapter.title }}" placeholder="Chapter title"
                                required
                                style="flex: 1; padding: 6px; border-radius: 4px; border: 1px solid #444; background: #2a2a2a; color: white;">
                            <button type="submit" class="btn-save">Save</button>
                            <button type="button" class="btn-cancel"
                                onclick="toggleChapterEdit({{ chapter.id }})">Cancel</button>
                        </form>
                    </li>
                    {% endif %}
                    {% endfor %}
                </ul>
                {% else %}
                <p style="color: #888; font-style: italic; margin-bottom: 15px; font-size: 14px;">No chapters yet.</p>
                {% endif %}

                {% if current_user.is_authenticated and (current_user.is_admin() or video.owner_username ==
                current_user.username) %}
                <button type="button" class="btn-comment" style="padding: 6px 12px; font-size: 13px;"
                    onclick="toggleChapterAdd()">+ Add Chapter</button>
                <div id="add-chapter-form"
                    style="display: none; padding: 10px; background-color: #2a2a2a; border-radius: 4px; margin-top: 10px;">
                    <form method="post" action="{{ url_for('videos.add_chapter', v=video.short_id) }}"
                        style="display: flex; gap: 10px; align-items: center;">
                        <input type="text" name="time" placeholder="MM:SS" required
                            style="width: 80px; padding: 6px; border-radius: 4px; border: 1px solid #444; background: #333; color: white;">
                        <input type="text" name="title" placeholder="Chapter title" required
                            style="flex: 1; padding: 6px; border-radius: 4px; border: 1px solid #444; background: #333; color: white;">
                        <button type="submit" class="btn-save">Add</button>
                        <button type="button" class="btn-cancel" onclick="toggleChapterAdd()">Cancel</button>
                    </form>
                </div>
                {% endif %}
            </div>

            <div class="comments-section">
                <div class="comments-header">
                    <h3 class="comments-title">{{ video.comments | selectattr('parent_id', 'none') | list | length }}
                        Comments</h3>
                    <div class="sort-selector">
                        <span>Sort by</span>
                        <button onclick="changeSort('newest')"
                            class="{{ 'active' if current_sort == 'newest' else '' }}">Newest</button>
                        <button onclick="changeSort('oldest')"
                            class="{{ 'active' if current_sort == 'oldest' else '' }}">Oldest</button>
                    </div>
                </div>

                {% with messages = get_flashed_messages(with_categories=true) %}
                {% if messages %}
                {% for category, message in messages %}
                <div class="flash-message flash-{{ category }}">{{ message }}</div>
                {% endfor %}
                {% endif %}
                {% endwith %}

                {% if current_user.is_authenticated %}
                <form class="comment-form" method="post"
                    action="{{ url_for('videos.post_comment', v=video.short_id) }}">
                    <textarea name="content" id="comment-content" placeholder="Write a comment..."
                        maxlength="5000"></textarea>
                    <div class="comment-form-footer">
                        <span class="char-counter"><span id="char-count">0</span> / 5000</span>
                        <button type="submit" class="btn-comment">Post Comment</button>
                    </div>
                </form>
                {% else %}
                <p class="login-prompt"><a href="{{ url_for('auth.login') }}">Log in</a> to post a comment.</p>
                {% endif %}

                {# Recursive macro for rendering comments and replies #}
                {% macro render_comment(comment, is_reply=false) %}
                <li class="{{ 'reply-item' if is_reply else 'comment-item' }}{{ ' comment-deleted' if comment.is_deleted else '' }}"
                    id="comment-{{ comment.id }}">
                    <div class="comment-header">
                        <a href="{{ url_for('auth.user_profile', username=comment.author_username) }}"
                            class="comment-author">{{ comment.author_username }}</a>
                        <span class="comment-date">{{ comment.created_at.strftime('%Y-%m-%d %H:%M') }}</span>
                        {% if not comment.is_deleted %}
                        {% if current_user.is_authenticated and comment.author_username == current_user.username %}
                        <div class="comment-actions">
                            <button type="button" class="btn-edit"
                                onclick="toggleEditForm({{ comment.id }})">Edit</button>
                            <form method="post" action="{{ url_for('videos.delete_comment', v=video.short_id) }}"
                                style="display: inline;">
                                <input type="hidden" name="comment_id" value="{{ comment.id }}">
                                <button type="submit" class="btn-delete"
                                    onclick="return confirm('Delete this comment?')">Delete</button>
                            </form>
                        </div>
                        {% elif current_user.is_authenticated and current_user.is_admin() %}
                        <div class="comment-actions">
                            <form method="post" action="{{ url_for('videos.delete_comment', v=video.short_id) }}"
                                style="display: inline;">
                                <input type="hidden" name="comment_id" value="{{ comment.id }}">
                                <button type="submit" class="btn-delete"
                                    onclick="return confirm('Delete this comment?')">Delete</button>
                            </form>
                        </div>
                        {% endif %}
                        {% endif %}
                    </div>
                    {% if comment.is_deleted %}
                    <div class="comment-content" id="comment-content-{{ comment.id }}">
                        {% if comment.deleted_by == 'admin' %}
                        [This comment has been removed by a moderator]
                        {% else %}
                        [This comment has been deleted by the author]
                        {% endif %}
                    </div>
                    {% else %}
                    <div class="comment-content" id="comment-content-{{ comment.id }}">{{ comment.content | urlize }}
                    </div>
                    {% if current_user.is_authenticated and comment.author_username == current_user.username %}
                    <form class="edit-form" id="edit-form-{{ comment.id }}" method="post"
                        action="{{ url_for('videos.edit_comment', v=video.short_id) }}">
                        <input type="hidden" name="comment_id" value="{{ comment.id }}">
                        <textarea name="content" maxlength="5000">{{ comment.content }}</textarea>
                        <div class="edit-form-actions">
                            <button type="submit" class="btn-save">Save</button>
                            <button type="button" class="btn-cancel"
                                onclick="toggleEditForm({{ comment.id }})">Cancel</button>
                        </div>
                    </form>
                    {% endif %}
                    {% endif %}

                    {# Reply button - available for all comments (deleted or not) #}
                    {% if current_user.is_authenticated %}
                    <button type="button" class="btn-reply" onclick="toggleReplyForm({{ comment.id }})">Reply</button>
                    <form class="reply-form" id="reply-form-{{ comment.id }}" method="post"
                        action="{{ url_for('videos.post_comment', v=video.short_id) }}">
                        <input type="hidden" name="parent_id" value="{{ comment.id }}">
                        <textarea name="content" placeholder="Write a reply..." maxlength="5000"></textarea>
                        <div class="reply-form-actions">
                            <button type="submit" class="btn-save">Reply</button>
                            <button type="button" class="btn-cancel"
                                onclick="toggleReplyForm({{ comment.id }})">Cancel</button>
                        </div>
                    </form>
                    {% endif %}

                    {# Display nested replies recursively #}
                    {% if comment.replies %}
                    <button type="button" class="replies-toggle" onclick="toggleReplies({{ comment.id }})">
                        <span class="toggle-icon">&#9660;</span>
                        <span id="reply-toggle-text-{{ comment.id }}">{{ comment.replies | length }} repl{{ 'ies' if
                            comment.replies | length > 1 else 'y' }}</span>
                    </button>
                    <div class="replies-container" id="replies-container-{{ comment.id }}">
                        <ul class="replies-list" id="replies-{{ comment.id }}">
                            {% for reply in comment.replies %}
                            {{ render_comment(reply, is_reply=true) }}
                            {% endfor %}
                        </ul>
                    </div>
                    {% endif %}
                </li>
                {% endmacro %}

                {% set top_level_comments = video.comments | selectattr('parent_id', 'none') | list %}
                {% if current_sort == 'oldest' %}
                {% set top_level_comments = top_level_comments | reverse | list %}
                {% endif %}
                {% if top_level_comments %}
                <ul class="comment-list">
                    {% for comment in top_level_comments %}
                    {{ render_comment(comment) }}
                    {% endfor %}
                </ul>
                {% else %}
                <p class="no-comments">No comments yet. Be the first to comment!</p>
                {% endif %}
            </div>
            {% endif %}
        </div><!-- end watch-main -->

        <!-- Recommended Videos Sidebar -->
        <aside class="watch-sidebar">
            <div class="recommended-videos">
                <h3>Recommended Videos</h3>
                {% if recommended_videos %}
                {% for rec_video in recommended_videos %}
                <a href="{{ url_for('videos.watch_video', v=rec_video.short_id) }}" class="recommended-item">
                    {% if rec_video.thumbnail %}
                    <img src="{{ url_for('videos.serve_thumbnail', filename=rec_video.thumbnail) }}"
                        alt="{{ rec_video.title or rec_video.filename }}" class="recommended-thumb">
                    {% else %}
                    <div class="recommended-thumb"></div>
                    {% endif %}
                    <div class="recommended-info">
                        <div class="recommended-title">{{ rec_video.title or rec_video.filename }}</div>
                        <div class="recommended-meta">
                            {{ rec_video.owner_username or 'Unknown' }}<br>
                            {{ rec_video.view_count }} view{{ 's' if rec_video.view_count != 1 else '' }}
                        </div>
                    </div>
                </a>
                {% endfor %}
                {% else %}
                <p class="no-recommendations">No recommendations available.</p>
                {% endif %}
            </div>
        </aside>
    </div><!-- end watch-layout -->

    <script src="{{ url_for('static', filename='node_modules/video.js/dist/video.min.js')}}"></script>
    <script
        src="{{ url_for('static', filename='node_modules/videojs-contrib-quality-levels/dist/videojs-contrib-quality-levels.min.js')}}"></script>
    <script
        src="{{ url_for('static', filename='node_modules/videojs-hls-quality-selector/dist/videojs-hls-quality-selector.min.js')}}"></script>
    <script src="{{ url_for('static', filename='node_modules/videojs-hotkeys/videojs.hotkeys.min.js')}}"></script>
    <script src="{{ url_for('static', filename='node_modules/jquery/dist/jquery.min.js')}}"></script>
    <script src="{{ url_for('static', filename='node_modules/videojs-markers/dist/videojs-markers.min.js')}}"></script>
    <script
        src="{{ url_for('static', filename='node_modules/videojs-sprite-thumbnails/dist/videojs-sprite-thumbnails.min.js')}}"></script>
    <script src="{{ url_for('static', filename='js/plugin-test.js')}}" type="text/javascript"></script>
    <script src="{{ url_for('static', filename='js/video-player.js')}}" type="text/javascript"></script>
    <script>
        const commentContent = document.getElementById('comment-content');
        const charCount = document.getElementById('char-count');
        if (commentContent && charCount) {
            commentContent.addEventListener('input', function () {
                charCount.textContent = this.value.length;
            });
        }

        function toggleChapterEdit(chapterId) {
            const editForm = document.getElementById('edit-chapter-form-' + chapterId);
            if (editForm) {
                editForm.style.display = editForm.style.display === 'none' ? 'block' : 'none';
            }
        }

        function toggleChapterAdd() {
            const addForm = document.getElementById('add-chapter-form');
            if (addForm) {
                addForm.style.display = addForm.style.display === 'none' ? 'block' : 'none';
            }
        }

        function toggleEditForm(commentId) {
            const editForm = document.getElementById('edit-form-' + commentId);
            const commentContent = document.getElementById('comment-content-' + commentId);
            if (editForm && commentContent) {
                editForm.classList.toggle('active');
                commentContent.style.display = editForm.classList.contains('active') ? 'none' : 'block';
            }
        }

        function toggleReplyForm(commentId) {
            const replyForm = document.getElementById('reply-form-' + commentId);
            if (replyForm) {
                replyForm.classList.toggle('active');
            }
        }

        function toggleReplies(commentId) {
            const container = document.getElementById('replies-container-' + commentId);
            const toggleBtn = container.previousElementSibling;
            if (container && toggleBtn) {
                const isExpanded = container.classList.contains('expanded');
                container.classList.toggle('expanded');
                toggleBtn.classList.toggle('expanded');
            }
        }

        function changeSort(order) {
            const url = new URL(window.location.href);
            url.searchParams.set('sort', order);
            window.location.href = url.toString();
        }

        function toggleShareMenu(button) {
            const menu = document.getElementById('share-menu');
            const isActive = menu.classList.contains('active');

            // Close all other menus first
            document.querySelectorAll('.share-menu.active').forEach(function (m) {
                m.classList.remove('active');
            });

            if (!isActive) {
                // Update timestamp display before showing menu
                updateShareTimestamp();
                menu.classList.add('active');
            }
        }

        function updateShareTimestamp() {
            const timestampSpan = document.getElementById('share-timestamp');
            if (typeof player !== 'undefined' && player.currentTime) {
                const seconds = Math.floor(player.currentTime());
                timestampSpan.textContent = formatTime(seconds);
            }
        }

        function formatTime(totalSeconds) {
            const hours = Math.floor(totalSeconds / 3600);
            const minutes = Math.floor((totalSeconds % 3600) / 60);
            const seconds = totalSeconds % 60;

            if (hours > 0) {
                return hours + ':' + String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
            }
            return minutes + ':' + String(seconds).padStart(2, '0');
        }

        function shareVideo(includeTimestamp) {
            const baseUrl = window.location.origin + window.location.pathname;
            const params = new URLSearchParams(window.location.search);

            if (includeTimestamp && typeof player !== 'undefined' && player.currentTime) {
                const seconds = Math.floor(player.currentTime());
                if (seconds > 0) {
                    params.set('t', seconds);
                } else {
                    params.delete('t');
                }
            } else {
                params.delete('t');
            }

            const url = baseUrl + (params.toString() ? '?' + params.toString() : '');
            const shareButton = document.querySelector('.btn-share');

            navigator.clipboard.writeText(url).then(function () {
                // Close menu
                document.getElementById('share-menu').classList.remove('active');

                // Show feedback on main button
                const originalText = shareButton.textContent;
                shareButton.textContent = 'Copied!';
                shareButton.classList.add('copied');
                setTimeout(function () {
                    shareButton.textContent = originalText;
                    shareButton.classList.remove('copied');
                }, 2000);
            }).catch(function (err) {
                console.error('Failed to copy URL:', err);
                alert('Failed to copy URL to clipboard');
            });
        }

        // Close share menu when clicking outside
        document.addEventListener('click', function (event) {
            if (!event.target.closest('.share-dropdown')) {
                document.querySelectorAll('.share-menu.active').forEach(function (menu) {
                    menu.classList.remove('active');
                });
            }
        });

        function openPlaylistModal() {
            const modal = document.getElementById('playlist-modal');
            const modalBody = document.getElementById('playlist-modal-body');
            modal.classList.add('active');

            // Load playlist content via AJAX
            fetch('{{ url_for("playlists.modal_content") }}?video_id={{ video.id if video else 0 }}&video_short_id={{ video.short_id if video else "" }}')
                .then(response => response.text())
                .then(html => {
                    modalBody.innerHTML = html;
                })
                .catch(err => {
                    modalBody.innerHTML = '<p style="color: #ff6b6b; padding: 20px;">Failed to load playlists.</p>';
                });
        }

        function closePlaylistModal() {
            const modal = document.getElementById('playlist-modal');
            modal.classList.remove('active');
        }

        // Close modal when clicking outside
        document.addEventListener('click', function (event) {
            const modal = document.getElementById('playlist-modal');
            if (event.target === modal) {
                closePlaylistModal();
            }
        });

        // Close modal with Escape key
        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                closePlaylistModal();
            }
        });
    </script>

    {% if current_user.is_authenticated and video %}
    <!-- Playlist Modal -->
    <div id="playlist-modal" class="modal-overlay">
        <div class="modal-content" style="position: relative;">
            <button type="button" class="modal-close" onclick="closePlaylistModal()">&times;</button>
            <div id="playlist-modal-body">
                <div class="playlist-modal-header">
                    <h3>Add to Playlist</h3>
                </div>
                <div class="playlist-modal-body">
                    <p style="color: #888;">Loading...</p>
                </div>
            </div>
        </div>
    </div>
    {% endif %}
</body>

</html>