import { useEffect, useRef, type CSSProperties } from 'react';
import { useT } from '../i18n';

const MAX_VISIBLE_LINES = 5;

const panelBase: CSSProperties = {
  position: 'absolute',
  top: '26%',
  zIndex: 50,
  maxWidth: 200,
  padding: '8px 10px',
  borderRadius: 8,
  backgroundColor: 'rgba(8, 10, 18, 0.82)',
  border: '1px solid rgba(255, 255, 255, 0.1)',
  boxShadow: '0 4px 16px rgba(0,0,0,0.45)',
  pointerEvents: 'none',
};

const titleStyle: CSSProperties = {
  fontSize: 10,
  fontWeight: 700,
  letterSpacing: 0.6,
  textTransform: 'uppercase',
  color: 'rgba(180, 195, 220, 0.85)',
  marginBottom: 4,
};

const scrollStyle: CSSProperties = {
  maxHeight: `${MAX_VISIBLE_LINES * 18}px`,
  overflowY: 'auto',
  fontSize: 11,
  lineHeight: 1.45,
  color: '#c8c8d0',
  scrollbarWidth: 'thin',
};

const lineStyle: CSSProperties = {
  margin: 0,
  padding: 0,
  wordBreak: 'break-word',
};

interface CombatLogPanelProps {
  lines: string[];
  /** Dock panel on this side; floating damage stays near center / opposite side. */
  anchor: 'left' | 'right';
  visible: boolean;
}

export function CombatLogPanel({ lines, anchor, visible }: CombatLogPanelProps) {
  const tr = useT();
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const el = scrollRef.current;
    if (el) {
      el.scrollTop = el.scrollHeight;
    }
  }, [lines]);

  if (!visible || lines.length === 0) {
    return null;
  }

  const pos: CSSProperties =
    anchor === 'left'
      ? { left: 10, right: 'auto' }
      : { right: 10, left: 'auto' };

  return (
    <div style={{ ...panelBase, ...pos }}>
      <div style={titleStyle}>{tr.combatLogTitle}</div>
      <div ref={scrollRef} style={scrollStyle}>
        {lines.map((line, i) => (
          <p key={`${i}-${line.slice(0, 24)}`} style={lineStyle}>
            {line}
          </p>
        ))}
      </div>
    </div>
  );
}
