<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Eversync</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    {% load static %}
    <link rel="icon" href="{% static 'favicon.ico' %}">
    <link rel="stylesheet" href="{% static 'index-style.css' %}" ">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.0/fabric.min.js"></script>
    {% block scripts %}
        {% include "sentry_replay.html" %}
    {% endblock %}


    <style>
        .container {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.welcome-box {
  flex: 0 0 auto;
  padding: 20px;
  border-radius: 8px;
  width: 100%;
  max-width: 800px;
}

/* On mobile */
@media (max-width: 700px) {
  .container {
    flex-direction: column;
    align-items: center; 
  }
  .welcome-box {
    flex: none;
    width: 100%;
    max-width: 100%;
    margin: 0 0 20px 0; 
    padding: 15px;
  }
  .content-box {
    width: 100%;
  }
  #whiteboard {
    width: 100%;
    height: auto;
  }
}

#whiteboard {
  border: 2px solid #4B0082;
  border-radius: 8px;
  background-color: white;
}

    </style>
</head>
    
</head>
<body>
    <div class="header">
        <div class="header-content">
            <a href="/"><img src="{% static 'eversync2.png' %}" alt="Eversync Logo" style="height: 80px; margin-right: 10px; display: flex; align-items: center; gap: 5px;"></a>
            <a href="/" class="logo" >eversync</a>
            <div class="nav-links" style="position: relative;">
                <div class="dropdown">
                    <button class="dropdown-toggle" style="background: none; border: none; color: white; font-size: 16px; cursor: pointer;">
                        Welcome, {{ user.username }} <i class="fas fa-caret-down"></i>
                    </button>
                    <div class="dropdown-menu" style="display: none; position: absolute; right: 0; background-color: #333; border: 1px solid #444; border-radius: 4px; padding: 10px; width: 184px;">
                        
                        <form action="{% url 'manage' %}" method="post" style="margin: 0;">
                            {% csrf_token %}
                            <button type="submit" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Manage Account</button>
                        </form>
                        
                        <form action="{% url 'logoutz' %}" method="post" style="margin: 0;">
                            {% csrf_token %}
                            <button type="submit" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Log Out</button>
                        </form>
                        <button id="themeToggle" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Toggle Dark Mode</button>

                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div class="welcome-box">
            <div style="text-align: center; margin-bottom: 10px;">
                <div style="display: flex; justify-content: center; gap: 12px; flex-wrap: wrap;">
                  <button id="delete-toggle" style="padding: 6px 12px; background-color: #800080; color: white; border: none; border-radius: 4px; cursor: pointer;">
                    ✖️ Toggle Delete Mode
                  </button>
                  <button id="deleteAllBtn" style="padding: 8px 16px; background-color: #800080; color: white; border: none; border-radius: 6px; cursor: pointer;">
                    🗑️ Delete All Strokes
                  </button>
                  <button id="export-png" style="padding: 8px 12px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">
                    Export as PNG
                  </button>
                </div>
              </div>
            <h2 style="text-align: center;">{{ whiteboard.title }}</h2>   
            <canvas id="whiteboard" width="800" height="600"></canvas>
            <input type="file" id="imageUpload" accept="image/*" />

            <script>
                let imagesOnCanvas = []; // Stores added image objects
                let draggingImage = null;
                let dragOffsetX = 0;
                let dragOffsetY = 0;

                document.getElementById('imageUpload').addEventListener('change', function (e) {
                const file = e.target.files[0];
                if (!file) return;

                const img = new Image();
                img.onload = () => {
                    const imageObj = {
                    img,
                    x: 100,
                    y: 100,
                    width: img.width * 0.3,
                    height: img.height * 0.3,
                    };
                    imagesOnCanvas.push(imageObj);
                    redrawCanvas();
                };
                img.src = URL.createObjectURL(file);
                });
                    document.getElementById('export-png').addEventListener('click', function() {
                    const canvas = document.getElementById('whiteboard');
                    if (!canvas) {
                        alert('Canvas not found!');
                        return;
                    }
                
                    // Create a temporary canvas to add white background
                    const tempCanvas = document.createElement('canvas');
                    tempCanvas.width = canvas.width;
                    tempCanvas.height = canvas.height;
                    const tempCtx = tempCanvas.getContext('2d');
                
                    // Fill white background
                    tempCtx.fillStyle = '#ffffff';
                    tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
                
                    // Draw your existing canvas content on top
                    tempCtx.drawImage(canvas, 0, 0);
                
                    // Export the temp canvas as PNG
                    const image = tempCanvas.toDataURL('image/png');
                
                    // Create a link and trigger download
                    const link = document.createElement('a');
                    link.href = image;
                    link.download = 'whiteboard.png';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                });

                document.getElementById('deleteAllBtn').addEventListener('click', function () {
                    if (!confirm('Are you sure you want to delete all strokes?')) return;

                    fetch(`/whiteboard/{{ whiteboard.id }}/delete-all-strokes/`, {
                        method: 'POST',
                        headers: {
                            'X-CSRFToken': getCookie('csrftoken'),
                        },
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                            console.log('All strokes deleted!');
                        } else {
                            console.error('Error deleting all strokes:', data.error);
                        }
                    })
                    .catch(err => console.error('Fetch error:', err));
                });


                function getCookie(name) {
                    let cookieValue = null;
                    if (document.cookie && document.cookie !== '') {
                        const cookies = document.cookie.split(';');
                        for (let cookie of cookies) {
                            cookie = cookie.trim();
                            if (cookie.startsWith(name + '=')) {
                                cookieValue = decodeURIComponent(cookie.slice(name.length + 1));
                                break;
                            }
                        }
                    }
                    return cookieValue;
                }
            
                // Parse saved strokes from Django context
                const savedStrokes = JSON.parse('{{ strokes_json|escapejs }}');
            
                const canvas = document.getElementById('whiteboard');
                const ctx = canvas.getContext('2d');
            
                // Function to draw a stroke (array of points)
                function drawStroke(points) {
                    if (points.length < 2) return;  // Need at least 2 points to draw a line
            
                    ctx.lineWidth = 2;
                    ctx.strokeStyle = '#4B0082';  // purple-ish
                    ctx.lineCap = 'round';
            
                    ctx.beginPath();
                    ctx.moveTo(points[0].x, points[0].y);
                    for (let i = 1; i < points.length; i++) {
                        ctx.lineTo(points[i].x, points[i].y);
                    }
                    ctx.stroke();
                }
            
                // Draw all saved strokes when the page loads
                savedStrokes.forEach(drawStroke);
            
                let drawing = false;
                let currentStroke = [];
            
                let deleteMode = false;
                const deleteButton = document.getElementById('delete-toggle');
                deleteButton.addEventListener('click', () => {
                    deleteMode = !deleteMode;
                    deleteButton.textContent = deleteMode ? '✅ Delete Mode ON' : '✖️ Toggle Delete Mode';
                });
                canvas.addEventListener('mousedown', (e) => {
                    const x = e.offsetX;
                    const y = e.offsetY;
                    
                    if (draggingImage) {
                        draggingImage.x = x - dragOffsetX;
                        draggingImage.y = y - dragOffsetY;
                        redrawCanvas(); // re-renders images and strokes
                        return;
                    }
                    if (deleteMode) {
                        for (let i = 0; i < savedStrokes.length; i++) {
                        const stroke = savedStrokes[i];
                        for (const point of stroke.points || stroke) {
                            const dx = point.x - x;
                            const dy = point.y - y;
                            const dist = Math.sqrt(dx * dx + dy * dy);
                            if (dist < 10) {
                            deleteStrokeFromServer(i);
                            return;
                            }
                        }
                        }
                        return;
                    }

                    for (let i = imagesOnCanvas.length - 1; i >= 0; i--) {
                        const img = imagesOnCanvas[i];
                        if (
                        x >= img.x &&
                        x <= img.x + img.width &&
                        y >= img.y &&
                        y <= img.y + img.height
                        ) {
                        draggingImage = img;
                        dragOffsetX = x - img.x;
                        dragOffsetY = y - img.y;
                        return; // Don’t start drawing if dragging an image
                        }
                    }

                    drawing = true;
                    currentStroke = [{ x, y }];
                    });
            function deleteStrokeFromServer(index) {
                fetch(`/whiteboard/{{ whiteboard.id }}/delete-stroke/`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCookie('csrftoken'),
                    },
                    body: JSON.stringify({ index }),
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        savedStrokes.splice(index, 1);
                        redrawCanvas();
                    } else {
                        console.error('Delete stroke error:', data.error);
                    }
                })
                .catch(err => console.error('Fetch error:', err));
            }

            function redrawCanvas() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            // Draw images
            for (const imgObj of imagesOnCanvas) {
                ctx.drawImage(imgObj.img, imgObj.x, imgObj.y, imgObj.width, imgObj.height);
            }

            // Draw strokes
            savedStrokes.forEach(drawStroke);
            }
            canvas.addEventListener('mousemove', (e) => {
                const x = e.offsetX;
                const y = e.offsetY;

                if (draggingImage) {
                    draggingImage.x = x - dragOffsetX;
                    draggingImage.y = y - dragOffsetY;
                    redrawCanvas();
                    return;
                }

                if (!drawing) return;

                const point = { x, y };
                currentStroke.push(point);

                ctx.lineWidth = 2;
                ctx.strokeStyle = '#4B0082';  // purple-ish
                ctx.lineCap = 'round';

                ctx.beginPath();
                const prevPoint = currentStroke[currentStroke.length - 2];
                ctx.moveTo(prevPoint.x, prevPoint.y);
                ctx.lineTo(point.x, point.y);
                ctx.stroke();
                });
            
                canvas.addEventListener('mouseup', () => {
                if (draggingImage) {
                    draggingImage = null;
                    return;
                }

                if (!drawing) return;
                drawing = false;
                saveStrokeToServer(currentStroke);
                });

                canvas.addEventListener('mouseleave', () => {
                if (draggingImage) {
                    draggingImage = null;
                    return;
                }

                if (drawing) {
                    drawing = false;
                    saveStrokeToServer(currentStroke);
                }
                });

            
                function saveStrokeToServer(stroke) {
                    fetch(`/whiteboard/{{ whiteboard.id }}/save-stroke/`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': getCookie('csrftoken'),
                        },
                        body: JSON.stringify({ stroke }),
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.error) {
                            console.error('Save stroke error:', data.error);
                        } else {
                            console.log('Stroke saved!');
                            savedStrokes.push(stroke);
                        }
                    })
                    .catch(err => console.error('Fetch error:', err));
                }
            </script>

        </div>
    </div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const toggle = document.querySelector('.dropdown-toggle');
        const menu = document.querySelector('.dropdown-menu');
        toggle.addEventListener('click', function () {
            menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
        });
    });

    const toggle = document.getElementById("themeToggle");
        const root = document.documentElement;

        if (localStorage.getItem("theme") === "dark") {
        root.classList.add("dark");
        }

        toggle.addEventListener("click", () => {
        root.classList.toggle("dark");
        if (root.classList.contains("dark")) {
            localStorage.setItem("theme", "dark");
        } else {
            localStorage.setItem("theme", "light");
        }
        });
</script>
</body>
</html>