#!/usr/bin/env bash
# ui/logs.module.sh — rendering for logs and watch data

function ui::logs::build_dest() {
  local dest_ip="${1:-}" dest_port="${2:-}" proto="${3:-}" svc="${4:-}"
  if [[ -n "$svc" ]]; then
    [[ -n "$dest_port" ]] && echo "${svc}/${proto}" || echo "${svc} (${proto})"
  else
    [[ -n "$dest_port" ]] && echo "${dest_ip}:${dest_port}/${proto}" || echo "${dest_ip} (${proto})"
  fi
}

function ui::logs::fw_section_header() {
  local cols=$(( $(tput cols 2>/dev/null || echo 80) - 4 ))
  printf "  Firewall Drops\n"
  printf "  %s\n" "$(printf '─%.0s' $(seq 1 $cols))"
}

function ui::logs::wg_section_header() {
  local cols=$(( $(tput cols 2>/dev/null || echo 80) - 4 ))
  printf "  WireGuard Events\n"
  printf "  %s\n" "$(printf '─%.0s' $(seq 1 $cols))"
}

function ui::logs::fw_section_header_table() {
  printf "  Firewall Drops:\n"
  printf "  %-20s %-18s %-25s %s\n" "TIME" "CLIENT" "DESTINATION" "PROTOCOL"
  printf "  %s\n" "$(printf '─%.0s' {1..75})"
}

function ui::logs::wg_section_header_table() {
  printf "  WireGuard Events:\n"
  printf "  %-20s %-20s %-18s %s\n" "TIME" "CLIENT" "ENDPOINT" "EVENT"
  printf "  %s\n" "$(printf '─%.0s' {1..75})"
}

