/* global React */
// =============================================================================
// <StreamStatus> — small chip showing live SSE connection state.
//
// Drop into any panel header that uses useStream():
//   <StreamStatus status={status} error={error} lastEvent={lastEvent} />
//
// Renders as a colour-coded pill:
//   green pulse  — open (live), shows age of last event
//   amber        — connecting / reconnecting (with retry message)
//   red          — error / closed
//   grey         — idle (no URL or disabled)
// =============================================================================

function StreamStatus(props) {
  const { status, error, lastEvent, label } = props;

  // Re-render every second so the "Xs ago" age stays fresh.
  const [, force] = React.useState(0);
  React.useEffect(() => {
    if (status !== "open") return;
    const t = setInterval(() => force(n => n + 1), 1000);
    return () => clearInterval(t);
  }, [status]);

  let cls = "pill pill-dim";
  let text = "OFFLINE";
  let title = "";

  if (status === "open") {
    cls = "pill pill-up";
    if (lastEvent && lastEvent.ts) {
      const ageSec = Math.max(0, Math.floor((Date.now() - lastEvent.ts) / 1000));
      text = ageSec < 2 ? "LIVE" : ("LIVE · " + ageSec + "s");
      title = "Last event: " + (lastEvent.type || "?") + " · " + ageSec + "s ago";
    } else {
      text = "LIVE";
      title = "Connected, no events yet";
    }
  } else if (status === "connecting") {
    cls = "pill pill-amber";
    text = "CONNECTING";
    title = "Opening stream";
  } else if (status === "reconnecting") {
    cls = "pill pill-amber";
    text = "RECONNECTING";
    title = error || "reconnecting";
  } else if (status === "error") {
    cls = "pill pill-down";
    text = "ERROR";
    title = error || "stream failed";
  } else if (status === "closed") {
    cls = "pill pill-down";
    text = "CLOSED";
    title = error || "stream closed";
  } else {
    cls = "pill pill-dim";
    text = "IDLE";
    title = "no stream";
  }

  return (
    <span className={cls} title={title} style={{ fontSize: 9, letterSpacing: "0.06em" }}>
      {status === "open" ? <span className="dot dot-live" style={{ marginRight: 4 }} /> : null}
      {label ? (label + " · ") : ""}{text}
    </span>
  );
}

window.StreamStatus = StreamStatus;
