export default function LineChart({ data, width = 500, height = 180 }) {
  if (!data || data.length < 2) {
    return (
      <div style={{ height, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#94a3b8', fontSize: '0.85rem' }}>
        Need at least 2 attempts to show a graph
      </div>
    )
  }

  const pad = { top: 16, right: 16, bottom: 32, left: 40 }
  const W = width - pad.left - pad.right
  const H = height - pad.top - pad.bottom

  const minY = 0, maxY = 100
  const xStep = W / (data.length - 1)

  const toX = (i) => pad.left + i * xStep
  const toY = (v) => pad.top + H - ((v - minY) / (maxY - minY)) * H

  // Line path
  const points = data.map((d, i) => `${toX(i)},${toY(d.percentage)}`)
  const linePath = `M ${points.join(' L ')}`

  // Fill path
  const fillPath = `M ${toX(0)},${toY(0)} L ${points.join(' L ')} L ${toX(data.length - 1)},${toY(0)} Z`

  // Y gridlines
  const gridLines = [0, 25, 50, 75, 100]

  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} style={{ overflow: 'visible' }}>
      {/* Grid lines */}
      {gridLines.map(v => (
        <g key={v}>
          <line
            x1={pad.left} y1={toY(v)} x2={pad.left + W} y2={toY(v)}
            stroke={v === 75 ? '#fde68a' : '#f1f5f9'} strokeWidth={v === 75 ? 1.5 : 1}
            strokeDasharray={v === 75 ? '4 3' : 'none'}
          />
          <text x={pad.left - 6} y={toY(v)} textAnchor="end" dominantBaseline="middle"
            fontSize="10" fill="#94a3b8">{v}%</text>
        </g>
      ))}

      {/* 75% label */}
      <text x={pad.left + W + 4} y={toY(75)} dominantBaseline="middle" fontSize="9" fill="#d97706">75%</text>

      {/* Fill */}
      <path d={fillPath} fill="#e0e7ff" opacity="0.4" />

      {/* Line */}
      <path d={linePath} fill="none" stroke="#2563eb" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />

      {/* Dots + tooltips */}
      {data.map((d, i) => {
        const x = toX(i), y = toY(d.percentage)
        const color = d.percentage >= 75 ? '#22c55e' : '#ef4444'
        const label = new Date(d.date).toLocaleDateString('en', { month: 'short', day: 'numeric' })
        return (
          <g key={i}>
            <circle cx={x} cy={y} r="4" fill={color} stroke="white" strokeWidth="2" />
            {/* X axis label */}
            <text x={x} y={pad.top + H + 16} textAnchor="middle" fontSize="9" fill="#94a3b8">{label}</text>
            {/* Hover tooltip via title */}
            <title>{label}: {d.percentage}% ({d.score}/{d.total})</title>
          </g>
        )
      })}
    </svg>
  )
}
