#!/usr/bin/env bash
set -Eeuo pipefail

PROFILE_VERSION="4"
MARKER="$HOME/.config/.celita-visual-v${PROFILE_VERSION}"
WALLPAPER_PNG="/usr/local/share/celita-visual/wallpapers/celita-fluent.png"
WALLPAPER_SVG="/usr/local/share/celita-visual/wallpapers/celita-fluent.svg"

if [[ "${XDG_CURRENT_DESKTOP:-}" != *XFCE* && "${DESKTOP_SESSION:-}" != *xfce* ]]; then
    exit 0
fi

if [[ -f "$MARKER" ]]; then
    exit 0
fi

for _attempt in {1..30}; do
    if xfconf-query -c xsettings -p /Net/ThemeName >/dev/null 2>&1; then
        break
    fi
    sleep 1
done

mkdir -p \
    "$HOME/.config" \
    "$HOME/.config/gtk-3.0" \
    "$HOME/.config/xfce4/panel" \
    "$HOME/.config/Thunar" \
    "$HOME/.local/share/applications"

xdg-user-dirs-update >/dev/null 2>&1 || true

xfset() {
    local channel="$1" property="$2" type="$3" value="$4"
    if xfconf-query -c "$channel" -p "$property" >/dev/null 2>&1; then
        xfconf-query -c "$channel" -p "$property" -s "$value" >/dev/null 2>&1 || true
    else
        xfconf-query -c "$channel" -n -p "$property" -t "$type" -s "$value" >/dev/null 2>&1 || true
    fi
}

xfarray_int() {
    local channel="$1" property="$2"
    shift 2
    xfconf-query -c "$channel" -p "$property" -r -R >/dev/null 2>&1 || true
    local args=() value
    for value in "$@"; do
        args+=( -t int -s "$value" )
    done
    xfconf-query -c "$channel" -n -a -p "$property" "${args[@]}" >/dev/null 2>&1 || true
}

