const canvas = document.getElementById('graphCanvas');
const ctx = canvas.getContext('2d');
const tooltip = document.querySelector('.tooltip');

// Set canvas size with proper scaling
function resizeCanvas() {
    const rect = canvas.parentElement.getBoundingClientRect();
    canvas.width = rect.width * window.devicePixelRatio;
    canvas.height = rect.height * window.devicePixelRatio;
    canvas.style.width = ${rect.width}px;
    canvas.style.height = ${rect.height}px;
    ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}

resizeCanvas();
window.addEventListener('resize', resizeCanvas);

// Sample data
const data = {
    avatrade: Array.from({length: 100}, () => Math.random() * 600 + 400),
    industry: Array.from({length: 100}, () => Math.random() * 200 + 400)
};

function drawGraph() {
    const width = canvas.width / window.devicePixelRatio;
    const height = canvas.height / window.devicePixelRatio;
    
    ctx.clearRect(0, 0, width, height);

    // Draw grid lines
    ctx.strokeStyle = '#e0e0e0';
    ctx.beginPath();
    for(let i = 0; i < 6; i++) {
        const y = height * (i / 5);
        ctx.moveTo(0, y);
        ctx.lineTo(width, y);
    }
    ctx.stroke();

    // Draw lines
    const drawLine = (data, color) => {
        ctx.strokeStyle = color;
        ctx.lineWidth = 2;
        ctx.beginPath();
        data.forEach((value, index) => {
            const x = (width * index) / (data.length - 1);
            const y = height - (value / 1400 * height);
            if(index === 0) ctx.moveTo(x, y);
            else ctx.lineTo(x, y);
        });
        ctx.stroke();
    };

    drawLine(data.avatrade, '#1a73e8');
    drawLine(data.industry, '#fa7b17');
}

// Handle hover
canvas.addEventListener('mousemove', (e) => {
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const index = Math.floor((x / rect.width) * data.avatrade.length);
    
    if(index >= 0 && index < data.avatrade.length) {
        tooltip.style.display = 'block';
        tooltip.style.left = ${x + 10}px;
        tooltip.style.top = ${e.clientY - rect.top - 30}px;
        tooltip.textContent = `AvaTrade: ${Math.round(data.avatrade[index])}ms
Industry: ${Math.round(data.industry[index])}ms`;
    }
});

canvas.addEventListener('mouseleave', () => {
    tooltip.style.display = 'none';
});

drawGraph();