import React, { HTMLAttributes, useRef } from 'react'
import { useCanvasStore } from '../../state/canvasStore'
import { useKrateStore } from '../../state/krateStore'

interface MinimapProps extends HTMLAttributes<HTMLDivElement> {}

export const Minimap: React.FC<MinimapProps> = ({ ...props }) => {
  const { camX, camY, zoom } = useCanvasStore()
  const { krates } = useKrateStore()
  const minimapRef = useRef<HTMLDivElement>(null)
  
  const minimapWidth = 180
  const minimapHeight = 120
  const worldWidth = 12000
  const worldHeight = 8000
  const minimapScaleX = minimapWidth / worldWidth
  const minimapScaleY = minimapHeight / worldHeight

  const viewportWidthWorld = window.innerWidth / zoom
  const viewportHeightWorld = window.innerHeight / zoom
  
  const viewportX = camX * minimapScaleX
  const viewportY = camY * minimapScaleY
  const viewportW = viewportWidthWorld * minimapScaleX
  const viewportH = viewportHeightWorld * minimapScaleY

  const handleClick = (e: React.MouseEvent) => {
    const rect = minimapRef.current?.getBoundingClientRect()
    if (!rect) return
    
    const clickX = e.clientX - rect.left
    const clickY = e.clientY - rect.top
    
    const worldX = (clickX / minimapScaleX) - camX - viewportWidthWorld / 2
    const worldY = (clickY / minimapScaleY) - camY - viewportHeightWorld / 2
    
    useCanvasStore.getState().setCam(worldX, worldY)
  }

  return (
    <div
      ref={minimapRef}
      onClick={handleClick}
      style={{
        position: 'absolute',
        right: '18px',
        bottom: '64px',
        width: minimapWidth,
        height: minimapHeight,
        background: 'rgba(16,20,28,.97)',
        border: '1px solid rgba(140,165,200,.2)',
        borderRadius: '4px',
        overflow: 'hidden',
        zIndex: 30,
      }}
      {...props}
    >
      {Array.from(krates.values()).map((krate: any) => (
        <div
          key={krate.id}
          style={{
            position: 'absolute',
            left: (krate.x as number) * minimapScaleX,
            top: (krate.y as number) * minimapScaleY,
            width: (krate.width as number) * minimapScaleX,
            height: (krate.height as number) * minimapScaleY,
            backgroundColor: (krate.color as string) || '#6fb1ff',
            opacity: 0.7,
          }}
        />
      ))}
      
      <div
        style={{
          position: 'absolute',
          left: viewportX,
          top: viewportY,
          width: viewportW,
          height: viewportH,
          border: '1px solid #4dd6e8',
          borderColor: 'rgba(77, 214, 232, 0.4)',
          boxSizing: 'border-box',
        }}
      />
    </div>
  )
}