{% extends "base.html" %}
{% block title %}Board View{% endblock %}
{% block content %}
<!--<h2>{{ board.name }}</h2>-->

<script type="text/javascript">
    // Определяем currentBoardId, чтобы он был доступен в JavaScript
    const currentBoardId = {{ board.id }};
</script>

<div id="board-wrapper">
    <div id="board">
        {% for note in notes %}
        <div class="note" data-id="{{ note.id }}"
            style="left: {{ note.x }}px; top: {{ note.y }}px; width: {{ note.width }}px; height: {{ note.height }}px;">
            <textarea>{{ note.text }}</textarea>
        </div>
        {% endfor %}
        {% for image in images %}
        <div class="image hidden" data-id="{{ image.id }}"
            style="left: {{ image.x }}px; top: {{ image.y }}px; width: {{ image.width }}px; height: {{ image.height }}px;">
            <img src="{{ image.url }}" style="width: 100%; height: 100%; object-fit: contain;">
        </div>
        {% endfor %}
        {% for audio in audios %}
        <div class="audio" data-id="{{ audio.id }}"
            style="left: {{ audio.x }}px; top: {{ audio.y }}px; width: {{ audio.width }}px; height: {{ audio.height }}px;">
            <div class="audio-file-name">{{ audio.file_name }}</div>
            <audio src="{{ audio.url }}"></audio>
            <div class="controls">
                <button class="play-pause">▶️</button>
                <button class="stop">⏹️</button>
                <input class="progress-bar" type="range" min="0" step="0.1" max="32.078333">
            </div>
            <div class="resize-handle"></div>
        </div>
        {% endfor %}
        {% for link in links %}
        <div class="link" data-id="{{ link.id }}"
            style="position: absolute; left: {{ link.x }}px; top: {{ link.y }}px; width: {{ link.width }}px; height: {{ link.height }}px; border: 1px solid #ccc; background-color: #f5f5f5; padding: 5px; box-sizing: border-box;">
            <a href="{{ link.url }}" target="_blank" style="text-decoration: none; color: #333;">{{ link.name }}</a>
        </div>
        {% endfor %}
    </div>
</div>

<div id="menu-container">
    <button id="menu-button">Menu</button>
    <div id="dropdown-menu" class="hidden">
        <button id="add-note">Add Comment</button>
        <button id="add-image">Add Image</button>
        <button id="add-audio">Add Audio</button>
        <button id="add-link">Add Link</button>
        <button id="toggle-fullscreen">Toggle Fullscreen</button>
        <button id="toggle-vr">Toggle VR</button>
    </div>
</div>

<!-- Подключение Socket.io -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>

<!-- Инициализация Socket -->
<script src="{{ url_for('static', filename='js/socket.js') }}"></script>

<!-- Другие JavaScript файлы -->
<script src="{{ url_for('static', filename='js/fullscreen.js') }}"></script>
<script src="{{ url_for('static', filename='js/upload.js') }}"></script>
<script src="{{ url_for('static', filename='js/contextMenu.js') }}"></script>
<script src="{{ url_for('static', filename='js/resize.js') }}"></script>
<script src="{{ url_for('static', filename='js/notes.js') }}"></script>
<script src="{{ url_for('static', filename='js/images.js') }}"></script>
<script src="{{ url_for('static', filename='js/audio.js') }}"></script>
<script src="{{ url_for('static', filename='js/link.js') }}"></script>
<script src="{{ url_for('static', filename='js/board.js') }}"></script>
<script src="{{ url_for('static', filename='js/vr.js') }}"></script>
<script src="{{ url_for('static', filename='js/main.js') }}"></script>

{% endblock %}

socket.on('new_link', (data) => {
    const linkElement = createLinkElement(data);
    document.getElementById('board').appendChild(linkElement);
});

function createLinkElement(data) {
    const link = document.createElement('div');
    link.className = 'link';
    link.dataset.id = data.id;

    // Установка стилей прямо внутри JavaScript
    Object.assign(link.style, {
        position: 'absolute',
        left: `${data.x}px`,
        top: `${data.y}px`,
        width: `${data.width}px`,
        height: `${data.height}px`,
        border: '1px solid #ccc',
        backgroundColor: '#f5f5f5',
        padding: '5px',
        boxSizing: 'border-box',
        cursor: 'pointer',
    });

    const anchor = document.createElement('a');
    anchor.href = data.url;
    anchor.target = '_blank';
    Object.assign(anchor.style, {
        textDecoration: 'none',
        color: '#333',
    });
    anchor.textContent = data.name;

    link.appendChild(anchor);

    // Добавляем обработчики событий
    addLinkEventListeners(link, data.id);

    return link;
}

