<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Google Trends API</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script>
    let trendChart = null; // Biến để lưu biểu đồ

    async function getTrends() {
      const keywords = document.getElementById("keywords").value.trim().split("\n");

      try {
        const response = await fetch('http://localhost:3000/api/get-trends', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ keywords }),
        });

        if (response.ok) {
          const result = await response.json();
          displayChart(result);
        } else {
          alert('Lỗi khi lấy dữ liệu từ server');
        }
      } catch (error) {
        console.error('Lỗi kết nối:', error);
      }
    }

    function displayChart(data) {
      const ctx = document.getElementById('trendChart').getContext('2d');

      // Nếu biểu đồ đã tồn tại, hủy bỏ biểu đồ cũ trước khi vẽ lại
      if (trendChart) {
        trendChart.destroy();
      }

      // Xử lý dữ liệu cho biểu đồ
      const datasets = [];
      const labels = [];  // Mảng lưu nhãn thời gian chung cho tất cả từ khóa

      Object.keys(data).forEach((keyword, index) => {
        const values = data[keyword].map(item => item.value);  // Giá trị xu hướng
        const times = data[keyword].map(item => item.time);   // Nhãn thời gian

        // Lưu nhãn thời gian từ từ khóa đầu tiên
        if (index === 0) {
          times.forEach(time => labels.push(time));
        }

        datasets.push({
          label: keyword,
          data: values,
          borderColor: `hsl(${index * 60}, 70%, 50%)`, // Mỗi keyword một màu
          fill: false,
        });
      });

      // Vẽ biểu đồ mới
      trendChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,   // Nhãn thời gian
          datasets: datasets,  // Dữ liệu xu hướng
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'top',
            },
          },
          scales: {
            x: {
              title: {
                display: true,
                text: 'Thời gian',
              },
            },
            y: {
              title: {
                display: true,
                text: 'Xu hướng',
              },
              beginAtZero: true,
            },
          },
        },
      });
    }
  </script>
</head>
<body>
  <h1>Google Trends</h1>
  <textarea id="keywords" rows="5" cols="50" placeholder="Nhập danh sách từ khóa, mỗi từ khóa một dòng..."></textarea>
  <br>
  <button onclick="getTrends()">Get Trends</button>
  <h2>Kết quả:</h2>
  <canvas id="trendChart" width="800" height="400"></canvas>
</body>
</html>
