document.addEventListener('DOMContentLoaded', function () {
    let markers = [];
    const markerList = document.getElementById('markerList');
    const markersDataInput = document.getElementById('vehicle_diagram');
    const mapImage = document.getElementById('mapImage');
    const svgOverlay = document.getElementById('svgOverlay');

    // Remove the cursor style so it doesn't change to the hand when clicking the image
    mapImage.style.cursor = 'default';

    // Wait for the image to load before allowing marker placement
    mapImage.addEventListener('load', function () {
        // Function to get accurate image size
        function getImageSize() {
            const rect = mapImage.getBoundingClientRect();
            return { width: rect.width, height: rect.height, left: rect.left, top: rect.top };
        }

        // Function to add a marker
        function addMarker(event) {
            const imageSize = getImageSize();
            let clientX, clientY;

            // Handle both touch and mouse events
            if (event.touches) {
                clientX = event.touches[0].clientX;
                clientY = event.touches[0].clientY;
            } else {
                clientX = event.clientX;
                clientY = event.clientY;
            }

            // Calculate position based on actual image dimensions
            const x = ((clientX - imageSize.left) / imageSize.width) * 100;
            const y = ((clientY - imageSize.top) / imageSize.height) * 100;

            // Add marker to the SVG overlay
            const markerId = 'marker-' + Date.now();
            const marker = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
            marker.setAttribute('cx', `${x}%`);
            marker.setAttribute('cy', `${y}%`);
            marker.setAttribute('r', 5);
            marker.setAttribute('fill', 'red');
            marker.setAttribute('class', 'marker-point');
            marker.setAttribute('data-id', markerId);
            svgOverlay.appendChild(marker);

            // Add marker data to the list and hidden input
            const markerData = { id: markerId, x: x, y: y, note: '' };
            markers.push(markerData);
            updateMarkerList();
            updateMarkersData();
        }

        // Update the marker list with selectable options instead of a text input
        function updateMarkerList() {
            markerList.innerHTML = '';
            markers.forEach(function (marker) {
                const li = document.createElement('li');
                li.classList.add('list-group-item');
                li.innerHTML = `
                    <div>
                        <strong>Marker at (${marker.x.toFixed(2)}%, ${marker.y.toFixed(2)}%)</strong>
                        <button type="button" class="btn btn-danger btn-sm float-end delete-marker" data-id="${marker.id}">Delete</button>
                    </div>
                    <select class="form-control mt-2" data-id="${marker.id}">
                        <option value="" disabled ${!marker.note ? 'selected' : ''}>Select Damage</option>
                        <option value="S" ${marker.note === 'S - Scratch' ? 'selected' : ''}>Scratch</option>
                        <option value="D" ${marker.note === 'D - Dent' ? 'selected' : ''}>Dent</option>
                        <option value="P" ${marker.note === 'P - Paint Defect' ? 'selected' : ''}>Paint Defect</option>
                        <option value="C" ${marker.note === 'C - Crack' ? 'selected' : ''}>Crack</option>
                        <option value="R" ${marker.note === 'R - Rust' ? 'selected' : ''}>Rust</option>
                        <option value="B" ${marker.note === 'B - Bubble' ? 'selected' : ''}>Bubble</option>
                    </select>
                `;
                markerList.appendChild(li);
            });

            // Bind the delete button functionality
            const deleteButtons = document.querySelectorAll('.delete-marker');
            deleteButtons.forEach(button => {
                button.addEventListener('click', function () {
                    const markerId = button.getAttribute('data-id');
                    deleteMarker(markerId);
                });
            });

            // Bind the select change functionality
            const noteSelects = document.querySelectorAll('select');
            noteSelects.forEach(select => {
                select.addEventListener('change', function () {
                    const markerId = select.getAttribute('data-id');
                    const selectedValue = select.value;
                    const formattedNote = `${selectedValue} - ${noteOptions[selectedValue]}`;
                    updateNoteForMarker(markerId, formattedNote);
                });
            });
        }

        // Function to update the note for a marker
        function updateNoteForMarker(markerId, note) {
            const marker = markers.find(marker => marker.id === markerId);
            if (marker) {
                marker.note = note;
                updateMarkersData();
            }
        }

        // Function to update the hidden input with marker data
        function updateMarkersData() {
            markersDataInput.value = JSON.stringify(markers);
        }

        // Function to delete a marker
        function deleteMarker(markerId) {
            // Remove from the SVG
            const markerElement = svgOverlay.querySelector(`[data-id="${markerId}"]`);
            if (markerElement) {
                markerElement.remove();
            }

            // Remove from the markers array
            markers = markers.filter(marker => marker.id !== markerId);
            updateMarkerList();
            updateMarkersData();
        }

        // Update markers' positions when the window is resized
        window.addEventListener('resize', function () {
            const imageSize = getImageSize();
            markers.forEach(function (marker) {
                const markerElement = svgOverlay.querySelector(`[data-id="${marker.id}"]`);
                if (markerElement) {
                    markerElement.setAttribute('cx', `${marker.x}%`);
                    markerElement.setAttribute('cy', `${marker.y}%`);
                }
            });
        });

        // Add event listeners for marker placement
        mapImage.addEventListener('click', addMarker);
        mapImage.addEventListener('touchstart', addMarker, { passive: false });
    });
});

