// StatusBar — the 28px strip at the bottom. Surfaces the three bits of
// information an operator tends to want at a glance:
//   * Connection state to the configured node (poll /api/netstats).
//   * Current chain height (last successful poll).
//   * Node URL (short, hover-tooltip for the full thing).
//
// Poll interval is 5 seconds — low enough to feel live, cheap enough
// that even a free-tier node won't notice.

import React, { useEffect, useState } from 'react';
import { useStore } from '@/lib/store';
import { getNetStats, getNodeUrl, onNodeUrlChange } from '@/lib/api';

type ConnState = 'online' | 'connecting' | 'offline';

export function StatusBar(): React.ReactElement {
  const nodeUrl = useStore(s => s.settings.nodeUrl);
  const [conn,   setConn]   = useState<ConnState>('connecting');
  const [height, setHeight] = useState<number | null>(null);
  const [url,    setUrl]    = useState<string>(getNodeUrl());

  useEffect(() => onNodeUrlChange(setUrl), []);

  useEffect(() => {
    let cancelled = false;
    const poll = async () => {
      try {
        const s = await getNetStats();
        if (cancelled) return;
        setConn('online');
        setHeight(s.total_blocks);
      } catch {
        if (cancelled) return;
        setConn('offline');
      }
    };
    setConn('connecting');
    poll();
    const t = setInterval(poll, 5_000);
    return () => {
      cancelled = true;
      clearInterval(t);
    };
  }, [nodeUrl]);

  const dot = conn === 'online' ? '#3ba55d' :
              conn === 'connecting' ? '#f0b35a' :
              '#f4212e';

  const shortUrl = url
    .replace(/^https?:\/\//, '')
    .replace(/\/$/, '');

  return (
    <footer style={{
      height: 28, minHeight: 28,
      background: '#000',
      borderTop: '1px solid #1f1f1f',
      display: 'flex', alignItems: 'center', padding: '0 16px', gap: 14,
      fontSize: 11, color: '#8b8b8b',
    }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <span style={{
          width: 8, height: 8, borderRadius: 4, background: dot,
        }} />
        {conn}
      </span>
      <span style={{ opacity: 0.5 }}>·</span>
      <span title={url}>{shortUrl}</span>
      <span style={{ opacity: 0.5 }}>·</span>
      <span>height {height ?? '—'}</span>
      <div style={{ flex: 1 }} />
    </footer>
  );
}
