#!/bin/bash

## 🤓 http://crn.hopto.org  Enjoy and God bless! 

xtitle () 
{ 
    printf "\033]0;%s\007" "Timer: ${*}"
}


if [ -z "$1" ]; then
    echo -e "\e[1;31mError:\e[0m Usage: $0 <minutes>"
    echo "Example: $0 5"
    exit 1
fi

TOTAL_MIN="$(echo ${1} | sed -e 's/[[:alpha:]]//1')" 
TOTAL_SEC=$((TOTAL_MIN * 60))
START_SEC=$TOTAL_SEC

# ANSI Color Codes
GREEN="\e[1;32m"
YELLOW="\e[1;33m"
RED="\e[1;31m"
CYAN="\e[1;36m"
WHITE="\e[1;37m"
RESET="\e[0m"

tput civis
trap 'tput cnorm; echo; exit' EXIT SIGINT SIGTERM

echo -e "${CYAN}🍳 Starting your $TOTAL_MIN minute timer...${RESET}"
sleep 1

while [ $TOTAL_SEC -gt 0 ]; do
    PERCENT=$(( (START_SEC - TOTAL_SEC) * 100 / START_SEC ))
    BAR_WIDTH=$(( PERCENT / 4 ))
    
    PROGRESS_BAR=$(printf "%-${BAR_WIDTH}s" "#" | tr ' ' '#')
    EMPTY_BAR=$(printf "%-$((25 - BAR_WIDTH))s" "-")
    
    # Switch bar colors based on progress remaining
    if [ $PERCENT -lt 50 ]; then
        COLOR=$GREEN
    elif [ $PERCENT -lt 85 ]; then
        COLOR=$YELLOW
    else
        COLOR=$RED
    fi
    
    # Alternate ticking animation
    if [ $((TOTAL_SEC % 2)) -eq 0 ]; then
        EMOJI="🔅 "
    else
        EMOJI="🔆 "
    fi
    
    MIN=$((TOTAL_SEC / 60))
    SEC=$((TOTAL_SEC % 60))
    
    # Render colorized progress bar
    xtitle 
    printf "\r%s [${COLOR}%-25s${RESET}] ${WHITE}%02d:%02d${RESET} " "$EMOJI" "$PROGRESS_BAR$EMPTY_BAR" "$MIN" "$SEC"
    xtitle "$(printf "%02d:%02d" "$MIN" "$SEC")"
    sleep 1
    TOTAL_SEC=$((TOTAL_SEC - 1))
done

# Clear line and trigger the colored ending screen
printf "\r✨ [${RED}#########################${RESET}] 00:00 \n"
xtitle "Time is up!"
echo -e "${WHITE}🔔 Ding! Time is up!         🎉${RESET}"

# Audio alert ring
[[ -f /home/mitch/Music/sounds/system/alarm-clock-elapsed.oga ]] && canberra-gtk-play -f /home/mitch/Music/sounds/system/alarm-clock-elapsed.oga

