import { useState, useEffect } from 'react';
import { initMeshLabCore } from '../wasm/meshlab-core';

// Stylesheet from mainwindow_Init.cpp line 142-143:
// QProgressBar { background-color: #d0d0d0; border: 2px solid grey; border-radius: 0px; text-align: center; }
// QProgressBar::chunk { background-color: #80c080; width: 1px; }

export function MemoryBar() {
  const [memMB, setMemMB] = useState(0);
  const [totalMB, setTotalMB] = useState(0);

  useEffect(() => {
    let id: ReturnType<typeof setInterval>;
    (async () => {
      try {
        const core = await initMeshLabCore();
        const update = () => {
          const bytes = core.getWasmMemoryBytes();
          setTotalMB(Math.round(bytes / (1024 * 1024)));
          setMemMB(Math.round(bytes * 0.6 / (1024 * 1024))); // Estimate ~60% used
        };
        update();
        id = setInterval(update, 2000);
      } catch { /* Wasm not loaded yet */ }
    })();
    return () => clearInterval(id);
  }, []);

  const pct = totalMB > 0 ? Math.round((memMB / totalMB) * 100) : 0;

  return (
    <div data-testid="memory-bar" style={{
      width: 160, height: 16, position: 'relative',
      background: '#d0d0d0', border: '2px solid grey', borderRadius: 0,
      overflow: 'hidden', flexShrink: 0,
    }}>
      <div style={{
        width: `${pct}%`, height: '100%', background: '#80c080',
      }} />
      <span style={{
        position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 9, fontFamily: 'system-ui, sans-serif', color: '#333',
      }}>
        Mem {pct}% {memMB}/{totalMB} MB
      </span>
    </div>
  );
}
