{% extends "base.html" %}

{% block content %}
<div class="container mt-4">
    <div class="row">

        <!-- Related Videos Section -->
<div class="col-md-3 order-md-2" style="margin-left: 20px;">
    <h5>Related Videos</h5>
    {% for vid in random_videos %}
    <div class="related-video mb-3">
        <a href="/video/{{ vid.id }}" class="text-decoration-none text-dark">
            <img src="{{ url_for('static', filename='pre/' ~ vid.id ~ '.jpg') }}" class="img-fluid mb-1 related-video-img" alt="{{ vid.title }}">
            <p class="mt-3">{{ vid.title }}</p>
        </a>
        <div class="mt-2">
    <div class="avatar-container">
        <img src="{{ url_for('static', filename='avatars/' ~ vid.author.avatar) }}" alt="{{ vid.author.name }}" class="related-avatar me-2">
    </div>
    <div class="d-flex align-items-center">
        <a class="text-decoration-none text-dark h5 mb-0" href="{{ url_for('video', video_id=vid.id) }}"></a>
    </div>
    <p class="mb-1">
        <a class="text-decoration-none text-dark" href="{{ url_for('user', user_id=vid.author.id) }}">
            {{ vid.author.name }} {{ vid.author.surname }}
        </a>
    </p>
    <p class="text-muted mb-0">
        {{ vid.views }} {{ vid.views | decline_views }} -
        Загружено {{ vid.datetime | timesince }}
    </p>
</div>
    </div>
    {% endfor %}
</div>

<style>


/* Само видео */
.video-element {
    width: 960px; /* Устанавливаем фиксированную ширину */
    height: 543px;
 /* Растягиваем по высоте контейнера *//* Обеспечиваем масштабирование видео с обрезкой */
    background: black; /* Фон для видео, если пропорции не совпадают */
}
    .related-avatar {
        width: 40px; /* Установите фиксированную ширину для аватара */
        height: 40px; /* Установите фиксированную высоту для аватара */
        object-fit: cover; /* Это гарантирует, что аватар сохраняет пропорции и не растягивается */
        /* Убедитесь, что этот стиль рассчитывается в рамках контейнера */
    }

    .avatar-container {
        width: 40px;
        height: 40px;
        border-radius: 50%; /* Закругляем аватар */
        overflow: hidden; /* Удаляет все, что выходит за рамки */
        display: inline-block; /* Этот стиль помогает избежать проблем с выравниванием */
    }
</style>

<style>
    .related-video-img {
        width: 300px;
        height: 170px;
        object-fit: cover; /* This will ensure the image maintains aspect ratio and is not stretched */
    }
