import { useEffect, useRef, useState } from 'react';
import { useMeshStore } from '../stores/meshStore';
import { MemoryBar } from './MemoryBar';

const MODE_LABELS: Record<string, string> = {
  solid: 'BO_RENDERING', flat: 'FLAT_RENDERING', wireframe: 'WIRE_RENDERING', points: 'POINT_RENDERING',
};

export function StatusBar() {
  const { state } = useMeshStore();
  const [fps, setFps] = useState(0);
  const frameCount = useRef(0);
  const lastTime = useRef(performance.now());

  useEffect(() => {
    let id: number;
    const tick = () => {
      frameCount.current++;
      const now = performance.now();
      if (now - lastTime.current >= 1000) {
        setFps(frameCount.current);
        frameCount.current = 0;
        lastTime.current = now;
      }
      id = requestAnimationFrame(tick);
    };
    id = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(id);
  }, []);

  const active = state.layers.find(l => l.id === state.activeLayerId);
  const totalVerts = state.layers.reduce((s, l) => s + l.vertexCount, 0);
  const totalFaces = state.layers.reduce((s, l) => s + l.faceCount, 0);

  return (
    <div
      data-testid="status-bar"
      style={{
        height: 22,
        background: '#d4d4d4',
        color: '#333',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '0 6px',
        fontSize: 11,
        fontFamily: '"Courier New", monospace',
        borderTop: '1px solid #b0b0b0',
        flexShrink: 0,
        gap: 4,
      }}
    >
      {/* Left: FOV, FPS, render mode */}
      <span style={{ whiteSpace: 'nowrap', color: '#444' }}>
        FOV: 60 | FPS: {fps.toFixed(1)} | {MODE_LABELS[state.globalRenderMode] || 'BO_RENDERING'}
      </span>

      {/* Center: status message + mesh info */}
      <span data-testid="status-message" style={{ flex: 1, overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis', textAlign: 'center', color: '#333' }}>
        {state.statusMessage}
        {active ? ` | Mesh: ${active.name}` : ''}
      </span>

      {/* Right-center: vertices, faces, selection */}
      <span style={{ color: '#555', whiteSpace: 'nowrap' }}>
        Vertices: {totalVerts.toLocaleString()} | Faces: {totalFaces.toLocaleString()}
        {state.selectedFaceCount > 0 && ` | Sel v:0 f:${state.selectedFaceCount}`}
      </span>

      {/* Right: memory bar */}
      <MemoryBar />
    </div>
  );
}
