#!/bin/bash
# Step 08: Dark theme (GTK3 settings, GTK CSS, taskbar theme)

step_08_dark_theme() {
  local theme_name="$GTK_THEME_NAME"
  [[ ! -d "/usr/share/themes/$theme_name" ]] && [[ -d /usr/share/themes/Adwaita-dark ]] \
    && theme_name="Adwaita-dark" && log "Using Adwaita-dark (PiXnoir not found)"

  local icon_theme=""
  [[ -d /usr/share/icons/PiXtrix ]] && icon_theme="PiXtrix"

  # GTK3 settings
  local gtk_ini="$PI_HOME/.config/gtk-3.0/settings.ini"
  mkdir -p "$(dirname "$gtk_ini")"
  if [[ ! -f "$gtk_ini" ]]; then
    { printf '%s\n' '[Settings]' 'gtk-application-prefer-dark-theme=1' "gtk-theme-name=$theme_name"
      [[ -n "$icon_theme" ]] && echo "gtk-icon-theme-name=$icon_theme"
    } > "$gtk_ini"
  else
    _set_ini() { grep -q "^$1=" "$gtk_ini" && sed -i "s/^$1=.*/$1=$2/" "$gtk_ini" || echo "$1=$2" >> "$gtk_ini"; }
    _set_ini gtk-application-prefer-dark-theme 1
    _set_ini gtk-theme-name "$theme_name"
    [[ -n "$icon_theme" ]] && _set_ini gtk-icon-theme-name "$icon_theme"
  fi
  log "GTK theme: $theme_name" && [[ -n "$icon_theme" ]] && log "Icon theme: $icon_theme"

  # GTK4/Libadwaita dark preference
  if [[ -f "$PI_HOME/.profile" ]] && ! grep -q 'ADW_DEBUG_COLOR_SCHEME' "$PI_HOME/.profile" 2>/dev/null; then
    printf '\n%s\n' 'export ADW_DEBUG_COLOR_SCHEME=prefer-dark' >> "$PI_HOME/.profile"
    chown "$PI_USER:$PI_USER" "$PI_HOME/.profile"
    log "Added prefer-dark to .profile"
  fi

  # Custom GTK CSS (dark menus/popovers)
  curl -fsSL "${FILE_SERVER}/gtk.css" -o "$PI_HOME/.config/gtk-3.0/gtk.css" 2>/dev/null \
    && log "gtk.css installed" || true

  # Taskbar theme
  local panel_dir="$PI_HOME/.config/wf-panel-pi"
  mkdir -p "$panel_dir"
  if curl -fsSL "${FILE_SERVER}/wf-panel-pi.ini" -o "$panel_dir/wf-panel-pi.ini" 2>/dev/null; then
    sed -i "s|/home/pi|$PI_HOME|g" "$panel_dir/wf-panel-pi.ini"
    curl -fsSL "${FILE_SERVER}/panel-theme.css" -o "$panel_dir/panel-theme.css" 2>/dev/null || true
    log "Taskbar theme installed"
  fi

  chown -R "$PI_USER:$PI_USER" "$PI_HOME/.config"
}