/////////
document.addEventListener("DOMContentLoaded", function () {
    // Initialize signature pads for Customer and Owner
    initSignaturePad("customer_signatureCanvas", "customer_signatureData", "clearCustomerBtn", "saveCustomerBtn", "customerSignatureForm");

    function initSignaturePad(canvasId, hiddenInputId, clearBtnId, saveBtnId, formId) {
        const canvas = document.getElementById(canvasId);
        if (!canvas) {
            console.error(`Canvas with ID '${canvasId}' not found.`);
            return;
        }

        const ctx = canvas.getContext("2d");

        // Set canvas dimensions to match its display size
        const rect = canvas.getBoundingClientRect();
        const scale = window.devicePixelRatio || 1; // Handle high-DPI displays
        canvas.width = rect.width * scale;
        canvas.height = rect.height * scale;

        // Scale the context to ensure drawing matches display
        ctx.scale(scale, scale);

        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;

        // Function to get the correct coordinates
        function getCanvasCoordinates(event) {
            const rect = canvas.getBoundingClientRect();
            let clientX, clientY;

            if (event.touches) {
                // For touch events
                clientX = event.touches[0].clientX;
                clientY = event.touches[0].clientY;
            } else {
                // For mouse events
                clientX = event.clientX;
                clientY = event.clientY;
            }

            // Adjust for canvas position
            return {
                x: clientX - rect.left,
                y: clientY - rect.top,
            };
        }

        // Start drawing
        function startDrawing(event) {
            isDrawing = true;
            const { x, y } = getCanvasCoordinates(event);
            lastX = x;
            lastY = y;
        }

        // Draw
        function draw(event) {
            if (!isDrawing) return;
            const { x, y } = getCanvasCoordinates(event);

            ctx.beginPath();
            ctx.moveTo(lastX, lastY);
            ctx.lineTo(x, y);
            ctx.strokeStyle = "black";
            ctx.lineWidth = 2;
            ctx.stroke();

            lastX = x;
            lastY = y;
        }

        // Stop drawing
        function stopDrawing() {
            isDrawing = false;
        }

        // Mouse events
        canvas.addEventListener("mousedown", startDrawing);
        canvas.addEventListener("mousemove", draw);
        canvas.addEventListener("mouseup", stopDrawing);
        canvas.addEventListener("mouseleave", stopDrawing);

        // Touch events
        canvas.addEventListener("touchstart", startDrawing);
        canvas.addEventListener("touchmove", draw);
        canvas.addEventListener("touchend", stopDrawing);

        // Attach Clear Button
        const clearBtn = document.getElementById(clearBtnId);
        if (clearBtn) {
            clearBtn.addEventListener("click", () => {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
            });
        } else {
            console.error(`Clear button with ID '${clearBtnId}' not found.`);
        }

        // Attach Save Button
        const saveBtn = document.getElementById(saveBtnId);
        if (saveBtn) {
            saveBtn.addEventListener("click", () => {
                const dataURL = canvas.toDataURL("image/png");
                const hiddenInput = document.getElementById(hiddenInputId);
                if (hiddenInput) {
                    hiddenInput.value = dataURL;
                } else {
                    console.error(`Hidden input with ID '${hiddenInputId}' not found.`);
                }

                const form = document.getElementById(formId);
                if (form) {
                    form.submit();
                } else {
                    console.error(`Form with ID '${formId}' not found.`);
                }
            });
        } else {
            console.error(`Save button with ID '${saveBtnId}' not found.`);
        }
    }
});