</style>
<script type=text/javascript>
                function follow() {
                    var follow = document.getElementById("follow");
                    var unfollow = document.getElementById("unfollow");
                    var followers = document.getElementById("followers");
                    if ( follow.classList.contains('active') )
                    {
                        follow.classList.remove("active");
                        followers.innerHTML = parseInt(followers.innerText) - 1;
                        $.post('/api/not_follow/{{ current_video.author }}');
                    }
                    else
                    {
                        follow.classList.add("active");
                        followers.innerHTML = parseInt(followers.innerText) + 1;
                        $.post('/api/follow/{{ current_video.author }}');
                        if ( unfollow.classList.contains('active') )
                        {
                            unfollow.classList.remove("active");
                            followers.innerHTML = parseInt(followers.innerText) + 1;
                        }
                    }
                }
            </script>
            <script>
    function toggleLike(videoId) {
    const likeBtn = document.getElementById("like");
    const likesSpan = document.getElementById("likes");
    const isActive = likeBtn.classList.contains('active');

    const apiUrl = isActive ? `/api/not_like/${videoId}` : `/api/like/${videoId}`;

    fetch(apiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(err => { throw new Error(err.message); });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            likesSpan.innerText = data.new_like_count; // Update like count
            likeBtn.classList.toggle('active'); // Toggle button state
        } else {
            console.error('Failed to update like status:', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
}
</script>
        <!-- Main Video Section -->
        <div class="col-md-9 order-md-1"> <!-- Right Side for Main Video -->
            <div class="video-container paused" data-volume-level="high">
                <img class="thumbnail-img">
                <div class="video-controls-container">
                    <!-- Control elements -->
                </div>
                <div class="video-container">
                <video width="100%" autoplay src="{{ video_src }}" controls autoplay width="408" class="video-element">
                    <track kind="captions" srclang="en" src="assets/subtitles.vtt">
                </video>
                </div>
            </div>

            <!-- Video Title and Details -->
            <h3 class="mt-3">{{ current_video.title }}</h3>
            <p><svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="currentColor" class="bi bi-eye" viewBox="0 0 16 16">
  <path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8M1.173 8a13 13 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5s3.879 1.168 5.168 2.457A13 13 0 0 1 14.828 8q-.086.13-.195.288c-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5s-3.879-1.168-5.168-2.457A13 13 0 0 1 1.172 8z"/>
  <path d="M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5M4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0"/>
</svg> {{ current_video.views }} {{ current_video.views | decline_views }}</p>
            <p>Загружено {{ current_video.datetime | timesince }} назад</p>
            {% if authenticated %}
    <button onclick="toggleLike('{{ current_video.id }}')"
        class="btn btn-outline-danger btn-sm {% if current_video.id in current_user.get_likes() %} active {% endif %}"
        type="button" id="like" {% if not authenticated or current_user.id == current_video.author %} disabled {% endif %}>


        {% if current_video.id in current_user.get_likes() %}
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <g id="style=fill">
                    <g id="like">
                        <path id="Subtract" fill-rule="evenodd" clip-rule="evenodd" d="M15.9977 5.63891C16.2695 4.34931 15.433 3.00969 14.2102 2.59462C13.6171 2.37633 12.9892 2.4252 12.4662 2.60499C11.9449 2.78419 11.4461 3.12142 11.1369 3.58441L11.136 3.58573L7.49506 9.00272C8.05104 9.29585 8.43005 9.87954 8.43005 10.5518V21.3018H6.91003V21.3018H16.6801C18.2938 21.3018 19.2028 20.2977 19.8943 19.202C20.6524 18.0009 21.1453 16.7211 21.5116 15.5812C21.6808 15.0546 21.8252 14.5503 21.9547 14.0984L21.9863 13.9881C22.126 13.5007 22.2457 13.0904 22.366 12.7549C22.698 11.8292 22.5933 10.9072 22.067 10.2072C21.5476 9.5166 20.7005 9.15175 19.76 9.15175H15.76C15.6702 9.15175 15.6017 9.11544 15.5599 9.06803C15.5238 9.02716 15.4831 8.95058 15.502 8.81171L15.9977 5.63891Z" fill="#000000"/>
                        <path id="rec" d="M2.18005 10.6199C2.18005 10.03 2.62777 9.55176 3.18005 9.55176H6.68005C7.23234 9.55176 7.68005 10.03 7.68005 10.6199V21.3018H3.18005C2.62777 21.3018 2.18005 20.8235 2.18005 20.2336V10.6199Z" fill="#000000"/>
                    </g>
                </g>
            </svg>
        {% else %}

            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g fill-rule="evenodd" clip-rule="evenodd" fill="#000">
    <path d="M14.21 2.595c1.223.415 2.06 1.754 1.788 3.044l-.496 3.173c-.019.139.022.215.058.256.042.047.11.084.2.084h4c.94 0 1.787.365 2.307 1.055.526.7.63 1.622.299 2.548-.12.335-.24.746-.38 1.233l-.031.11a48 48 0 0 1-.443 1.483c-.367 1.14-.86 2.42-1.618 3.621-.691 1.096-1.6 2.1-3.214 2.1H6.66v-1.5h10.02c.821 0 1.338-.437 1.946-1.4.662-1.05 1.109-2.195 1.457-3.28.162-.502.3-.985.43-1.44l.031-.107c.137-.478.27-.937.41-1.326.188-.525.093-.903-.086-1.14-.186-.247-.548-.457-1.108-.457h-4c-1.043 0-1.909-.892-1.742-2.056v-.01l.505-3.224.005-.023c.11-.498-.243-1.138-.805-1.326l-.013-.004-.013-.005c-.203-.076-.47-.074-.743.02-.278.095-.48.257-.57.394l-.002.002-4.1 6.1-1.245-.837 4.099-6.097v-.002c.31-.463.809-.8 1.33-.979.523-.18 1.151-.229 1.744-.01"/>
    <path d="M1.43 10.552c0-.967.784-1.75 1.75-1.75h3.5c.967 0 1.75.783 1.75 1.75v10.75H3.18a1.75 1.75 0 0 1-1.75-1.75zm1.75-.25a.25.25 0 0 0-.25.25v9c0 .138.112.25.25.25h3.75v-9.25a.25.25 0 0 0-.25-.25z"/>
  </g>
</svg>
        {% endif %}

        <span id="likes">{{ current_video.likes }}</span>
    </button>
{% endif %}
<p>


            <div class="d-flex align-items-center mb-3">
            <a href="/user/{{ author.id }}" class="text-decoration-none text-dark">
                <img src="{{ avatar_url }}" alt="Avatar" class="img-fluid rounded-circle me-2" style="width:90px; height:90px;">
                </a>
                <div>
                    <a href="/user/{{ author.id }}" class="text-decoration-none text-dark">{{ author.name }} {{ author.surname }} </a>
                    <div>
                        <button onclick="follow()" class="btn btn-outline-danger btn-sm {% if subscription %} active {% endif %}" type="submit" name="follow" id="follow" {% if not authenticated or current_user.id == current_video.author %} disabled {% endif %}>
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-person-plus-fill" viewBox="0 0 16 16">
                            <path d="M1 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"/>
                            <path fill-rule="evenodd" d="M13.5 5a.5.5 0 0 1 .5.5V7h1.5a.5.5 0 0 1 0 1H14v1.5a.5.5 0 0 1-1 0V8h-1.5a.5.5 0 0 1 0-1H13V5.5a.5.5 0 0 1 .5-.5z"/>
                        </svg>
                        <span id="followers">{{ author.followers }}</span>
                    </button>
                        <div class="col-auto">

                </div>
                    <script language="JavaScript" type="text/javascript" src="/static/js/jquery-1.2.6.min.js"></script>
<script language="JavaScript" type="text/javascript" src="/static/js/jquery-ui-personalized-1.5.2.packed.js"></script>
<script language="JavaScript" type="text/javascript" src="/static/js/sprinkle.js"></script>

                    </div>
                </div>
            </div>

    <div>

   {% if current_video.description %}
   <h4>Описание видео:</h4>
        <p id="description-text" class="description">
            {{ current_video.description | truncate(100, '...') }}
            {% if current_video.description | length > 100 %}
                <span class="toggle-description" style="cursor: pointer;">[Развернуть]</span>
            {% endif %}
        </p>
    {% else %}

    {% endif %}
</div>

<script>
// Функция для обработки клика на кнопке развертывания/сворачивания
document.addEventListener("DOMContentLoaded", function() {
    const toggleDescriptions = document.querySelectorAll('.toggle-description');

    toggleDescriptions.forEach(function(toggle) {
        toggle.addEventListener('click', function() {
            // Получаем полное описание из Jinja2, экранируя его
            const fullDescription = {{ current_video.description | tojson | safe }};

            // Проверяем, развернуто описание или свернуто (по наличию ... в тексте)
            if (this.parentElement.textContent.includes('...')) {
                this.parentElement.innerHTML = fullDescription + ' <span class="toggle-description" style="cursor: pointer;">[Свернуть]</span>';
            } else {
                this.parentElement.innerHTML = "{{ current_video.description | truncate(100, '...') }} <span class='toggle-description' style='cursor: pointer;'>[Развернуть]</span>";
            }
        });
    });
});
</script>
            {% if authenticated and current_user.id == current_video.author.id %}
    <a href="{{ url_for('edit_video', video_id=current_video.id) }}" class="btn btn-warning">Изменить видео</a>
    <form action="{{ url_for('delete_video', video_id=current_video.id) }}" style="display: inline;">
        <button type="submit" class="btn btn-danger">Удалить Видео</button>
    </form>
{% endif %}
            <!-- Share Modal (Only for Author) -->
            {% if authenticated and current_user.id == current_video.author.id %}
                <!-- Share Modal -->
                <div class="modal fade" id="shareModal" tabindex="-1" aria-labelledby="shareModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="shareModalLabel">Ссылка для общего доступа</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
                            </div>
                            <div class="modal-body">
                                <div class="mb-3">
                                    <label for="sharedLinkInput" class="form-label">Ссылка:</label>
                                    <input type="text" class="form-control" id="sharedLinkInput" readonly>
                                </div>
                                <button class="btn btn-secondary" id="copyLinkButton">Скопировать ссылку</button>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Закрыть</button>
                            </div>
                        </div>
                    </div>
                </div>
            {% endif %}
            <button id="shareBtn" class="btn btn-primary me-2">Поделиться</button>
            <script>
    // Share Functionality
    document.getElementById('shareBtn').addEventListener('click', () => {
        const currentURL = window.location.href;

        // Create a temporary input element to hold the URL
        const tempInput = document.createElement('input');
        tempInput.value = currentURL;
        document.body.appendChild(tempInput);

        // Select and copy the URL from the temporary input element
        tempInput.select();
        document.execCommand('copy'); // Legacy method for compatibility

        // Remove the temporary input element from the DOM
        document.body.removeChild(tempInput);

        // Show a confirmation alert
        alert('Ссылка скопирована!');
    });

    // You can add other JavaScript functions here, like liking comments or editing them.
</script>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const shareButton = document.getElementById('shareButton');
      const shareModal = new bootstrap.Modal(document.getElementById('shareModal'));
      const sharedLinkInput = document.getElementById('sharedLinkInput');
      const copyLinkButton = document.getElementById('copyLinkButton');

      if (shareButton) {
        shareButton.addEventListener('click', function () {
          fetch("{{ url_for('share_video', video_id=current_video.id) }}", {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
                // Ensure CSRF token is included
            },
            body: JSON.stringify({})
          })
          .then(response => response.json())
          .then(data => {
            if (data.shared_url) {
              sharedLinkInput.value = data.shared_url;
              shareModal.show();
            } else {
              alert('Не удалось получить ссылку для общего доступа.');
            }
          })
          .catch(error => {
            console.error('Error:', error);
            alert('Произошла ошибка при генерации ссылки.');
          });
        });
      }

      if (copyLinkButton) {
        copyLinkButton.addEventListener('click', function () {
          sharedLinkInput.select();
          sharedLinkInput.setSelectionRange(0, 99999); // For mobile devices
          document.execCommand('copy');
          copyLinkButton.textContent = 'Скопировано!';
          setTimeout(() => {
            copyLinkButton.textContent = 'Скопировать ссылку';
          }, 2000);
        });
      }

      // Revoke Share Button
      const revokeShareButton = document.getElementById('revokeShareButton');
      const revokeModal = new bootstrap.Modal(document.getElementById('revokeModal'));

      if (revokeShareButton) {
        revokeShareButton.addEventListener('click', function () {
          revokeModal.show();
        });
      }
    });
  </script>
 <script>
        function like(videoId) {
            fetch(`/api/like/${videoId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const likesSpan = document.getElementById('likes');
                    likesSpan.innerText = data.new_like_count;
                } else {
                    console.error('Failed to like the video:', data.message);
                }
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
<script>
function toggleLikeComment(commentId) {
    const likeButton = document.getElementById(`like-btn-${commentId}`);
    const likesCount = document.getElementById(`comment-likes-${commentId}`);
    const isLiked = likeButton.classList.contains('active'); // Check if the button is "liked"
    const apiUrl = isLiked ? `/api/comments/${commentId}/unlike` : `/api/comments/${commentId}/like`;

    // Send a POST request to like/unlike the comment
    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update likes count
            likesCount.innerText = data.likes;

            // Update button state (toggle active class and icon)
            if (isLiked) {
                likeButton.classList.remove('btn-primary', 'active');
                likeButton.classList.add('btn-outline-primary');
                document.getElementById(`like-btn-icon-${commentId}`).innerText = "🤍";
            } else {
                likeButton.classList.remove('btn-outline-primary');
                likeButton.classList.add('btn-primary', 'active');
                document.getElementById(`like-btn-icon-${commentId}`).innerText = "👍";
            }
        } else {
            console.error(data.message);
        }
    })
    .catch(error => console.error('Error:', error));
}
</script>
            <!-- Comments Section -->
<div class="comments-section mt-5">
    <h4>Комментарии</h4>
    {% if authenticated and not current_user.is_blocked %}
    <form action="" method="post" id="comment-form">
        {{ form.hidden_tag() }}
        <div class="mb-3">
            {{ form.content(class="form-control", placeholder="Ваш комментарий...", maxlength="50", id="comment-content") }}
            <div id="commentCount" class="text-muted">Осталось: <span id="commentRemaining">50</span> символов</div>
            {% for error in form.content.errors %}
            <div class="alert alert-danger" role="alert">
                {{ error }}
            </div>
            {% endfor %}
        </div>
        <button type="submit" class="btn btn-primary">Отправить</button>
    </form>
    {% elif authenticated and current_user.is_blocked %}
    <p>Ваш аккаунт заблокирован, вы не можете комментировать.</p>
    {% else %}
    <p>Вы должны <a href="{{ url_for('login') }}">войти</a> или <a href="{{ url_for('register') }}">зарегистрироваться</a>, чтобы оставлять комментарии.</p>
    {% endif %}
    <p>

    <!-- Comments List -->
{% for comment in comments %}
<div class="media mb-3">
    <img src="{{ url_for('static', filename='avatars/' ~ comment.user.avatar) }}" alt="Avatar" class="mr-3 rounded-circle" style="width:50px; height:50px;">
    <div class="media-body">
        <h5 class="mt-0">
            <a href="{{ url_for('user', user_id=comment.user.id) }}" class="text-decoration-none text-dark">{{ comment.user.name }} {{ comment.user.surname }}</a>
        </h5>

        <p id="comment-{{ comment.id }}" class="comment-text" data-full-description="{{ comment.content | tojson | safe }}">
            {{ comment.content | safe }}  <!-- Замените truncate на safe -->
        </p>

        <small class="text-muted">{{ comment.datetime.strftime('%Y-%m-%d %H:%M') }}</small>

        <!-- Like Button -->
        <button onclick="toggleLikeComment({{ comment.id }})"
        id="like-btn-{{ comment.id }}"
        class="btn btn-sm {% if comment.liked %} btn-primary active {% else %} btn-outline-primary {% endif %}">
    <span id="like-btn-icon-{{ comment.id }}">{{ "👍" if comment.liked else "🤍" }}</span>
    <span id="comment-likes-{{ comment.id }}">{{ comment.likes }}</span>
</button>

        {% if current_user.is_authenticated and current_user.id == comment.user_id %}

        <form action="{{ url_for('delete_comment', comment_id=comment.id) }}" method="post" style="display: inline;">
            <button type="submit" class="btn btn-sm btn-outline-danger">Удалить</button>
        </form>
        {% endif %}
    </div>
</div>
{% endfor %}

</div>


        </div>

    </div>
</div>

<script>
    // JavaScript for actions such as copy, like, follow
    document.getElementById('copyBtn').addEventListener('click', () => {
        const currentURL = window.location.href;
        const tempInput = document.createElement('input');
        tempInput.value = currentURL;
        document.body.appendChild(tempInput);
        tempInput.select();
        document.execCommand('copy');
        document.body.removeChild(tempInput);
        alert('Ссылка скопирована!');
    });

    // Follow and like function implementations
</script>

<style>
    .video-container {
        width: 100%; /* Ensure full width within column */
    }

    .related-video img {
        width: 100%;
        border-radius: 4px;
    }
</style>

{% endblock %}
по какой-то причине релейтед видеос оказываются под комментариями