#!/usr/bin/env bash

TUI_FS_ACTIVE=0
TUI_FS_ROWS=0
TUI_FS_COLS=0
TUI_FS_OVERALL_CURRENT=0
TUI_FS_OVERALL_TOTAL=0
TUI_FS_MODULE_LABEL=""
TUI_FS_SAVED_STTY=""

tui_fs_init() {
  ((OMERON_HAS_GUM)) || return 1

  TUI_FS_SAVED_STTY=$(stty -g 2>/dev/null || true)
  TUI_FS_ROWS=$(tput lines 2>/dev/null || echo 24)
  TUI_FS_COLS=$(tput cols 2>/dev/null || echo 80)

  tput smcup 2>/dev/null || true
  tput civis 2>/dev/null || true
  tput clear 2>/dev/null || true

  TUI_FS_ACTIVE=1
}

tui_fs_exit() {
  [[ "$TUI_FS_ACTIVE" -eq 0 ]] && return
  TUI_FS_ACTIVE=0
  tput cnorm 2>/dev/null || true
  tput rmcup 2>/dev/null || true
  [[ -n "$TUI_FS_SAVED_STTY" ]] && stty "$TUI_FS_SAVED_STTY" 2>/dev/null || true
}

tui_fs_set_overall() {
  TUI_FS_OVERALL_CURRENT=$1
  TUI_FS_OVERALL_TOTAL=$2
  TUI_FS_MODULE_LABEL="${3:-}"
  _tui_fs_draw_screen
}

_tui_fs_draw_screen() {
  [[ "$TUI_FS_ACTIVE" -eq 0 ]] && return
  tput cup 0 0 2>/dev/null || true

  local cols=$TUI_FS_COLS
  local cols_safe=$((cols > 60 ? cols : 60))

  printf "\033[7m  %-*s\033[0m\n" $((cols_safe - 2)) " Omeron — Modular System Setup"

  if [[ -n "$TUI_FS_MODULE_LABEL" ]]; then
    printf "  Module: %-*s" $((cols_safe - 18)) "$TUI_FS_MODULE_LABEL"
    if ((TUI_FS_OVERALL_TOTAL > 0)); then
      printf "  [%d/%d]" "$TUI_FS_OVERALL_CURRENT" "$TUI_FS_OVERALL_TOTAL"
    fi
    printf "\n"
  else
    printf "\n"
  fi

  local bar_width=$((cols_safe - 16))
  ((bar_width < 10)) && bar_width=10

  local progress=0
  if ((TUI_FS_OVERALL_TOTAL > 0)); then
    progress=$(( TUI_FS_OVERALL_CURRENT * 100 / TUI_FS_OVERALL_TOTAL ))
    ((progress > 100)) && progress=100
  fi

  printf "  "
  local filled=$(( progress * bar_width / 100 ))
  local i
  for ((i=0; i<filled && i<bar_width; i++)); do printf '▓'; done
  for ((i=filled; i<bar_width; i++)); do printf '░'; done
  printf " %3d%%\n" "$progress"

  printf "  "
  printf '%*s' $((cols_safe - 3)) '' | tr ' ' '─'
  printf "\n"
}
