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

function formatTime(timestamp: number): string {
  const d = new Date(timestamp);
  const hh = String(d.getHours()).padStart(2, '0');
  const mm = String(d.getMinutes()).padStart(2, '0');
  return `${hh}:${mm}`;
}

const scrollAreaStyle: CSSProperties = {
  flex: 1,
  overflowY: 'auto',
  padding: '4px 2px',
  fontSize: 12,
  lineHeight: 1.6,
  color: '#bbb',
  maxHeight: 'min(52vh, 420px)',
};

const entryStyle: CSSProperties = {
  whiteSpace: 'nowrap',
  overflow: 'hidden',
  textOverflow: 'ellipsis',
};

const timestampStyle: CSSProperties = {
  color: 'rgba(140,160,200,0.7)',
  marginRight: 4,
  fontFamily: 'monospace',
  fontSize: 11,
};

/** Scrollable adventure log list (Hero sheet Journal tab). */
export function AdventureLogEntries({
  entries,
  scrollRef,
}: {
  entries: AdventureLogEntry[];
  scrollRef?: RefObject<HTMLDivElement | null>;
}) {
  const tr = useT();
  const innerRef = useRef<HTMLDivElement>(null);
  const ref = scrollRef ?? innerRef;

  useEffect(() => {
    if (ref.current) {
      ref.current.scrollTop = ref.current.scrollHeight;
    }
  }, [entries.length, ref]);

  return (
    <div ref={ref} style={scrollAreaStyle}>
      {entries.length === 0 && (
        <div style={{ textAlign: 'center', opacity: 0.5, padding: 12 }}>
          {tr.noEventsYet}
        </div>
      )}
      {entries.map((entry) => (
        <div key={entry.id} style={entryStyle}>
          <span style={timestampStyle}>[{formatTime(entry.timestamp)}]</span>
          {entry.message}
        </div>
      ))}
    </div>
  );
}
