import React from 'react'
import { useTextures } from '../../context/TextureContext'
import { useScale } from '../../context/ScaleContext'
import type { ProgressBar as ProgressBarDef } from '../../types'

interface ProgressBarProps {
  definition: ProgressBarDef
  properties: Record<string, number>
  backgroundTexture: string
}

export function ProgressBar({ definition, properties, backgroundTexture }: ProgressBarProps) {
  const textures = useTextures()
  const { scale } = useScale()

  const value = definition.getValue(properties)
  const max = definition.getMax(properties)
  const ratio = max > 0 ? Math.min(1, Math.max(0, value / max)) : 0

  if (ratio <= 0) return null

  // Use standalone sprite image when available (mc-assets 1.20+ format),
  // otherwise fall back to clipping from the background GUI texture.
  const imgUrl = definition.spriteTexture
    ? textures.getGuiTextureUrl(definition.spriteTexture)
    : textures.getGuiTextureUrl(backgroundTexture)

  const { x, y, width: w, height: h, textureX: srcX, textureY: srcY, direction } = definition

  // Compute the visible sub-rectangle of the sprite (unscaled pixels).
  // 'up' fills from bottom, 'left' fills from right — offset into the sprite accordingly.
  let visibleX = 0
  let visibleY = 0
  let visibleW = w
  let visibleH = h

  // Round to whole pixels to avoid sub-pixel jitter (vanilla MC uses integer steps).
  switch (direction) {
    case 'right':
      visibleW = Math.floor(w * ratio)
      break
    case 'left':
      visibleW = Math.floor(w * ratio)
      visibleX = w - visibleW
      break
    case 'down':
      visibleH = Math.floor(h * ratio)
      break
    case 'up':
      visibleH = Math.floor(h * ratio)
      visibleY = h - visibleH
      break
  }

  return (
    <div
      style={{
        position: 'absolute',
        left: (x + visibleX) * scale,
        top: (y + visibleY) * scale,
        width: visibleW * scale,
        height: visibleH * scale,
        overflow: 'hidden',
        pointerEvents: 'none',
      }}
    >
      {/* Render at 1× then scale via CSS transform, matching InventoryBackground */}
      <div style={{
        width: visibleW,
        height: visibleH,
        overflow: 'hidden',
        transform: `scale(${scale})`,
        transformOrigin: 'top left',
      }}>
        <img
          src={imgUrl}
          alt=""
          aria-hidden
          style={{
            position: 'absolute',
            left: -(srcX + visibleX),
            top: -(srcY + visibleY),
            imageRendering: 'pixelated',
            display: 'block',
            maxWidth: 'none',
          }}
          draggable={false}
        />
      </div>
    </div>
  )
}