import { useTranslation } from 'react-i18next'
import { useStore } from '../store'

export default function SolveHeatmap() {
  const { t } = useTranslation()
  const puzzle = useStore((s) => s.puzzle)
  const cellStatus = useStore((s) => s.cellStatus)
  const cellEverWrong = useStore((s) => s.cellEverWrong)

  if (!puzzle) return null

  const size = Math.min(200, window.innerWidth - 40)
  const cellW = size / puzzle.width
  const cellH = size / puzzle.height

  function cellColor(r: number, c: number): string {
    if (puzzle!.cells[r][c] === 'black') return 'var(--cell-black, #1a1a2e)'
    if (cellStatus[r]?.[c] === 'revealed') return 'var(--heatmap-hint, #f59e0b)'
    if (cellEverWrong[r]?.[c]) return 'var(--heatmap-wrong, #ef4444)'
    return 'var(--heatmap-clean, #22c55e)'
  }

  return (
    <div className="solve-heatmap">
      <h4 className="solve-heatmap-title">{t('heatmap.title')}</h4>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="solve-heatmap-grid">
        {Array.from({ length: puzzle.height }, (_, r) =>
          Array.from({ length: puzzle.width }, (_, c) => (
            <rect key={`${r}-${c}`}
              x={c * cellW} y={r * cellH}
              width={cellW - 1} height={cellH - 1}
              rx={1}
              fill={cellColor(r, c)}
            />
          ))
        )}
      </svg>
      <div className="solve-heatmap-legend">
        <span><span className="heatmap-dot" style={{ background: 'var(--heatmap-clean, #22c55e)' }} /> {t('heatmap.clean')}</span>
        <span><span className="heatmap-dot" style={{ background: 'var(--heatmap-hint, #f59e0b)' }} /> {t('heatmap.hinted')}</span>
        <span><span className="heatmap-dot" style={{ background: 'var(--heatmap-wrong, #ef4444)' }} /> {t('heatmap.wrong')}</span>
      </div>
    </div>
  )
}