function ui::logs::fw_row() {
  local ts="${1:-}" client="${2:-}" dest_ip="${3:-}" dest_port="${4:-}" \
        proto="${5:-}" svc_name="${6:-}" count="${7:-1}" \
        w_client="${8:-20}" w_dest="${9:-30}" \
        src_endpoint="${10:-}" src_resolved="${11:-}" \
        w_endpoint="${12:-0}" resolved_only="${13:-false}"
 
  local ts_pad client_pad
  ts_pad=$(printf "%-11s" "$ts")
  client_pad=$(printf "%-${w_client}s" "$client")
 
  # ── Source endpoint ──
  # " → " = 5 bytes, 3 visible chars → overcount by _UI_ARROW_EXTRA=2
  local src_padded=""
  if [[ "$w_endpoint" -gt 0 ]]; then
    local src_colored src_visible_len pad_n
 
    if [[ -n "$src_endpoint" ]]; then
      if $resolved_only; then
        src_colored="${src_resolved:-$src_endpoint}"
        src_visible_len=${#src_colored}
      else
        if [[ -n "$src_resolved" ]]; then
          src_colored="${src_endpoint} \033[2m→ ${src_resolved}\033[0m"
          # bytes: endpoint + " → " (5 bytes, 3 visible) + resolved
          # visible: endpoint + 3 + resolved
          src_visible_len=$(( ${#src_endpoint} + 3 + ${#src_resolved} ))
        else
          src_colored="${src_endpoint}"
          src_visible_len=${#src_endpoint}
        fi
      fi
    else
      # — is 3 bytes, 1 visible char
      src_colored="\033[2m—\033[0m"
      src_visible_len=1
    fi
 
    pad_n=$(( w_endpoint - src_visible_len ))
    [[ $pad_n -lt 0 ]] && pad_n=0
    src_padded=$(printf "%b%*s" "$src_colored" "$pad_n" "")
  fi
 
  # ── Destination ──
  local svc_display="" raw_suffix=""
  if [[ -n "$svc_name" ]]; then
    [[ -n "$dest_port" ]] && svc_display="${svc_name}/${proto}" \
                          || svc_display="${svc_name} (${proto})"
    if ! $resolved_only; then
      [[ -n "$dest_port" ]] && raw_suffix=" \033[2m(${dest_ip}:${dest_port})\033[0m" \
                            || raw_suffix=" \033[2m(${dest_ip})\033[0m"
    fi
  else
    [[ -n "$dest_port" ]] && svc_display="${dest_ip}:${dest_port}/${proto}" \
                          || svc_display="${dest_ip} (${proto})"
  fi
 
  local raw_plain=""
  if ! $resolved_only; then
    [[ -n "$svc_name" && -n "$dest_port" ]] && raw_plain=" (${dest_ip}:${dest_port})"
    [[ -n "$svc_name" && -z "$dest_port" ]] && raw_plain=" (${dest_ip})"
  fi
  local full_dest_len=$(( ${#svc_display} + ${#raw_plain} ))
  local dest_pad_n=$(( w_dest - full_dest_len ))
  [[ $dest_pad_n -lt 0 ]] && dest_pad_n=0
 
  local count_suffix=""
  [[ "$count" -gt 1 ]] && count_suffix=" \033[2m(x${count})\033[0m"
 
  if [[ "$w_endpoint" -gt 0 ]]; then
    printf "  %s  %s  %b  \033[1;31m→\033[0m %s%b%*s%b\n" \
      "$ts_pad" "$client_pad" \
      "$src_padded" \
      "$svc_display" "$raw_suffix" \
      "$dest_pad_n" "" \
      "$count_suffix"
  else
    printf "  %s  %s  \033[1;31m→\033[0m %s%b%*s%b\n" \
      "$ts_pad" "$client_pad" \
      "$svc_display" "$raw_suffix" \
      "$dest_pad_n" "" \
      "$count_suffix"
  fi
}

function ui::logs::fw_row_table() {
  local ts="${1:-}" client="${2:-}" dst="${3:-}" proto="${4:-}" count="${5:-1}"
  local count_str=""
  [[ "$count" -gt 1 ]] && count_str=" (x${count})"
  printf "  %-20s %-18s %-25s %s%s\n" "$ts" "$client" "$dst" "$proto" "$count_str"
}

# function ui::logs::wg_row() {
#   local ts="${1:-}" client="${2:-}" endpoint="${3:-}" event="${4:-}" \
#         count="${5:-1}" w_client="${6:-20}" w_endpoint="${7:-20}" \
#         gap_seconds="${8:-}" resolved="${9:-}"
 
#   local event_color
#   case "$event" in
#     handshake) event_color="\033[1;32m" ;;
#     attempt)   event_color="\033[1;31m" ;;
#     *)         event_color="\033[0;37m" ;;
#   esac
 
#   local count_suffix=""
#   [[ "$count" -gt 1 ]] && count_suffix=" \033[2m(x${count})\033[0m"
 
#   # Gap suffix — offline label only when gap > threshold * 2
#   local gap_suffix=""
#   if [[ "$event" == "handshake" && -n "$gap_seconds" && "$gap_seconds" -gt 0 ]]; then
#     local gap_int="$gap_seconds"
#     local threshold="${WG_HANDSHAKE_CHECK_TIME_SEC:-300}"
#     local offline_label=""
#     [[ "$gap_int" -gt $(( threshold * 2 )) ]] && offline_label=" offline"
#     if (( gap_int >= 3600 )); then
#       gap_suffix="  \033[2m↑ $(( gap_int / 3600 ))h${offline_label}\033[0m"
#     elif (( gap_int >= 60 )); then
#       gap_suffix="  \033[2m↑ $(( gap_int / 60 ))m${offline_label}\033[0m"
#     fi
#   fi
 
#   # ── Endpoint — native padding, no ui::pad_mb ──
#   local endpoint_colored endpoint_visible_len
#   local endpoint_raw="${endpoint:--}"
 
#   if [[ -n "$resolved" && -n "$endpoint" ]]; then
#     endpoint_colored="${endpoint} \033[2m→ ${resolved}\033[0m"
#     endpoint_visible_len=$(( ${#endpoint} + 4 + ${#resolved} - _UI_ARROW_EXTRA ))
#   else
#     endpoint_colored="$endpoint_raw"
#     # "-" is 1 char; endpoint may be empty
#     [[ -n "$endpoint" ]] && endpoint_visible_len=${#endpoint} \
#                          || endpoint_visible_len=1
#   fi
 
#   local ep_pad_n=$(( w_endpoint - endpoint_visible_len ))
#   [[ $ep_pad_n -lt 0 ]] && ep_pad_n=0
#   local endpoint_padded=$(printf "%b%*s" "$endpoint_colored" "$ep_pad_n" "")
#   local ts_pad client_pad
#   ts_pad=$(printf "%-11s" "$ts")
#   client_pad=$(printf "%-${w_client}s" "$client")
 
#   printf "  %s  %s  %b  %b%s\033[0m%b%b\n" \
#     "$ts_pad" "$client_pad" \
#     "$endpoint_padded" \
#     "$event_color" "$event" "$count_suffix" "$gap_suffix"
# }

function ui::logs::wg_row_table() {
  local ts="${1:-}" client="${2:-}" endpoint="${3:-}" event="${4:-}" count="${5:-1}"
  local count_str=""
  [[ "$count" -gt 1 ]] && count_str=" (x${count})"
  local event_colored
  case "$event" in
    attempt*)   event_colored="\033[1;31m${event}\033[0m" ;;
    handshake*) event_colored="\033[1;32m${event}\033[0m" ;;
    *)          event_colored="$event" ;;
  esac
  printf "  %-20s %-20s %-18s %b%s\n" "$ts" "$client" "$endpoint" "$event_colored" "$count_str"
}

_UI_WATCH_FW_COLOR="\033[1;31m"
_UI_WATCH_WG_COLOR="\033[1;32m"

# function ui::watch::fw_row() {
#   local ts="${1:-}" client="${2:-}" dest_display="${3:-}" \
#         w_client="${4:-20}" w_dest="${5:-18}"
 
#   # "fw" is always 2 visible chars — no padding needed
#   local src="${_UI_WATCH_FW_COLOR}fw\033[0m"
 
#   local ts_pad client_pad dest_pad_n
#   ts_pad=$(printf "%-11s" "$ts")
#   client_pad=$(printf "%-${w_client}s" "$client")
#   dest_pad_n=$(( w_dest - ${#dest_display} ))
#   [[ $dest_pad_n -lt 0 ]] && dest_pad_n=0
 
#   printf "  %s  %b  %s  \033[1;31m→\033[0m %s%*s  \033[1;31mdrop\033[0m\n" \
#     "$ts_pad" "$src" "$client_pad" "$dest_display" "$dest_pad_n" ""
# }


# function ui::watch::wg_row() {
#   local ts="${1:-}" client="${2:-}" endpoint="${3:-}" event="${4:-}" \
#         w_client="${5:-20}" w_endpoint="${6:-18}"

#   local event_color
#   case "$event" in
#     handshake) event_color="\033[1;32m" ;;
#     attempt)   event_color="\033[1;31m" ;;
#     *)         event_color="\033[0;37m" ;;
#   esac

#   local endpoint_display="${endpoint:--}"

#   local ts_pad client_pad ep_pad_n
#   ts_pad=$(printf "%-11s" "$ts")
#   client_pad=$(printf "%-${w_client}s" "$client")
#   ep_pad_n=$(( w_endpoint - ${#endpoint_display} ))
#   [[ $ep_pad_n -lt 0 ]] && ep_pad_n=0

#   printf "  %s  %s    %s%*s  %b%s\033[0m\n" \
#     "$ts_pad" "$client_pad" \
#     "$endpoint_display" "$ep_pad_n" "" \
#     "$event_color" "$event"
# }


# function ui::logs::wg_row() {
#   local ts="${1:-}" client="${2:-}" endpoint="${3:-}" event="${4:-}" \
#         count="${5:-1}" w_client="${6:-20}" w_endpoint="${7:-20}" \
#         gap_seconds="${8:-}" resolved="${9:-}"
 
#   local event_color
#   case "$event" in
#     handshake) event_color="\033[1;32m" ;;
#     attempt)   event_color="\033[1;31m" ;;
#     *)         event_color="\033[0;37m" ;;
#   esac
 
#   local count_suffix=""
#   [[ "$count" -gt 1 ]] && count_suffix=" \033[2m(x${count})\033[0m"
 
#   local gap_suffix=""
#   if [[ "$event" == "handshake" && -n "$gap_seconds" && "$gap_seconds" -gt 0 ]]; then
#     local gap_int="$gap_seconds"
#     local threshold="${WG_HANDSHAKE_CHECK_TIME_SEC:-300}"
#     local offline_label=""
#     [[ "$gap_int" -gt $(( threshold * 2 )) ]] && offline_label=" offline"
#     if (( gap_int >= 3600 )); then
#       gap_suffix="  \033[2m↑ $(( gap_int / 3600 ))h${offline_label}\033[0m"
#     elif (( gap_int >= 60 )); then
#       gap_suffix="  \033[2m↑ $(( gap_int / 60 ))m${offline_label}\033[0m"
#     fi
#   fi
 
#   # ── Endpoint padding ──
#   # " → " = 5 bytes, 3 visible → visible = endpoint + 3 + resolved
#   local endpoint_colored endpoint_visible_len
#   if [[ -n "$resolved" && -n "$endpoint" ]]; then
#     endpoint_colored="${endpoint} \033[2m→ ${resolved}\033[0m"
#     endpoint_visible_len=$(( ${#endpoint} + 3 + ${#resolved} ))
#   elif [[ -n "$endpoint" ]]; then
#     endpoint_colored="${endpoint}"
#     endpoint_visible_len=${#endpoint}
#   else
#     endpoint_colored="-"
#     endpoint_visible_len=1
#   fi
 
#   local ep_pad_n=$(( w_endpoint - endpoint_visible_len ))
#   [[ $ep_pad_n -lt 0 ]] && ep_pad_n=0
#   local endpoint_padded
#   endpoint_padded=$(printf "%b%*s" "$endpoint_colored" "$ep_pad_n" "")
 
#   local ts_pad client_pad
#   ts_pad=$(printf "%-11s" "$ts")
#   client_pad=$(printf "%-${w_client}s" "$client")
 
#   printf "  %s  %s  %b  %b%s\033[0m%b%b\n" \
#     "$ts_pad" "$client_pad" \
#     "$endpoint_padded" \
#     "$event_color" "$event" "$count_suffix" "$gap_suffix"
# }

function ui::watch::header_table() {
  printf "\n  %-20s %-8s %-22s %-28s %-14s %s\n" \
    "TIME" "SOURCE" "CLIENT" "DESTINATION/ENDPOINT" "EVENT" "STATUS"
  printf "  %s\n\n" "$(printf '─%.0s' {1..105})"
}

function ui::watch::fw_row_table() {
  local ts="${1:-}" client="${2:-}" dest="${3:-}" event="${4:-}" status="${5:-}"
  printf "  %-20s %-8s %-22s %-28s \033[1;31m%-14s\033[0m %s\n" \
    "$ts" "firewall" "$client" "$dest" "$event" "$status"
}

function ui::watch::wg_row_table() {
  local ts="${1:-}" client="${2:-}" endpoint="${3:-}" event="${4:-}" status="${5:-}"
  local event_color
  case "$event" in
    handshake) event_color="\033[1;32m" ;;
    attempt)   event_color="\033[1;31m" ;;
    *)         event_color="\033[0;37m" ;;
  esac
  printf "  %-20s %-8s %-22s %-28s %b%-14s\033[0m %s\n" \
    "$ts" "wireguard" "$client" "$endpoint" "$event_color" "$event" "$status"
}


# ui::_render_endpoint_col
# Builds padded endpoint string: "raw_ip → resolved" or "raw_ip" or "-"
# Args: endpoint resolved w_endpoint
# Returns: padded colored string via stdout
function ui::_render_endpoint_col() {
  local endpoint="${1:-}" resolved="${2:-}" w_endpoint="${3:-20}"
  local colored visible_len pad_n
 
  if [[ -n "$endpoint" ]]; then
    if [[ -n "$resolved" ]]; then
      colored="${endpoint} \033[2m→ ${resolved}\033[0m"
      visible_len=$(( ${#endpoint} + 3 + ${#resolved} ))
    else
      colored="$endpoint"
      visible_len=${#endpoint}
    fi
  else
    colored="\033[2m—\033[0m"
    visible_len=1
  fi
 
  pad_n=$(( w_endpoint - visible_len ))
  [[ $pad_n -lt 0 ]] && pad_n=0
  printf "%b%*s" "$colored" "$pad_n" ""
}
 
# ui::_render_dest_col
# Builds padded destination string: "svc/proto (ip:port)" or raw
# Args: dest_ip dest_port proto svc_name w_dest resolved_only
# Returns: two vars via nameref — dest_colored dest_pad_n
function ui::_build_dest() {
  local dest_ip="${1:-}" dest_port="${2:-}" proto="${3:-}" \
        svc_name="${4:-}" w_dest="${5:-20}" resolved_only="${6:-false}"
  local svc_display raw_suffix="" raw_plain=""
 
  if [[ -n "$svc_name" ]]; then
    [[ -n "$dest_port" ]] && svc_display="${svc_name}/${proto}" \
                          || svc_display="${svc_name} (${proto})"
    if ! $resolved_only; then
      [[ -n "$dest_port" ]] && raw_suffix=" \033[2m(${dest_ip}:${dest_port})\033[0m" \
                            || raw_suffix=" \033[2m(${dest_ip})\033[0m"
      [[ -n "$dest_port" ]] && raw_plain=" (${dest_ip}:${dest_port})" \
                            || raw_plain=" (${dest_ip})"
    fi
  else
    [[ -n "$dest_port" ]] && svc_display="${dest_ip}:${dest_port}/${proto}" \
                          || svc_display="${dest_ip} (${proto})"
  fi
 
  local full_len=$(( ${#svc_display} + ${#raw_plain} ))
  local dest_pad_n=$(( w_dest - full_len ))
  [[ $dest_pad_n -lt 0 ]] && dest_pad_n=0
 
  # Output: svc_display|raw_suffix|dest_pad_n
  printf "%s\t%s\t%s" "$svc_display" "$raw_suffix" "$dest_pad_n"
}
 
function ui::logs::fw_row() {
  local ts="${1:-}" client="${2:-}" dest_ip="${3:-}" dest_port="${4:-}" \
        proto="${5:-}" svc_name="${6:-}" count="${7:-1}" \
        w_client="${8:-20}" w_dest="${9:-30}" \
        src_endpoint="${10:-}" src_resolved="${11:-}" \
        w_endpoint="${12:-0}" resolved_only="${13:-false}"
 
  local ts_pad client_pad
  ts_pad=$(printf "%-11s" "$ts")
  client_pad=$(printf "%-${w_client}s" "$client")
 
  local count_suffix=""
  [[ "$count" -gt 1 ]] && count_suffix=" \033[2m(x${count})\033[0m"
 
  # Dest
  local dest_parts
  dest_parts=$(ui::_build_dest "$dest_ip" "$dest_port" "$proto" "$svc_name" "$w_dest" "$resolved_only")
  local svc_display raw_suffix dest_pad_n
  IFS=$'\t' read -r svc_display raw_suffix dest_pad_n <<< "$dest_parts"
 
  if [[ "$w_endpoint" -gt 0 ]]; then
    local src_padded
    src_padded=$(ui::_render_endpoint_col "$src_endpoint" "$src_resolved" "$w_endpoint")
    printf "  %s  %s  %b  \033[1;31m→\033[0m %s%b%*s%b\n" \
      "$ts_pad" "$client_pad" "$src_padded" \
      "$svc_display" "$raw_suffix" "$dest_pad_n" "" "$count_suffix"
  else
    printf "  %s  %s  \033[1;31m→\033[0m %s%b%*s%b\n" \
      "$ts_pad" "$client_pad" \
      "$svc_display" "$raw_suffix" "$dest_pad_n" "" "$count_suffix"
  fi
}
 
function ui::logs::wg_row() {
  local ts="${1:-}" client="${2:-}" endpoint="${3:-}" event="${4:-}" \
        count="${5:-1}" w_client="${6:-20}" w_endpoint="${7:-20}" \
        gap_seconds="${8:-}" resolved="${9:-}"
 
  local event_color
  case "$event" in
    handshake) event_color="\033[1;32m" ;;
    attempt)   event_color="\033[1;31m" ;;
    *)         event_color="\033[0;37m" ;;
  esac
 
  local count_suffix=""
  [[ "$count" -gt 1 ]] && count_suffix=" \033[2m(x${count})\033[0m"
 
  local gap_suffix=""
  if [[ "$event" == "handshake" && -n "$gap_seconds" && "$gap_seconds" -gt 0 ]]; then
    local gap_int="$gap_seconds"
    local threshold="${WG_HANDSHAKE_CHECK_TIME_SEC:-300}"
    local offline_label=""
    [[ "$gap_int" -gt $(( threshold * 2 )) ]] && offline_label=" offline"
    if (( gap_int >= 3600 )); then
      gap_suffix="  \033[2m↑ $(( gap_int / 3600 ))h${offline_label}\033[0m"
    elif (( gap_int >= 60 )); then
      gap_suffix="  \033[2m↑ $(( gap_int / 60 ))m${offline_label}\033[0m"
    fi
  fi
 
  local ep_padded
  ep_padded=$(ui::_render_endpoint_col "$endpoint" "$resolved" "$w_endpoint")
 
  local ts_pad client_pad
  ts_pad=$(printf "%-11s" "$ts")
  client_pad=$(printf "%-${w_client}s" "$client")
 
  printf "  %s  %s  %b  %b%s\033[0m%b%b\n" \
    "$ts_pad" "$client_pad" "$ep_padded" \
    "$event_color" "$event" "$count_suffix" "$gap_suffix"
}

function ui::watch::fw_row() {
  local ts="${1:-}" client="${2:-}" dest_ip="${3:-}" dest_port="${4:-}" \
        proto="${5:-}" svc_name="${6:-}" \
        src_endpoint="${7:-}" src_resolved="${8:-}" \
        w_client="${9:-20}" w_dest="${10:-18}" w_endpoint="${11:-0}"
 
  local ts_pad client_pad
  ts_pad=$(printf "%-11s" "$ts")
  client_pad=$(printf "%-${w_client}s" "$client")
 
  local dest_parts
  dest_parts=$(ui::_build_dest "$dest_ip" "$dest_port" "$proto" "$svc_name" "$w_dest" "false")
  local svc_display raw_suffix dest_pad_n
  IFS=$'\t' read -r svc_display raw_suffix dest_pad_n <<< "$dest_parts"
 
  if [[ "$w_endpoint" -gt 0 ]]; then
    local src_padded
    src_padded=$(ui::_render_endpoint_col "$src_endpoint" "$src_resolved" "$w_endpoint")
    printf "  %s  %s  %s  \033[1;31m→\033[0m %s%b%*s  \033[1;31mdrop\033[0m\n" \
      "$ts_pad" "$client_pad" "$src_padded" \
      "$svc_display" "$raw_suffix" "$dest_pad_n" ""
  else
    printf "  %s  %s  \033[1;31m→\033[0m %s%b%*s  \033[1;31mdrop\033[0m\n" \
      "$ts_pad" "$client_pad" \
      "$svc_display" "$raw_suffix" "$dest_pad_n" ""
  fi
}

 
function ui::watch::wg_row() {
  local ts="${1:-}" client="${2:-}" endpoint="${3:-}" event="${4:-}" \
        src_resolved="${5:-}" \
        w_client="${6:-20}" w_endpoint="${7:-18}"
 
  local event_color
  case "$event" in
    handshake) event_color="\033[1;32m" ;;
    attempt)   event_color="\033[1;31m" ;;
    *)         event_color="\033[0;37m" ;;
  esac
 
  local ep_padded
  ep_padded=$(ui::_render_endpoint_col "$endpoint" "$src_resolved" "$w_endpoint")
 
  local ts_pad client_pad
  ts_pad=$(printf "%-11s" "$ts")
  client_pad=$(printf "%-${w_client}s" "$client")
 
  # echo "DEBUG: ts='$ts_pad' client='$client_pad'(${#client_pad}) ep='$ep_padded'(${#ep_padded}) event='$event'" >&2

  printf "  %s  %s  %s  %b%s\033[0m\n" \
    "$ts_pad" "$client_pad" "$ep_padded" \
    "$event_color" "$event"
}
 