import { useRef, useEffect, useState } from 'react';

// Log area: Source is QColor(128,16,16) but desktop renders it as dark magenta/wine
// because it's alpha-blended over the blue gradient in OpenGL viewport.
// For the docked panel, we approximate the visual result: dark wine/magenta.
const LOG_BG = '#5c1040';
const LOG_TEXT = '#e0e0e0';

export interface LogEntry {
  level: 'info' | 'warning' | 'error' | 'filter' | 'system';
  message: string;
  timestamp: number;
}

interface LogPanelProps {
  entries: LogEntry[];
}

const LEVEL_COLORS: Record<string, string> = {
  info: LOG_TEXT,
  warning: '#ffff00',
  error: '#ff4444',
  filter: '#88ccff',
  system: '#aaaaaa',
};

export function LogPanel({ entries }: LogPanelProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [height, setHeight] = useState(100);
  const dragging = useRef(false);

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

  useEffect(() => {
    const onMove = (e: MouseEvent) => {
      if (!dragging.current) return;
      setHeight((h) => Math.max(24, h - e.movementY));
    };
    const onUp = () => { dragging.current = false; };
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    return () => { window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
  }, []);

  return (
    <div data-testid="log-panel" style={{ flexShrink: 0, background: LOG_BG, display: 'flex', flexDirection: 'column' }}>
      <div
        data-testid="log-resize-handle"
        onMouseDown={() => { dragging.current = true; }}
        style={{ height: 4, cursor: 'ns-resize', background: '#400830' }}
      />
      <div ref={scrollRef} style={{
        height, overflowY: 'auto', padding: '2px 6px',
        fontFamily: '"Courier New", monospace', fontSize: 12, color: LOG_TEXT,
      }}>
        {entries.map((e, i) => (
          <div key={i} style={{ color: LEVEL_COLORS[e.level] || LOG_TEXT, whiteSpace: 'pre-wrap' }}>
            {e.message}
          </div>
        ))}
        {entries.length === 0 && <div style={{ color: '#806070' }}>Log output</div>}
      </div>
    </div>
  );
}
