// Logs stream — live tailing feed
const { useState: useLogsState, useEffect: useLogsEffect, useRef: useLogsRef } = React;

function Logs({ logs, live }) {
  const [levelFilter, setLevelFilter] = useLogsState('all');
  const [follow, setFollow] = useLogsState(true);
  const containerRef = useLogsRef(null);

  const visible = logs.filter(l => levelFilter === 'all' || l.lvl === levelFilter);

  useLogsEffect(() => {
    if (follow && containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
    }
  }, [visible.length, follow]);

  return (
    <div style={{display:'flex', flexDirection:'column', height:'100%'}}>
      <div style={{display:'flex', alignItems:'center', gap: 12, padding: '8px 16px', borderBottom:'1px solid var(--border)', background:'var(--bg-1)', flexShrink: 0}}>
        <span style={{fontSize: 11, color:'var(--text-faint)', letterSpacing:'0.08em', textTransform:'uppercase'}}>Level</span>
        <div className="pill-toggle">
          {['all','I','W','E','D'].map(l => (
            <button key={l} className={levelFilter === l ? 'on' : ''} onClick={() => setLevelFilter(l)}>
              {l === 'all' ? 'all' : l === 'I' ? 'info' : l === 'W' ? 'warn' : l === 'E' ? 'error' : 'debug'}
            </button>
          ))}
        </div>
        <span style={{marginLeft: 12, fontSize: 11, color:'var(--text-faint)'}}>
          {visible.length} lines · {live ? 'tailing' : 'paused'}
        </span>
        <div style={{marginLeft:'auto', display:'flex', gap:6}}>
          <button className={`btn ${follow ? 'on' : ''}`} onClick={() => setFollow(f => !f)} style={{padding:'3px 10px'}}>
            follow
          </button>
        </div>
      </div>
      <div ref={containerRef} className="logs" style={{flex: 1, overflow: 'auto'}}>
        {visible.map((l, i) => (
          <div key={i} className="log-line">
            <span className="ts">{window.fmtTs(l.ts)}</span>
            <span className={`lvl ${l.lvl}`}>{l.lvl === 'I' ? 'INFO' : l.lvl === 'W' ? 'WARN' : l.lvl === 'E' ? 'ERROR' : 'DEBUG'}</span>
            <span className="src">{l.src}</span>
            <span className="msg">
              <span style={{color: 'var(--text-mute)'}}>{l.node}</span> {l.msg}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Logs });
