'use client'

import { useMemo } from 'react'
import { Risk, RISK_LEVEL_COLORS, calculateRiskLevel } from './risk-heatmap-types'

interface MiniRiskMatrixProps {
  risks: Risk[]
  size?: 'sm' | 'md'
}

export function MiniRiskMatrix({ risks, size = 'sm' }: MiniRiskMatrixProps) {
  const matrix = useMemo(() => {
    const m: Record<number, Record<number, number>> = {}
    for (let l = 1; l <= 5; l++) {
      m[l] = {}
      for (let i = 1; i <= 5; i++) {
        m[l][i] = 0
      }
    }
    risks.forEach((r) => {
      if (m[r.likelihood] && m[r.likelihood][r.impact] !== undefined) {
        m[r.likelihood][r.impact]++
      }
    })
    return m
  }, [risks])

  const cellSize = size === 'sm' ? 'w-6 h-6' : 'w-8 h-8'
  const fontSize = size === 'sm' ? 'text-[8px]' : 'text-[10px]'

  return (
    <div className="inline-block">
      {[5, 4, 3, 2, 1].map((l) => (
        <div key={l} className="flex">
          {[1, 2, 3, 4, 5].map((i) => {
            const level = calculateRiskLevel(l, i)
            const count = matrix[l][i]
            const colors = RISK_LEVEL_COLORS[level]

            return (
              <div
                key={i}
                className={`${cellSize} ${colors.bg} border ${colors.border} flex items-center justify-center m-px rounded-sm`}
              >
                {count > 0 && (
                  <span className={`${fontSize} font-bold ${colors.text}`}>{count}</span>
                )}
              </div>
            )
          })}
        </div>
      ))}
    </div>
  )
}
