document.addEventListener('DOMContentLoaded', () => {
    const cards = document.querySelectorAll('.dashboard > .card');
    const dashboard = document.querySelector('.dashboard');
    if (dashboard) {
        dashboard.addEventListener('mouseenter', () => {
            cards.forEach(card => card.style.opacity = '1');
        });
    }

    cards.forEach(card => {
        card.addEventListener('mouseenter', () => {
            cards.forEach(c => c.style.opacity = '0.9');
            card.style.opacity = '1';
        });
        card.addEventListener('mouseleave', () => {
            cards.forEach(c => c.style.opacity = '1');
        });
    });

    cards.forEach(card => {
        card.addEventListener('dblclick', handleCardClick);
    });
});

function handleCardClick(event) {
    const target = event.target.closest('.card');
    if (target) {
        const modal = document.getElementById('modal');
        const modalContent = document.getElementById('modalContent');
        while (modalContent.firstChild) {
            modalContent.removeChild(modalContent.firstChild);
        }
        const clone = target.cloneNode(true);
        clone.classList.remove('card');
        clone.style.minHeight = '80vh';
        clone.style.minWidth = '80vw';
        clone.style.overflowY = 'auto';
        clone.style.overflowX = 'auto';
        const originalCanvases = target.querySelectorAll('canvas');
        const clonedCanvases = clone.querySelectorAll('canvas');
        originalCanvases.forEach((canvas, index) => {
            const newCanvas = document.createElement('canvas');
            const newId = canvas.id + '_modal';
            newCanvas.id = newId;
            clonedCanvases[index].replaceWith(newCanvas);
        });
        modalContent.appendChild(clone);
        modal.classList.add('show');
        originalCanvases.forEach((canvas) => {
            initChart(canvas.id + '_modal');
        });
        history.pushState({ modalOpen: true }, "", "#modal");
    }
}

function closeModal() {
    const modal = document.getElementById('modal');
    modal.classList.remove('show');
    if (history.state && history.state.modalOpen) {
        history.back();
    }
}

window.addEventListener('popstate', () => {
    const modal = document.getElementById('modal');
    if (modal && modal.classList.contains('show')) {
        modal.classList.remove('show');
    }
});

var modal = document.getElementById('modal');
if (modal) {
    modal.addEventListener('click', () => {
        closeModal();
    });
}

var modalContent = document.getElementById('modalContent');
if (modalContent) {
    modalContent.addEventListener('click', (event) => {
        event.stopPropagation();
    });
}