"""Connection status bar."""
from textual.widgets import Static


class StatusBar(Static):
    """Bottom status bar showing connection info."""

    DEFAULT_CSS = """
    StatusBar {
        dock: bottom;
        height: 1;
        background: $primary-background;
        color: $text;
        padding: 0 1;
    }
    """

    def __init__(self):
        super().__init__("")
        self.connected = False
        self.pkt_count = 0
        self.drop_count = 0
        self.last_seq = 0
        self.fps = 0.0          # telemetry frames RECEIVED per second
        self.sent_fps = 0.0     # frames the MCU GENERATED per second (from seq advance)
        self.loss_pct = 0.0     # 100 * (1 - received/generated)

    def refresh_status(self):
        conn = "[green]CONN:OK[/green]" if self.connected else "[red]CONN:LOST[/red]"
        if self.loss_pct >= 5.0:
            loss = f"[red]LOSS:{self.loss_pct:.0f}%[/red]"
        else:
            loss = f"LOSS:{self.loss_pct:.0f}%"
        self.update(f"  {conn}  PKTS:{self.pkt_count}  DROPS:{self.drop_count}  SEQ:{self.last_seq}"
                    f"  RX:{self.fps:.1f}Hz  TX:{self.sent_fps:.1f}Hz  {loss}")
