{% extends "base.html" %}

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

        <!-- Related Videos Section -->
        <div class="col-md-3 order-md-2"> <!-- Left Side for Related Videos -->
            <h5>Related Videos</h5>
            {% for vid in last_videos %}
            <div class="related-video mb-3">
                <a href="/video/{{ vid.id }}" class="text-decoration-none text-dark" width="408" height="230">
                    <img src="/static/pre/{{ vid.id }}.jpg" class="img-fluid mb-1" >
                    <p class="mt-3">{{ vid.title }}</p>
                </a>
            </div>
            {% endfor %}
        </div>

        <!-- 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>
                <video width="100%" autoplay src="{{ video_src }}" controls autoplay width="408" >
                    <track kind="captions" srclang="en" src="assets/subtitles.vtt">
                </video>
            </div>

            <!-- Video Title and Details -->
            <h3 class="mt-3">{{ current_video.title }}</h3>
            <p>Загружено {{ current_video.datetime | timesince }} назад</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>
                        <button onclick="like()" class="btn btn-outline-danger btn-sm {% if like %} active {% endif %}" type="submit" name="like" id="like" {% 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-heart-fill" viewBox="0 0 16 16">
                            <path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/>
                        </svg>
                        <span id="likes">{{ current_video.likes }}</span>
                    </button>
                    <script language="JavaScript" type="text/javascript" src="/js/jquery-1.2.6.min.js"></script>
<script language="JavaScript" type="text/javascript" src="/js/jquery-ui-personalized-1.5.2.packed.js"></script>
<script language="JavaScript" type="text/javascript" src="/js/sprinkle.js"></script>
 <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;
                        }
                    }
                }

                function like() {
                    var like = document.getElementById("like");
                    var dislike = document.getElementById("dislike");
                    var likes = document.getElementById("likes");
                    if ( like.classList.contains('active') )
                    {
                        like.classList.remove("active");
                        likes.innerHTML = parseInt(likes.innerText) - 1;
                        $.post('/api/not_like/{{ current_video.id }}');
                    }
                    else
                    {
                        like.classList.add("active");
                        likes.innerHTML = parseInt(likes.innerText) + 1;
                        $.post('/api/like/{{ current_video.id }}');
                        if ( dislike.classList.contains('active') )
                        {
                            dislike.classList.remove("active");
                            likes.innerHTML = parseInt(likes.innerText) + 1;
                        }
                    }
                }
            </script>
                    </div>
                </div>
            </div>

            <p style="color: #808080">{{ current_video.description }}</p>
            {% if authenticated and (current_user.id |int == current_video.author |int or current_user.id == 1) %}
            <a href="{{ url_for('edit_video', video_id=current_video.id) }}" class="btn btn-warning">Edit Video</a>
            <form action="{{ url_for('delete_video', video_id=current_video.id) }}" style="display: inline;">
                <button type="submit" class="btn btn-danger">Delete Video</button>
            </form>

            {% endif %}
            {% if authenticated and current_user.id == author.id %}
    <button type="button" class="btn btn-success" id="shareButton">
      Поделиться
    </button>
    
    <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">
          <input type="text" class="form-control" id="sharedLinkInput" readonly>
          <button class="btn btn-secondary mt-2" id="copyLinkButton">Скопировать ссылку</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 likeComment(commentId) {
        fetch(`/api/like_comment/${commentId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({}), // Optionally send payload if needed
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const likeBtn = document.getElementById(`like-btn-${commentId}`);
                const likesCount = document.getElementById(`comment-likes-${commentId}`);
                likesCount.innerText = data.new_like_count;
                likeBtn.classList.toggle('active');
            } else {
                console.error(data.message);
            }
        })
        .catch(error => console.error('Error:', error));
    }
</script>
            <!-- Comments Section -->


           <div class="comments-section mt-5">
    <h4>Comments</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="Ваш комментарий...") }}
            {{ form.parent_id(value=0) }}
            {% for error in form.content.errors %}
            <div class="alert alert-danger" role="alert">
                {{ error }}
            </div>
            {% endfor %}
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    {% elif authenticated and current_user.is_blocked %}
    <p>Your account is blocked, you cannot comment.</p>
    {% else %}
    <p>Вы должны <a href="{{ url_for('login') }}">Войти</a> или <a href="{{ url_for('register') }}">Зарегистрироваться</a> чтобы писать комментарии.</p>
    {% endif %}

    <!-- 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>{{ comment.content }}</p>
            <small class="text-muted">{{ comment.datetime.strftime('%Y-%m-%d %H:%M') }}</small>

            <!-- Like Button -->
            <div class="d-flex mt-2">
                <button onclick="likeComment({{ comment.id }})" class="btn btn-sm btn-outline-primary me-2" id="like-btn-{{ comment.id }}">
                    Like <span id="comment-likes-{{ comment.id }}">{{ comment.likes }}</span>
                </button>

                <!-- Edit and Delete Buttons for Author -->
                {% if current_user.is_authenticated and current_user.id == comment.user_id or current_user.id ==1 %}
                <a href="{{ url_for('edit_comment', comment_id=comment.id) }}" class="btn btn-sm btn-outline-warning me-2">Edit</a>
                <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">Delete</button>
                </form>
                {% endif %}
            </div>
        </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 %}
fix the modal using bootstrao