xfarray_string() {
    local channel="$1" property="$2"
    shift 2
    xfconf-query -c "$channel" -p "$property" -r -R >/dev/null 2>&1 || true
    local args=() value
    for value in "$@"; do
        args+=( -t string -s "$value" )
    done
    [[ ${#args[@]} -gt 0 ]] && \
        xfconf-query -c "$channel" -n -a -p "$property" "${args[@]}" >/dev/null 2>&1 || true
}

set_command_shortcut() {
    local shortcut="$1" command="$2"
    local property="/commands/custom/$shortcut"
    if xfconf-query -c xfce4-keyboard-shortcuts -p "$property" >/dev/null 2>&1; then
        xfconf-query -c xfce4-keyboard-shortcuts -p "$property" -s "$command" >/dev/null 2>&1 || true
    else
        xfconf-query -c xfce4-keyboard-shortcuts -n -p "$property" -t string -s "$command" >/dev/null 2>&1 || true
    fi
}

set_wm_shortcut() {
    local shortcut="$1" action="$2"
    local property="/xfwm4/custom/$shortcut"
    if xfconf-query -c xfce4-keyboard-shortcuts -p "$property" >/dev/null 2>&1; then
        xfconf-query -c xfce4-keyboard-shortcuts -p "$property" -s "$action" >/dev/null 2>&1 || true
    else
        xfconf-query -c xfce4-keyboard-shortcuts -n -p "$property" -t string -s "$action" >/dev/null 2>&1 || true
    fi
}

GTK_THEME="Fluent-Light-compact"
[[ -d "/usr/share/themes/$GTK_THEME" ]] || GTK_THEME="Adwaita"

xfset xsettings /Net/ThemeName string "$GTK_THEME"
xfset xsettings /Net/IconThemeName string "Papirus"
xfset xsettings /Gtk/FontName string "Inter 10"
xfset xsettings /Gtk/MonospaceFontName string "Monospace 10"
xfset xsettings /Gtk/ToolbarStyle string "icons"
xfset xsettings /Gtk/CursorThemeName string "Adwaita"
xfset xsettings /Gtk/CursorThemeSize int 24

cat > "$HOME/.config/gtk-3.0/settings.ini" <<EOF
[Settings]
gtk-theme-name=$GTK_THEME
gtk-icon-theme-name=Papirus
gtk-cursor-theme-name=Adwaita
gtk-cursor-theme-size=24
gtk-font-name=Inter 10
gtk-application-prefer-dark-theme=false
gtk-decoration-layout=menu:minimize,maximize,close
EOF

xfset xfwm4 /general/theme string "$GTK_THEME"
xfset xfwm4 /general/button_layout string "|HMC"
xfset xfwm4 /general/title_alignment string "left"
xfset xfwm4 /general/active_opacity uint 100
xfset xfwm4 /general/inactive_opacity uint 100
xfset xfwm4 /general/move_opacity uint 100
xfset xfwm4 /general/resize_opacity uint 100
xfset xfwm4 /general/use_compositing bool true
xfset xfwm4 /general/show_dock_shadow bool false
xfset xfwm4 /general/workspace_count uint 1
xfset xfwm4 /general/placement_mode string "center"

WALLPAPER="$WALLPAPER_PNG"
[[ -f "$WALLPAPER" ]] || WALLPAPER="$WALLPAPER_SVG"
if [[ -f "$WALLPAPER" ]]; then
    while IFS= read -r property; do
        [[ -n "$property" ]] || continue
        xfconf-query -c xfce4-desktop -p "$property" -s "$WALLPAPER" >/dev/null 2>&1 || true
    done < <(xfconf-query -c xfce4-desktop -l 2>/dev/null | grep '/last-image$' || true)
    while IFS= read -r property; do
        [[ -n "$property" ]] || continue
        xfconf-query -c xfce4-desktop -p "$property" -s 5 >/dev/null 2>&1 || true
    done < <(xfconf-query -c xfce4-desktop -l 2>/dev/null | grep '/image-style$' || true)
fi

xfset xfce4-desktop /desktop-icons/style uint 2
xfset xfce4-desktop /desktop-icons/file-icons/show-home bool false
xfset xfce4-desktop /desktop-icons/file-icons/show-filesystem bool false
xfset xfce4-desktop /desktop-icons/file-icons/show-removable bool false
xfset xfce4-desktop /desktop-icons/file-icons/show-trash bool true
xfset xfce4-desktop /desktop-icons/icon-size uint 48

xfset thunar /last-view string "ThunarIconView"
xfset thunar /last-icon-view-zoom-level string "THUNAR_ZOOM_LEVEL_NORMAL"
xfset thunar /misc-open-new-windows-in-split-view bool false
xfset thunar /misc-show-delete-action bool false
xfset thunar /misc-thumbnail-mode string "THUNAR_THUMBNAIL_MODE_ONLY_LOCAL"

xdg-mime default celita-explorer.desktop inode/directory >/dev/null 2>&1 || true
xdg-mime default celita-deb-installer.desktop application/vnd.debian.binary-package >/dev/null 2>&1 || true

DESKTOP_DIR="$(xdg-user-dir DESKTOP 2>/dev/null || true)"
if [[ -n "$DESKTOP_DIR" && -f "$DESKTOP_DIR/celita-arquivos.desktop" ]]; then
    install -m 0755 /usr/local/share/applications/celita-arquivos.desktop \
        "$DESKTOP_DIR/celita-arquivos.desktop"
fi

set_command_shortcut "<Primary>Escape" "/usr/local/bin/celita-start-menu"
set_command_shortcut "<Super>space" "/usr/local/bin/celita-start-menu"
set_command_shortcut "<Super>e" "/usr/local/bin/celita-explorer"
set_command_shortcut "<Super>r" "xfce4-appfinder --collapsed"
set_command_shortcut "<Primary><Shift>Escape" "xfce4-taskmanager"
set_command_shortcut "Print" "xfce4-screenshooter -f"
set_wm_shortcut "<Super>Left" "tile_left_key"
set_wm_shortcut "<Super>Right" "tile_right_key"
set_wm_shortcut "<Super>Up" "maximize_window_key"
set_wm_shortcut "<Super>Down" "hide_window_key"

xfconf-query -c xfce4-panel -p /plugins -r -R >/dev/null 2>&1 || true
xfconf-query -c xfce4-panel -p /panels -r -R >/dev/null 2>&1 || true

xfset xfce4-panel /configver int 2
xfarray_int xfce4-panel /panels 1
xfset xfce4-panel /panels/panel-1/position string "p=8;x=0;y=0"
xfset xfce4-panel /panels/panel-1/position-locked bool true
xfset xfce4-panel /panels/panel-1/length uint 100
xfset xfce4-panel /panels/panel-1/length-adjust bool false
xfset xfce4-panel /panels/panel-1/size uint 48
xfset xfce4-panel /panels/panel-1/icon-size uint 27
xfset xfce4-panel /panels/panel-1/nrows uint 1
xfset xfce4-panel /panels/panel-1/mode uint 0
xfset xfce4-panel /panels/panel-1/autohide-behavior uint 0
xfset xfce4-panel /panels/panel-1/background-style uint 0
xfset xfce4-panel /panels/panel-1/enter-opacity uint 100
xfset xfce4-panel /panels/panel-1/leave-opacity uint 100
xfset xfce4-panel /panels/panel-1/span-monitors bool false

xfarray_int xfce4-panel /panels/panel-1/plugin-ids 1 2 3 4 5 6 7 8 9 10

xfset xfce4-panel /plugins/plugin-1 string "launcher"
mkdir -p "$HOME/.config/xfce4/panel/launcher-1"
install -m 0644 /usr/local/share/applications/celita-start-menu.desktop \
    "$HOME/.config/xfce4/panel/launcher-1/celita-start-menu.desktop"
sed -i '/^NoDisplay=/d' \
    "$HOME/.config/xfce4/panel/launcher-1/celita-start-menu.desktop"
xfarray_string xfce4-panel /plugins/plugin-1/items "celita-start-menu.desktop"
xfset xfce4-panel /plugins/plugin-1/disable-tooltips bool true

xfset xfce4-panel /plugins/plugin-2 string "separator"
xfset xfce4-panel /plugins/plugin-2/expand bool false
xfset xfce4-panel /plugins/plugin-2/style uint 0

xfset xfce4-panel /plugins/plugin-3 string "docklike"

xfset xfce4-panel /plugins/plugin-4 string "separator"
xfset xfce4-panel /plugins/plugin-4/expand bool true
xfset xfce4-panel /plugins/plugin-4/style uint 0

xfset xfce4-panel /plugins/plugin-5 string "systray"
xfset xfce4-panel /plugins/plugin-5/show-frame bool false
xfset xfce4-panel /plugins/plugin-5/square-icons bool true
xfset xfce4-panel /plugins/plugin-5/symbolic-icons bool true
xfset xfce4-panel /plugins/plugin-5/icon-size int 16
xfset xfce4-panel /plugins/plugin-5/single-row bool true

xfset xfce4-panel /plugins/plugin-6 string "notification-plugin"
xfset xfce4-panel /plugins/plugin-7 string "pulseaudio"
xfset xfce4-panel /plugins/plugin-7/enable-keyboard-shortcuts bool true
xfset xfce4-panel /plugins/plugin-7/mixer-command string "pavucontrol"
xfset xfce4-panel /plugins/plugin-8 string "power-manager-plugin"
xfset xfce4-panel /plugins/plugin-9 string "clock"
xfset xfce4-panel /plugins/plugin-9/mode uint 2
xfset xfce4-panel /plugins/plugin-9/digital-format string "%H:%M%n%d/%m/%Y"
xfset xfce4-panel /plugins/plugin-9/tooltip-format string "%A, %d de %B de %Y"
xfset xfce4-panel /plugins/plugin-10 string "showdesktop"

cat > "$HOME/.config/xfce4/panel/docklike-3.rc" <<'EOF'
[user]
pinned=celita-explorer;brave-browser;libreoffice-writer;libreoffice-calc;libreoffice-impress;
forceIconSize=true
iconSize=28
showPreviews=true
showWindowCount=true
noWindowsListIfSingle=false
onlyDisplayVisible=false
onlyDisplayScreen=false
indicatorOrientation=0
indicatorStyle=0
inactiveIndicatorStyle=0
indicatorColorFromTheme=true
middleButtonBehavior=0
keyComboActive=false
keyAloneActive=false
dockSize=380
previewScale=0.125
previewSleep=300
EOF

GTK_CSS="$HOME/.config/gtk-3.0/gtk.css"
python3 - "$GTK_CSS" <<'PY'
from pathlib import Path
import sys

path = Path(sys.argv[1])
text = path.read_text(encoding="utf-8") if path.exists() else ""
begin = "/* BEGIN CELITA VISUAL PANEL */"
end = "/* END CELITA VISUAL PANEL */"
if begin in text and end in text:
    before, rest = text.split(begin, 1)
    _, after = rest.split(end, 1)
    text = before.rstrip() + "\n" + after.lstrip("\n")
block = r'''
/* BEGIN CELITA VISUAL PANEL */
.xfce4-panel {
    background-color: rgba(248, 249, 252, 0.96);
    border-top: 1px solid rgba(205, 210, 218, 0.82);
    box-shadow: 0 -3px 15px rgba(35, 45, 60, 0.10);
}
.xfce4-panel button,
.xfce4-panel #xfce-panel-toggle-button {
    min-width: 40px;
    min-height: 40px;
    margin: 3px 1px;
    padding: 0 5px;
    border: 0;
    border-radius: 6px;
    background-image: none;
    background-color: transparent;
    box-shadow: none;
}
.xfce4-panel button:hover,
.xfce4-panel #xfce-panel-toggle-button:hover {
    background-color: rgba(90, 105, 125, 0.11);
}
#docklike-plugin button {
    min-width: 42px;
    padding: 0 5px;
}
#docklike-plugin button:checked {
    background-color: rgba(74, 139, 192, 0.14);
}
#docklike-plugin .group { border-radius: 6px; }
#systray, #xfce4-notification-plugin,
#pulseaudio-button, #power-manager-plugin {
    padding: 0 3px;
    border-radius: 6px;
}
#clock {
    padding: 0 9px;
    border-radius: 6px;
    font-size: 0.84em;
}
#showdesktop button { min-width: 6px; padding: 0; margin-left: 2px; }
/* END CELITA VISUAL PANEL */
'''
path.write_text(text.rstrip() + "\n\n" + block.strip() + "\n", encoding="utf-8")
PY

xfce4-panel -r >/dev/null 2>&1 || true
mkdir -p "$(dirname "$MARKER")"
touch "$MARKER"