// Добавление слушателей событий для элемента ссылки
function addLinkEventListeners(link, id) {
    link.addEventListener('mouseenter', () => {
        link.style.backgroundColor = '#e0e0e0';
    });

    link.addEventListener('mouseleave', () => {
        link.style.backgroundColor = '#f5f5f5';
    });

    link.addEventListener('mousedown', (e) => {
        if (e.button !== 0) return; // Только левая кнопка мыши
        e.preventDefault();
        e.stopPropagation();
        const startX = e.clientX;
        const startY = e.clientY;
        const startLeft = parseFloat(link.style.left) || 0;
        const startTop = parseFloat(link.style.top) || 0;

        function moveLink(e) {
            const deltaX = (e.clientX - startX) / scale;
            const deltaY = (e.clientY - startY) / scale;
            link.style.left = `${startLeft + deltaX}px`;
            link.style.top = `${startTop + deltaY}px`;
            const x = parseFloat(link.style.left) || 0;
            const y = parseFloat(link.style.top) || 0;
            const width = link.offsetWidth;
            const height = link.offsetHeight;
            socket.emit('update_link', { id, name: link.querySelector('a').textContent, url: link.querySelector('a').href, x, y, width, height });
        }

        document.addEventListener('mousemove', moveLink);

        document.addEventListener('mouseup', () => {
            document.removeEventListener('mousemove', moveLink);
        }, { once: true });
    });

    link.addEventListener('dblclick', (e) => {
        e.preventDefault();
        e.stopPropagation();
        showContextMenu(link, id, e.clientX, e.clientY); // Предполагается, что у вас есть такая функция
    });

    addResizeListeners(link, id);
}

function addResizeListeners(element, id) {
    const resizeHandle = document.createElement('div');
    resizeHandle.style.position = 'absolute';
    resizeHandle.style.width = '10px';
    resizeHandle.style.height = '10px';
    resizeHandle.style.right = '0';
    resizeHandle.style.bottom = '0';
    resizeHandle.style.cursor = 'se-resize';
    resizeHandle.style.backgroundColor = '#ccc';

    element.appendChild(resizeHandle);

    resizeHandle.addEventListener('mousedown', function(e) {
        e.preventDefault();
        e.stopPropagation();

        const startX = e.clientX;
        const startY = e.clientY;
        const startWidth = element.offsetWidth;
        const startHeight = element.offsetHeight;

        function resizeElement(e) {
            const newWidth = startWidth + (e.clientX - startX) / scale;
            const newHeight = startHeight + (e.clientY - startY) / scale;
            element.style.width = `${newWidth}px`;
            element.style.height = `${newHeight}px`;
            socket.emit('update_link', { id, name: element.querySelector('a').textContent, url: element.querySelector('a').href, x: element.offsetLeft, y: element.offsetTop, width: newWidth, height: newHeight });
        }

        document.addEventListener('mousemove', resizeElement);

        document.addEventListener('mouseup', () => {
            document.removeEventListener('mousemove', resizeElement);
        }, { once: true });
    });
}

// Добавление нового элемента-ссылки на доску
document.getElementById('add-link').addEventListener('click', showLinkForm);

function showLinkForm() {
    const formHtml = `
        <div id="link-form" style="position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); background:white; padding:20px; border-radius:8px; box-shadow:0 0 10px rgba(0,0,0,0.1); z-index: 1000;">
            <label for="link-name" style="display:block; margin-bottom:8px;">Название ссылки:</label>
            <input type="text" id="link-name" placeholder="Введите имя ссылки" style="width: calc(100% - 22px); padding:10px; margin-bottom:12px; border:1px solid #ccc; border-radius:4px;"><br>
            <label for="link-url" style="display:block; margin-bottom:8px;">URL:</label>
            <input type="text" id="link-url" placeholder="Введите URL" style="width: calc(100% - 22px); padding:10px; margin-bottom:12px; border:1px solid #ccc; border-radius:4px;"><br>
            <button id="add-link-submit" style="padding:10px 20px; background-color:#007bff; color:white; border:none; border-radius:4px; cursor:pointer; margin-right:8px;">Добавить ссылку</button>
            <button id="cancel-link" style="padding:10px 20px; background-color:#ccc; color:white; border:none; border-radius:4px; cursor:pointer;">Отмена</button>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', formHtml);

    document.getElementById('add-link-submit').addEventListener('click', submitLinkForm);
    document.getElementById('cancel-link').addEventListener('click', closeModal);
}

function submitLinkForm() {
    const name = document.getElementById('link-name').value;
    const url = document.getElementById('link-url').value;

    if (name && url) {
        const rect = boardWrapper.getBoundingClientRect();
        const width = 150;
        const height = 30;
        const centerX = ((rect.width / 2 - translateX) / scale) - width / 2;
        const centerY = ((rect.height / 2 - translateY) / scale) - height / 2;

        socket.emit('create_link', {
            name: name,
            url: url,
            x: centerX,
            y: centerY,
            width,
            height,
            board_id: currentBoardId
        });
        closeModal();
    }
}

function closeModal() {
    const form = document.getElementById('link-form');
    if (form) {
        form.remove();
    }
}

// Функция для обработки существующих ссылок на доске
function handleExistingLinks() {
    document.querySelectorAll('.link').forEach(link => {
        const id = link.dataset.id;
        addLinkEventListeners(link, id);
    });
}

Вынеси все стили для link в файл link.css