#!/usr/bin/env bash
set_fzf_theme() {
	local appearance="$1"
	# Detect the current system appearance (Light or Dark mode) for Linux and macOS
	if [ -z "$appearance" ]; then
		if [ "$(uname)" = "Darwin" ]; then
			# macOS
			appearance=$(defaults read -g AppleInterfaceStyle 2>/dev/null)
		elif [ "$(uname)" = "Linux" ]; then
			# Linux - try multiple desktop environments
			if command -v gsettings >/dev/null 2>&1; then
				# GNOME/GTK
				appearance=$(gsettings get org.gnome.desktop.interface gtk-theme 2>/dev/null)
			elif command -v kreadconfig5 >/dev/null 2>&1; then
				# KDE Plasma
				appearance=$(kreadconfig5 --file kdeglobals --group General --key ColorScheme 2>/dev/null)
			elif [ -f "$HOME/.config/xsettingsd/xsettingsd.conf" ]; then
				# Check xsettingsd for theme
				appearance=$(grep -i "theme" "$HOME/.config/xsettingsd/xsettingsd.conf" 2>/dev/null | head -1)
			fi
		fi
	fi
	
	# If still empty, check environment variables as fallback
	if [ -z "$appearance" ]; then
		if [ -n "$GTK_THEME" ]; then
			appearance="$GTK_THEME"
		elif [ -n "$QT_STYLE_OVERRIDE" ]; then
			appearance="$QT_STYLE_OVERRIDE"
		else
			# Default to Dark mode if the system is not recognized
			appearance="Dark"
		fi
	fi
	
	# Set FZF theme based on appearance
	if echo "$appearance" | grep -qi "dark" || [ -n "$TMUX" ]; then
		# High Contrast Dark Theme - Much more readable than original Monokai
		# Background: Dark gray (#1c1c1c) instead of Monokai green-tinted
		# Foreground: Light gray (#d0d0d0) for better readability
		# Selected line: Slightly lighter background (#262626) with bright white text (#ffffff)
		# Highlights: Bright cyan (#5fd7ff) stands out clearly
		FZF_DEFAULT_OPTS="--color=bg+:#262626,bg:#1c1c1c,spinner:#af5fff,hl:#5f87af,fg:#d0d0d0,header:#87afaf,info:#afaf87,pointer:#af5fff,marker:#87ff00,fg+:#ffffff,prompt:#d7005f,hl+:#5fd7ff,border:#585858,gutter:#1c1c1c"
	else
		# Solarized Light with better contrast for readability
		FZF_DEFAULT_OPTS="--color=bg+:#fdf6e3,bg:#fdf6e3,spinner:#d33682,hl:#cb4b16,fg:#586e75,header:#d33682,info:#268bd2,pointer:#859900,marker:#859900,fg+:#002b36,prompt:#eee8d5,hl+:#b58900"
	fi
	echo "$FZF_DEFAULT_OPTS"
}
# Call the function if executed directly
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
	set_fzf_theme "$1"
fi
