import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend, Filler } from 'chart.js';

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Legend, Filler);

export default function TrafficChart({ history = [], loading }) {
  if (loading) return <div className="skeleton" style={{ height: 160, borderRadius: 8 }} />;
  if (!history.length) return null;

  // Sample to ~30 points for readability
  const step = Math.max(1, Math.floor(history.length / 30));
  const sampled = history.filter((_, i) => i % step === 0);

  const labels = sampled.map(d => {
    const dt = new Date(d.date);
    return dt.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  });

  const data = {
    labels,
    datasets: [
      {
        label: 'Clicks',
        data: sampled.map(d => d.clicks),
        borderColor: '#378ADD',
        backgroundColor: 'rgba(55,138,221,0.08)',
        fill: true,
        tension: 0.4,
        pointRadius: 0,
        borderWidth: 1.5,
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: { legend: { display: false }, tooltip: { mode: 'index', intersect: false } },
    scales: {
      x: { grid: { display: false }, ticks: { font: { size: 10 }, maxTicksLimit: 8, color: '#888' } },
      y: { grid: { color: 'rgba(128,128,128,0.1)' }, ticks: { font: { size: 10 }, color: '#888' } },
    },
  };

  return (
    <div style={{ height: 140 }}>
      <Line data={data} options={options} />
    </div>
  );
}
