import { type CSSProperties } from 'react';
import { DebuffType, type ActiveDebuff } from '../game/types';
import { DEBUFF_COLORS } from '../shared/constants';

// ---- Debuff metadata ----

const DEBUFF_META: Record<DebuffType, { icon: string; label: string }> = {
  [DebuffType.Poison]: { icon: '\u2620\uFE0F', label: 'Poison' },
  [DebuffType.Freeze]: { icon: '\u2744\uFE0F', label: 'Freeze' },
  [DebuffType.Burn]:   { icon: '\uD83D\uDD25', label: 'Burn' },
  [DebuffType.Stun]:   { icon: '\uD83D\uDCAB', label: 'Stun' },
  [DebuffType.Slow]:   { icon: '\uD83D\uDC22', label: 'Slow' },
  [DebuffType.Weaken]: { icon: '\uD83D\uDCC9', label: 'Weaken' },
};

// ---- Types ----

interface DebuffBarProps {
  debuffs: ActiveDebuff[];
}

// ---- Styles ----

const containerStyle: CSSProperties = {
  display: 'flex',
  gap: 4,
  flexWrap: 'wrap',
  marginTop: 4,
};

const debuffStyle: CSSProperties = {
  display: 'flex',
  alignItems: 'center',
  gap: 3,
  padding: '2px 6px',
  borderRadius: 6,
  fontSize: 11,
  fontWeight: 600,
  color: '#fff',
  textShadow: '0 1px 2px rgba(0,0,0,0.8)',
};

// ---- Component ----

function DebuffIcon({ debuff }: { debuff: ActiveDebuff }) {
  const meta = DEBUFF_META[debuff.type];
  const color = DEBUFF_COLORS[debuff.type] ?? '#999';
  const remainingSec = Math.ceil(debuff.remainingMs / 1000);

  /** Pulse when more than 80% duration remains (just applied). */
  const justApplied = debuff.durationMs > 0
    && debuff.remainingMs / debuff.durationMs > 0.8;

  const style: CSSProperties = {
    ...debuffStyle,
    backgroundColor: `${color}33`,
    border: `1px solid ${color}88`,
    animation: justApplied ? 'debuff-pulse 0.6s ease-out' : undefined,
  };

  return (
    <span style={style} title={meta.label}>
      <span style={{ fontSize: 13 }}>{meta.icon}</span>
      <span>{remainingSec}s</span>
    </span>
  );
}

export function DebuffBar({ debuffs }: DebuffBarProps) {
  if (debuffs.length === 0) return null;

  return (
    <>
      {/* Inject keyframe animation once */}
      <style>{`
        @keyframes debuff-pulse {
          0%   { transform: scale(1);   opacity: 0.6; }
          50%  { transform: scale(1.2); opacity: 1;   }
          100% { transform: scale(1);   opacity: 1;   }
        }
      `}</style>
      <div style={containerStyle}>
        {debuffs.map((d) => (
          <DebuffIcon key={d.type} debuff={d} />
        ))}
      </div>
    </>
  );
}
