import type { MemorySamples } from '../types'

interface MemoryVizProps {
  samples: MemorySamples
}

export function MemoryViz({ samples }: MemoryVizProps) {
  const { traces, total } = samples

  // Create a grid of weight values for the heatmap
  const cellSize = 8
  const cols = 20
  const rows = Math.ceil(traces.length / cols)

  return (
    <div className="glass-card p-3">
      <div className="flex items-center justify-between mb-2">
        <span className="text-[10px] text-pal-muted">
          {total.toLocaleString()} total traces
        </span>
        <div className="flex items-center gap-1.5">
          <span className="text-[9px] text-pal-muted">weight</span>
          <div className="flex h-2 w-16 rounded-full overflow-hidden">
            <div className="flex-1" style={{ background: '#1e1e30' }} />
            <div className="flex-1" style={{ background: '#4c2a8e' }} />
            <div className="flex-1" style={{ background: '#7c3aed' }} />
            <div className="flex-1" style={{ background: '#a78bfa' }} />
          </div>
          <span className="text-[9px] text-pal-muted">1.0</span>
        </div>
      </div>

      <div
        className="grid gap-0.5"
        style={{ gridTemplateColumns: `repeat(${cols}, 1fr)` }}
      >
        {traces.map((trace, i) => {
          const w = trace.weight
          const color =
            w >= 0.75 ? '#a78bfa' :
            w >= 0.5  ? '#7c3aed' :
            w >= 0.25 ? '#4c2a8e' :
                        '#1e1e30'
          return (
            <div
              key={trace.id}
              className="aspect-square rounded-sm transition-all hover:scale-150 hover:z-10 cursor-pointer relative group"
              style={{
                background: color,
                boxShadow: w >= 0.5 ? `0 0 4px ${color}80` : 'none',
              }}
            >
              {trace.meta && (
                <div className="absolute top-0 right-0 w-1 h-1 rounded-full bg-pal-gold" />
              )}
              <div className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 rounded bg-pal-bg border border-pal-border text-[9px] text-pal-text whitespace-nowrap opacity-0 group-hover:opacity-100 pointer-events-none transition-opacity z-20">
                id:{trace.id} w:{trace.weight.toFixed(2)} {trace.tag && `· ${trace.tag}`}
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}
