import useConnectionStore from '../store/connectionStore'

/**
 * A 3px bar pinned to the very top of the screen (above the header).
 * Always visible — color signals connection state at a glance:
 *
 *   sseAlive=true  → solid green  (SSE stream live)
 *   online only    → solid blue   (HTTP reachable, SSE not yet connected)
 *   reconnecting   → amber, animated sweep
 *   offline        → red, animated sweep
 *   offline >5min  → flashing red
 */
export default function ConnectivityBar() {
  const { status, sseAlive, flashing } = useConnectionStore()

  const isOnline = status === 'online'
  const isReconnecting = status === 'reconnecting'
  const isOffline = status === 'offline'

  const color = isOnline
    ? (sseAlive ? '#22c55e' : '#3b82f6')
    : isReconnecting
    ? '#f59e0b'
    : '#ef4444'

  const animated = !isOnline

  return (
    <>
      <style>{`
        @keyframes connectivity-sweep {
          0%   { background-position: -200% center; }
          100% { background-position: 300% center; }
        }
        @keyframes connectivity-flash {
          0%, 100% { opacity: 1; }
          50%       { opacity: 0.15; }
        }
        .connectivity-bar {
          position: relative;
          height: 3px;
          flex-shrink: 0;
          overflow: hidden;
        }
        .connectivity-bar--sweep {
          background: linear-gradient(
            90deg,
            var(--cb-color) 0%,
            var(--cb-color) 30%,
            color-mix(in srgb, var(--cb-color) 20%, transparent) 50%,
            var(--cb-color) 70%,
            var(--cb-color) 100%
          );
          background-size: 200% 100%;
          animation: connectivity-sweep 1.8s ease-in-out infinite;
        }
        .connectivity-bar--flash {
          animation: connectivity-flash 0.7s ease-in-out infinite;
        }
      `}</style>

      <div
        className={[
          'connectivity-bar',
          animated && !flashing ? 'connectivity-bar--sweep' : '',
          flashing ? 'connectivity-bar--flash' : '',
        ].join(' ')}
        style={{
          '--cb-color': color,
          backgroundColor: color,
          boxShadow: `0 0 6px 1px ${color}99`,
        }}
      />
    </>
  )
}
