#!/usr/bin/env bash
# modules/display.module.sh
# Display configuration — controls layout style per view

# ============================================
# State — loaded once on first access
# ============================================

_DISPLAY_LOADED=false
declare -gA _DISPLAY_STYLES=()

# ============================================
# Load display config
# ============================================

function display::_load() {
  $_DISPLAY_LOADED && return 0
  _DISPLAY_LOADED=true

  local display_file
  display_file="$(ctx::display)"
  [[ ! -f "$display_file" ]] && return 0

  # Load styles per view via json_helper
  local view style
  while IFS='=' read -r view style; do
    [[ -n "$view" && -n "$style" ]] && _DISPLAY_STYLES["$view"]="$style"
  done < <(python3 "$(ctx::json_helper)" display_load "$display_file" 2>/dev/null)
}

# ============================================
# Accessors
# ============================================

# display::style <view>
# Returns: compact | table | minimal (default: compact)
function display::style() {
  local view="${1:-}"
  display::_load
  echo "${_DISPLAY_STYLES[$view]:-compact}"
}

# display::is_compact <view>
function display::is_compact() {
  [[ "$(display::style "$1")" == "compact" ]]
}

# display::is_table <view>
function display::is_table() {
  [[ "$(display::style "$1")" == "table" ]]
}

# ============================================
# display::render <view> <data> <compact_fn> <table_fn> [extra_args...]
# Generic dispatcher — calls compact or table render function
# ============================================

function display::render() {
  local view="${1:-}" data="${2:-}" compact_fn="${3:-}" table_fn="${4:-}"
  shift 4 || true

  case "$(display::style "$view")" in
    table)
      declare -f "$table_fn" >/dev/null 2>&1 && \
        "$table_fn" "$data" "$@" || \
        "$compact_fn" "$data" "$@"  # fallback to compact if no table fn
      ;;
    *)
      "$compact_fn" "$data" "$@"
      ;;
  esac
}