document.addEventListener('DOMContentLoaded', () => {
    const dropZones = [document.getElementById('dropZone'), document.getElementById('dropZone2')];
    let targetAmount = Math.floor(Math.random() * (100 - 51 + 1)) + 51;
    let euroCounter1 = 0;
    let euroCounter2 = 0;
    updateTargetDisplay();

    // Initialize draggable items
    document.querySelectorAll('#banknotes img').forEach(img => {
        // Mouse events
        img.addEventListener('dragstart', handleDragStart);
        img.addEventListener('dragend', handleDragEnd);

        // Touch events
        img.addEventListener('touchstart', handleTouchStart, {passive: false});
        img.addEventListener('touchend', handleDragEnd);
    });

    // Initialize drop zones for mouse events
    dropZones.forEach(zone => {
        zone.addEventListener('dragover', handleDragOver);
        zone.addEventListener('dragleave', handleDragLeave);
        zone.addEventListener('drop', handleDrop);

        zone.addEventListener('touchover', handleDragOver);
    });

    // Update target display
    function updateTargetDisplay() {
        const targetAmountDisplay = document.getElementById('targetAmountDisplay');
        targetAmountDisplay.textContent = `Στόχος: ${targetAmount}€ σε κάθε πορτοφόλι`;
    }

    // Reset functionality
    document.getElementById('resetButton').addEventListener('click', () => {
        euroCounter1 = 0;
        euroCounter2 = 0;
        dropZones.forEach(zone => zone.innerHTML = '');
        targetAmount = Math.floor(Math.random() * (100 - 51 + 1)) + 51;
        updateTargetDisplay();
        document.getElementById('message').textContent = '';
    });

    // Check functionality
    document.getElementById('checkButton').addEventListener('click', checkResult);

    function handleDragStart(e) {
        e.dataTransfer.setData('text/plain', e.target.dataset.value);
        e.dataTransfer.setData('image/src', e.target.src);

        $('.dropZone').css('outline', '5px dashed red');
    }
    function checkResult() {
        // Retrieve the total amount and distinct values in each drop zone
        let total1 = getTotalAndDistinct(document.getElementById('dropZone'));
        let total2 = getTotalAndDistinct(document.getElementById('dropZone2'));

        let message = document.getElementById('message');
        // Compare each drop zone's total against the target amount
        // and ensure there's at least one distinct euro note between zones
        if (total1.sum === targetAmount && total2.sum === targetAmount && 
            (total1.distinct.size !== total2.distinct.size || [...total1.distinct].some(value => !total2.distinct.has(value)) || [...total2.distinct].some(value => !total1.distinct.has(value)))) {
            message.textContent = 'Μπράβο! Τα κατάφερες! 😊'; // Success message
        } else {
            message.textContent = 'Προσπάθησε πάλι!'; // Failure message
        }
    }

    function getTotalAndDistinct(dropZone) {
        let sum = 0;
        let distinctValues = new Set();
        dropZone.querySelectorAll('img').forEach(img => {
            let value = parseInt(img.dataset.value, 10);
            sum += value;
            distinctValues.add(value);
        });
        return { sum: sum, distinct: distinctValues };
    }


    function handleTouchStart(e) {
        e.preventDefault(); // Prevent scrolling on touch start

        $('.dropZone').css('outline', '5px dashed red');

        const touchLocation = e.targetTouches[0];
        const img = e.target;

        // Mimic the dataTransfer object
        const mockDataTransfer = {
            data: {},
            setData: function(type, value) {
                this.data[type] = value;
            },
            getData: function(type) {
                return this.data[type];
            }
        };

        mockDataTransfer.setData('text/plain', img.dataset.value);
        mockDataTransfer.setData('image/src', img.src);

        // Attach the mock dataTransfer object to the touch point
        touchLocation.dataTransfer = mockDataTransfer;

        // Create a clone of the image for visual feedback during drag
        const clone = img.cloneNode(true);
        clone.style.position = 'absolute';
        clone.style.left = touchLocation.pageX + 'px';
        clone.style.top = touchLocation.pageY + 'px';
        clone.style.width = '80px';
        document.body.appendChild(clone);

        // Move clone with touch
        const moveAt = (pageX, pageY) => {
            clone.style.left = pageX - img.width / 2 + 'px';
            clone.style.top = pageY - img.height / 2 + 'px';
        };

        moveAt(touchLocation.pageX, touchLocation.pageY);

        const onTouchMove = (e) => {
            e.preventDefault(); // Prevent scrolling on touch move
            const touchLocation = e.targetTouches[0];
            moveAt(touchLocation.pageX, touchLocation.pageY);
        };

        const onTouchEnd = (e) => {
            document.removeEventListener('touchmove', onTouchMove);
            document.removeEventListener('touchend', onTouchEnd);
            clone.remove();

            // Determine drop zone
            dropZones.forEach(zone => {
                const rect = zone.getBoundingClientRect();
                if (e.changedTouches[0].pageX > rect.left && e.changedTouches[0].pageX < rect.right &&
                    e.changedTouches[0].pageY > rect.top && e.changedTouches[0].pageY < rect.bottom) {
                    handleDrop({
                        preventDefault: () => {},
                        target: zone,
                        dataTransfer: touchLocation.dataTransfer
                    });
                }
            });
        };

        document.addEventListener('touchmove', onTouchMove, {passive: false});
        document.addEventListener('touchend', onTouchEnd);
    }

    function handleDragOver(e) {
        e.preventDefault(); // Necessary to allow dropping

        $(this).css('outline', '5px dashed green');
    }

    function handleDragLeave(e) {
        e.preventDefault(); // Necessary to allow dropping

        $('.dropZone').css('outline', '5px dashed red');
    }

    function handleDrop(e) {
        e.preventDefault();

        if(e.target.id == '' || e.target.id == 'undefined' ){
            zoneId = $(e.target).parents('.dropZone').attr('id');
            dropzoneTarget = $(e.target).parents('.dropZone')[0];
        } else {
            zoneId = e.target.id;
            dropzoneTarget = e.target;
        }

        const value = parseInt(e.dataTransfer.getData('text/plain'), 10);
        const imgSrc = e.dataTransfer.getData('image/src');

        if (zoneId === 'dropZone' || zoneId === 'dropZone2') {
            const euroCounter = zoneId === 'dropZone' ? euroCounter1 += value : euroCounter2 += value;
            const wrapper = createWrapper(value, imgSrc, euroCounter, zoneId === 'dropZone' ? 1 : 2);
            dropzoneTarget.appendChild(wrapper);
        }
    }

    function handleDragEnd(e) {
        e.preventDefault();

        $('.dropZone').css('outline', 'none');

    }

    function createWrapper(value, imgSrc, euroCounter, zone) {
        const wrapper = document.createElement('div');
        wrapper.classList.add('img-wrapper');
        wrapper.style.position = 'relative';
        wrapper.style.display = 'inline-block';

        const imgElement = document.createElement('img');
        imgElement.src = imgSrc;
        imgElement.alt = `€${value}`;
        imgElement.style.height = '50px';
        imgElement.setAttribute('data-value', value);
        imgElement.setAttribute('draggable', 'false');

        if (value === 1 || value === 2) {
            imgElement.style.borderRadius = '50%';
        }

        const deleteBtn = document.createElement('div');
        deleteBtn.textContent = 'x';
        deleteBtn.style.position = 'absolute';
        deleteBtn.style.top = '-3px';
        deleteBtn.style.right = '-3px';
        deleteBtn.style.cursor = 'pointer';
        deleteBtn.style.color = 'white';
        deleteBtn.style.fontFamily = 'arial';
        deleteBtn.style.backgroundColor = '#363636';
        deleteBtn.style.padding = '1px 5px';
        deleteBtn.style.borderRadius = '4px';
        deleteBtn.style.opacity = '0.8';

        deleteBtn.addEventListener('click', function () {
            if (zone === 1) {
                euroCounter1 -= value;
            } else if (zone === 2) {
                euroCounter2 -= value;
            }
            wrapper.remove();
        });

        wrapper.appendChild(imgElement);
        wrapper.appendChild(deleteBtn);

        return wrapper;
    }

});

// $(".card").on("click keyup", function (e) {
//   if(e.keyCode == 13 || e.keyCode == 32) {
//     screenReader.textContent = "Επιλέξατε την κάρτα με τον αριθμό "+ $(this).text() +". Πατήστε Έλεγχος για αξιολόγηση της απάντησης.";
//   }
// });