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
    if (mapImage) {
        mapImage.style.cursor = 'default';

        mapImage.addEventListener('load', function () {
            function getImageSize() {
                const rect = mapImage.getBoundingClientRect();
                return { width: rect.width, height: rect.height, left: rect.left, top: rect.top };
            }

            function addMarker(event) {
                event.preventDefault(); // Prevent default behavior

                const imageSize = getImageSize();
                let clientX, clientY;

                if (event.touches) {
                    clientX = event.touches[0].clientX;
                    clientY = event.touches[0].clientY;
                } else {
                    clientX = event.clientX;
                    clientY = event.clientY;
                }

                const x = ((clientX - imageSize.left) / imageSize.width) * 100;
                const y = ((clientY - imageSize.top) / imageSize.height) * 100;

                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);

                markers.push({ id: markerId, x: x, y: y, note: '' });
                updateMarkerList();
                updateMarkersData();
            }

            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);
                });

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

                document.querySelectorAll('select').forEach(select => {
                    select.addEventListener('change', function () {
                        const markerId = select.getAttribute('data-id');
                        updateNoteForMarker(markerId, select.value);
                    });
                });
            }

            function updateNoteForMarker(markerId, note) {
                const marker = markers.find(marker => marker.id === markerId);
                if (marker) {
                    marker.note = note;
                    updateMarkersData();
                }
            }

            function updateMarkersData() {
                markersDataInput.value = JSON.stringify(markers);
            }

            function deleteMarker(markerId) {
                const markerElement = svgOverlay.querySelector(`[data-id="${markerId}"]`);
                if (markerElement) {
                    markerElement.remove();
                }
                markers = markers.filter(marker => marker.id !== markerId);
                updateMarkerList();
                updateMarkersData();
            }

            window.addEventListener('resize', function () {
                markers.forEach(function (marker) {
                    const markerElement = svgOverlay.querySelector(`[data-id="${marker.id}"]`);
                    if (markerElement) {
                        markerElement.setAttribute('cx', `${marker.x}%`);
                        markerElement.setAttribute('cy', `${marker.y}%`);
                    }
                });
            });

            mapImage.addEventListener('click', addMarker, { passive: true });
            mapImage.addEventListener('touchstart', addMarker, { passive: true });
        });
    }

    function initSignaturePad(canvasId, hiddenInputId, clearBtnId, saveBtnId, formId) {
        const canvas = document.getElementById(canvasId);
        if (!canvas) return;

        // Initialize signature pad functionality
        let ctx = canvas.getContext("2d");
        let isDrawing = false;
        let lastX = 0;
        let lastY = 0;

        // Resize canvas based on device
        const rect = canvas.getBoundingClientRect();
        const scale = window.devicePixelRatio || 1;
        canvas.width = rect.width * scale;
        canvas.height = rect.height * scale;
        ctx.scale(scale, scale);

        function getCanvasCoordinates(event) {
            const rect = canvas.getBoundingClientRect();
            return {
                x: (event.touches ? event.touches[0].clientX : event.clientX) - rect.left,
                y: (event.touches ? event.touches[0].clientY : event.clientY) - rect.top,
            };
        }

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

        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;
        }

        function stopDrawing() {
            isDrawing = false;
        }

        // Add event listeners for touch and mouse interactions
        canvas.addEventListener("mousedown", startDrawing);
        canvas.addEventListener("mousemove", draw);
        canvas.addEventListener("mouseup", stopDrawing);
        canvas.addEventListener("mouseleave", stopDrawing);
        canvas.addEventListener("touchstart", startDrawing);
        canvas.addEventListener("touchmove", draw);
        canvas.addEventListener("touchend", stopDrawing);

        // Get the buttons
        const clearCustomerBtn = document.getElementById(clearBtnId);
        const saveCustomerBtn = document.getElementById(saveBtnId);
        const customerSignatureData = document.getElementById(hiddenInputId);

        // Clear signature canvas
        clearCustomerBtn?.addEventListener("click", () => ctx.clearRect(0, 0, canvas.width, canvas.height));

        // Save signature and lock canvas position on mobile
        saveCustomerBtn?.addEventListener("click", () => {
            customerSignatureData.value = canvas.toDataURL("image/png");

            // Lock canvas position on mobile by adding a fixed position class
            if (window.innerWidth <= 768) {
                document.body.classList.add('no-scroll');  // Disable scroll
                canvas.classList.add('fixed-canvas');  // Make canvas fixed on the screen
            }
        });
    }

    // Initialize signature pad with appropriate IDs
    initSignaturePad("customer_signatureCanvas", "customer_signatureData", "clearCustomerBtn", "saveCustomerBtn", "customerSignatureForm");
});
