import { useEffect, useRef, type CSSProperties } from 'react';

interface HPBarProps {
  current: number;
  max: number;
  /** Bar color, defaults to health green */
  color?: string;
  /** Height in pixels */
  height?: number;
  /** Show numeric text */
  showText?: boolean;
  /** Label prefix (e.g., "HP", "Enemy") */
  label?: string;
}

const containerStyle: CSSProperties = {
  width: '100%',
  borderRadius: 4,
  overflow: 'hidden',
  position: 'relative',
  backgroundColor: 'rgba(0, 0, 0, 0.6)',
  border: '1px solid rgba(255, 255, 255, 0.15)',
};

const textStyle: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  color: '#fff',
  fontSize: 12,
  fontWeight: 700,
  textShadow: '0 1px 2px rgba(0,0,0,0.8)',
  pointerEvents: 'none',
};

export function HPBar({
  current,
  max,
  color = '#44cc44',
  height = 20,
  showText = true,
  label,
}: HPBarProps) {
  const barRef = useRef<HTMLDivElement>(null);
  const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;

  // Animate width via ref to avoid React re-renders on every tick
  useEffect(() => {
    if (barRef.current) {
      barRef.current.style.width = `${ratio * 100}%`;
    }
  }, [ratio]);

  // Color shifts to red as HP drops
  const barColor = ratio > 0.5 ? color : ratio > 0.25 ? '#ccaa22' : '#cc3333';

  const barStyle: CSSProperties = {
    height: '100%',
    width: `${ratio * 100}%`,
    backgroundColor: barColor,
    transition: 'width 0.2s ease-out, background-color 0.3s ease',
    borderRadius: 4,
  };

  return (
    <div style={{ ...containerStyle, height }}>
      <div ref={barRef} style={barStyle} />
      {showText && (
        <div style={textStyle}>
          {label ? `${label}: ` : ''}{Math.ceil(current)} / {Math.ceil(max)}
        </div>
      )}
    </div>
  );
}
