#!/bin/bash

# unparty_styles.sh - THEUNPARTYRUNWAY BUILT-IN STYLING LIBRARY
# Source this file to get consistent branding, colors, and utility functions
# Usage: source scripts/unparty_styles.sh
#
# Version: 31.1.0
# Last Updated: 2026-08-09
# Repository: https://github.com/theunpartyrunway/theunpartyrunway
# License: MIT

# Prevent multiple sourcing *within a single shell process*. Deliberately not
# exported: functions defined below never inherit across a `bash child.sh` /
# `./child.sh` process boundary, but an exported guard variable would — so a
# child process that re-sources this file to get its own copy of these
# functions would see the guard already "on" and return before defining any
# of them, breaking every unparty_* call in that child with no visible error.
if [ -n "${UNPARTY_STYLES_LOADED:-}" ]; then
    return 0
fi
UNPARTY_STYLES_LOADED=1

# =============================================================================
# UNPARTY COLOR PALETTE
# =============================================================================

# Basic colors
export RED='\033[0;31m'
export GREEN='\033[0;32m'
export YELLOW='\033[1;33m'
export BLUE='\033[0;34m'
export PURPLE='\033[0;35m'
export CYAN='\033[0;36m'
export WHITE='\033[1;37m'
export NC='\033[0m'

# Bright variants (better for CI/accessibility)
export BRIGHT_RED='\033[1;31m'
export BRIGHT_GREEN='\033[1;32m'
export BRIGHT_YELLOW='\033[1;33m'
export BRIGHT_BLUE='\033[1;34m'
export BRIGHT_PURPLE='\033[1;35m'
export BRIGHT_CYAN='\033[1;36m'
export BRIGHT_WHITE='\033[1;37m'

# Unparty brand colors
export BRAND_COLOR='\033[38;2;249;194;46m'    # #f9c22e (official unparty yellow)
export BRAND_LIGHT='\033[38;2;252;207;77m'    # Lighter variant
export BRAND_DARK='\033[38;2;204;159;38m'     # Darker variant

# Style modifiers
export BOLD='\033[1m'
export DIM='\033[2m'
export UNDERLINE='\033[4m'
export REVERSE='\033[7m'

# Background colors
export BG_RED='\033[41m'
export BG_GREEN='\033[42m'
export BG_YELLOW='\033[43m'
export BG_BLUE='\033[44m'
export BG_PURPLE='\033[45m'
export BG_CYAN='\033[46m'
export BG_WHITE='\033[47m'

# Custom RGB colors
export DARK_THEME_BG='\033[48;2;10;10;10m'      # #0a0a0a
export DARK_THEME_FG='\033[38;2;237;237;237m'   # #ededed
export ACCENT_ORANGE='\033[38;2;255;165;0m'     # #ffa500
export ACCENT_PINK='\033[38;2;255;20;147m'      # #ff1493

# =============================================================================
# UNPARTY BRANDING FUNCTIONS
# =============================================================================

# Main unparty logo with timing
show_unparty_logo() {
    local timing="${1:-0.1}"  # Default 0.1s, can be customized
    
    echo -e "${BRAND_COLOR}"
    echo "██╗   ██╗███╗   ██╗██████╗  █████╗ ██████╗ ████████╗██╗   ██╗"
    sleep "$timing"
    echo "██║   ██║████╗  ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝╚██╗ ██╔╝"
    sleep "$timing"
    echo "██║   ██║██╔██╗ ██║██████╔╝███████║██████╔╝   ██║    ╚████╔╝ "
    sleep "$timing"
    echo "██║   ██║██║╚██╗██║██╔═══╝ ██╔══██║██╔══██╗   ██║     ╚██╔╝  "
    sleep "$timing"
    echo "╚██████╔╝██║ ╚████║██║     ██║  ██║██║  ██║   ██║      ██║   "
    sleep "$timing"
    echo " ╚═════╝ ╚═╝  ╚═══╝╚═╝     ╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝      ╚═╝   "
    echo -e "${NC}"
}

# Compact logo variations
show_unparty_compact() {
    echo -e "${BRAND_COLOR}[ UNPARTY ]${NC}"
}

show_unparty_minimal() {
    echo -e "${BRAND_COLOR}unparty${NC}"
}

# Official taglines
show_unparty_tagline() {
    echo -e "${WHITE}YOU BUILD. AI HALLUCINATES. INNOVATE THE DIFFERENCE.${NC}"
}

show_unparty_house() {
    echo -e "${CYAN}THIS IS YOUR HOUSE${NC}"
}

show_unparty_execution() {
    echo -e "${BRAND_COLOR}WHERE INNOVATION MEETS EXECUTION${NC}"
}

# Complete header with logo and tagline
show_unparty_header() {
    local title="$1"
    local subtitle="$2"
    local timing="${3:-0.1}"
    
    show_unparty_logo "$timing"
    sleep 0.2
    
    if [ -n "$title" ]; then
        echo -e "${WHITE}${title}${NC}"
        sleep 0.1
    fi
    
    if [ -n "$subtitle" ]; then
        echo -e "${CYAN}${subtitle}${NC}"
        sleep 0.1
    else
        show_unparty_tagline
        sleep 0.1
        show_unparty_house
    fi
    
    echo ""
}

# =============================================================================
# UTILITY FUNCTIONS
# =============================================================================

# Safe color wrapper
unparty_colorize() {
    local color="$1"
    local text="$2"
    echo -e "${color}${text}${NC}"
}

# Status message functions
unparty_success() {
    echo -e "${GREEN}🪩${NC} ${WHITE}$1${NC}"
}

unparty_date() {
    echo -e "${BLUE}📅${NC} ${BRIGHT_PURPLE}$1${NC}"
}

unparty_error() {
    echo -e "${RED}❌${NC} ${WHITE}$1${NC}"
}

unparty_warning() {
    echo -e "${YELLOW}👾${NC} ${ACCENT_ORANGE}$1${NC}"
}

unparty_info() {
    echo -e "${BLUE}📌${NC} ${WHITE}$1${NC}"
}

unparty_action() {
    echo -e "${BRAND_COLOR}🚀${NC} ${WHITE}$1${NC}"
}

# Section headers
unparty_section() {
    local title="$1"
    echo ""
    echo -e "${BRAND_COLOR}═══${NC} ${BOLD}${WHITE}${title}${NC} ${BRAND_COLOR}═══${NC}"
    echo ""
}

unparty_subsection() {
    local title="$1"
    echo -e "${WHITE}## ${title}${NC}"
}

# Data display
unparty_key_value() {
    local key="$1"
    local value="$2"
    local indent="${3:-0}"
    
    local spaces=""
    for ((i=0; i<indent*2; i++)); do spaces+=" "; done
    
    echo -e "${spaces}${CYAN}${key}:${NC} ${WHITE}${value}${NC}"
}

unparty_list_item() {
    local text="$1"
    local indent="${2:-0}"
    local bullet="${3:-•}"
    
    local spaces=""
    for ((i=0; i<indent*2; i++)); do spaces+=" "; done
    
    echo -e "${spaces}${PURPLE}${bullet}${NC} ${WHITE}${text}${NC}"
}

unparty_brand_item() {
    local text="$1"
    local indent="${2:-0}"

    local spaces=""
    for ((i=0; i<indent*2; i++)); do spaces+=" "; done

    echo -e "${spaces}${BRAND_COLOR}▶${NC} ${WHITE}${text}${NC}"
}

# Table display — fixed-width columns with color, ANSI-safe padding
# Padding is applied before colorizing so ANSI bytes don't skew column widths.
unparty_table_header() {
    # Args: col1_label col1_width col2_label col2_width ...
    local output=""
    local total_width=0
    while [[ $# -ge 2 ]]; do
        local label="$1" width="$2"
        shift 2
        local padded
        padded=$(printf "%-${width}s" "$label")
        output+="${BOLD}${BRAND_COLOR}${padded}${NC}  "
        total_width=$(( total_width + width + 2 ))
    done
    echo -e "$output"
    local divider
    divider=$(printf '─%.0s' $(seq 1 $total_width))
    echo -e "${BRAND_COLOR}${divider}${NC}"
}

unparty_table_row() {
    # Args: rank name score activity hrs days_ago stars
    local rank="$1" name="$2" score="$3" activity="$4" hrs="$5" days_ago="$6" stars="$7"
    local r n s a h d st
    r=$(printf "%-4s"  "$rank")
    n=$(printf "%-26s" "$name")
    s=$(printf "%-9s"  "$score")
    a=$(printf "%-10s" "$activity")
    h=$(printf "%-8s"  "$hrs")
    d=$(printf "%-10s" "$days_ago")
    st=$(printf "%-6s" "$stars")
    echo -e "${CYAN}${r}${NC}${WHITE}${n}${NC}${BRAND_COLOR}${s}${NC}${PURPLE}${a}${NC}${GREEN}${h}${NC}${YELLOW}${d}${NC}${BLUE}${st}${NC}"
}

# =============================================================================
# ANIMATION FUNCTIONS
# =============================================================================

# Loading dots with customizable timing
unparty_loading() {
    local message="$1"
    local duration="${2:-1.0}"
    local dot_count="${3:-3}"
    
    echo -ne "${YELLOW}${message}${NC}"
    
    local dot_delay=$(echo "$duration / $dot_count" | bc -l 2>/dev/null || echo "0.33")
    
    for ((i=1; i<=dot_count; i++)); do
        echo -n "."
        sleep "$dot_delay"
    done
    echo -e " ${GREEN}✓${NC}"
}

# Progressive loading with steps
unparty_progressive_loading() {
    local message="$1"
    shift
    local steps=("$@")
    
    echo -e "${YELLOW}${message}${NC}"
    
    for step in "${steps[@]}"; do
        echo -ne "  ${CYAN}• ${step}${NC}"
        
        # Random delay between 0.2-0.8 seconds for natural feel
        local delay=$(echo "scale=1; ($(od -An -N2 -i /dev/urandom | tr -d ' ') % 7 + 2) / 10" | bc -l 2>/dev/null || echo "0.4")
        sleep "$delay"
        
        echo -e " ${GREEN}✓${NC}"
    done
    echo ""
}

# Spinner animation
unparty_spinner() {
    local duration="$1"
    local message="$2"
    local spinners="⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
    local delay=0.1
    
    # Use floating point math for duration
    local iterations=$(echo "$duration / $delay" | bc -l 2>/dev/null || echo "$(( ${duration%.*} * 10 ))")
    local count=0
    
    while [ "$count" -lt "${iterations%.*}" ]; do
        for (( i=0; i<${#spinners}; i++ )); do
            printf "\r${CYAN}${spinners:$i:1} ${message}${NC}"
            sleep "$delay"
            count=$((count + 1))
            [ "$count" -ge "${iterations%.*}" ] && break
        done
    done
    printf "\r${GREEN}✓ ${message} - Complete!${NC}\n"
}

# Simple spinner sleep (just timing, no message)
unparty_spinner_sleep() {
    local duration="$1"
    unparty_spinner "$duration" "thinking..."
}

# Typewriter effect
unparty_typewriter() {
    local text="$1"
    local delay="${2:-0.05}"
    local color="${3:-$BRAND_COLOR}"
    
    echo -ne "${color}"
    for (( i=0; i<${#text}; i++ )); do
        echo -n "${text:$i:1}"
        sleep "$delay"
    done
    echo -e "${NC}"
}

# =============================================================================
# LAYOUT FUNCTIONS
# =============================================================================

# Dividers
unparty_divider() {
    echo -e "${BRAND_COLOR}============================================================${NC}"
}

unparty_light_divider() {
    echo -e "${CYAN}────────────────────────────────────────────────────────────${NC}"
}

unparty_section_divider() {
    local title="$1"
    echo -e "${BRAND_COLOR}═══${NC} ${WHITE}${title}${NC} ${BRAND_COLOR}═══${NC}"
}

# Boxes
unparty_box() {
    local content="$1"
    echo -e "${CYAN}┌─────────────────────┐${NC}"
    echo -e "${CYAN}│${NC} ${WHITE}${content}${NC} ${CYAN}│${NC}"
    echo -e "${CYAN}└─────────────────────┘${NC}"
}

unparty_brand_box() {
    local content="$1"
    echo -e "${BRAND_COLOR}╔═══════════════════════╗${NC}"
    echo -e "${BRAND_COLOR}║${NC} ${WHITE}${content}${NC} ${BRAND_COLOR}║${NC}"
    echo -e "${BRAND_COLOR}╚═══════════════════════╝${NC}"
}

# =============================================================================
# INTERACTION FUNCTIONS
# =============================================================================

# Branded prompt
unparty_prompt() {
    local message="$1"
    local variable_name="${2:-}"
    
    if [[ -n "$variable_name" ]]; then
        read -p "$(echo -e "${BRAND_COLOR}${message}: ${NC}")" "$variable_name"
    else
        echo -ne "${BRAND_COLOR}${message}: ${NC}"
    fi
}

# Confirmation prompt
unparty_confirm() {
    local message="$1"
    read -p "$(echo -e "${YELLOW}${message} (y/n): ${NC}")" -n 1 -r
    echo ""
    [[ $REPLY =~ ^[Yy]$ ]]
}

# Menu option
unparty_menu_option() {
    local key="$1"
    local description="$2"
    local color="${3:-$CYAN}"
    
    echo -e "${color}[${key}]${NC} ${WHITE}${description}${NC}"
}

# Pause for user
unparty_pause() {
    local message="${1:-Press Enter to continue...}"
    echo -e "${DIM}${WHITE}${message}${NC}"
    read -r
}

# =============================================================================
# ENVIRONMENT DETECTION
# =============================================================================

# Check if terminal supports colors
supports_color() {
    [[ -t 1 ]] && [[ "${TERM}" != "dumb" ]] && [[ -n "${TERM}" ]]
}

# Get terminal dimensions
get_terminal_width() {
    tput cols 2>/dev/null || echo "80"
}

get_terminal_height() {
    tput lines 2>/dev/null || echo "24"
}

# Check platform
is_macos() {
    [[ "$OSTYPE" == "darwin"* ]]
}

is_linux() {
    [[ "$OSTYPE" == "linux"* ]]
}

# =============================================================================
# BRANDED ERROR HANDLING
# =============================================================================

unparty_exit_success() {
    echo -e ""
    echo -e "${BRAND_COLOR}cool!${NC}"
    echo -e ""
    exit 0
}

unparty_exit_error() {
    local message="$1"
    local code="${2:-1}"
    
    echo -e "${RED}❌ ${BOLD}Error: ${message}${NC}" >&2
    echo -e "${YELLOW}failure.${NC}" >&2
    exit "$code"
}

# =============================================================================
# THOUGHT SYSTEM EMOJIS (Single Source of Truth)
# =============================================================================

export THOUGHT_CORE_EMOJI="🧠"      # Brain for core insights
export THOUGHT_RISK_EMOJI="🚨"      # Warning/alert for risks  
export THOUGHT_CHALLENGE_EMOJI="❓"  # Question mark for challenges

# =============================================================================
# TIMING CONSTANTS
# =============================================================================

export INSTANT=0.05        # Immediate feedback
export QUICK=0.1          # Quick transitions  
export NORMAL=0.3         # Standard timing
export DRAMATIC=0.5       # Emphasis timing
export SLOW=1.0           # Deliberate pauses

# =============================================================================
# PLATFORM-SAFE UTILITIES
# =============================================================================

# Cross-platform file size
unparty_file_size() {
    local file="$1"
    if is_macos; then
        stat -f%z "$file" | awk '{
            if ($1 > 1024*1024*1024) printf "%.1fG", $1/1024/1024/1024
            else if ($1 > 1024*1024) printf "%.1fM", $1/1024/1024  
            else if ($1 > 1024) printf "%.1fK", $1/1024
            else printf "%dB", $1
        }'
    else
        stat -c%s "$file" | awk '{
            if ($1 > 1024*1024*1024) printf "%.1fG", $1/1024/1024/1024
            else if ($1 > 1024*1024) printf "%.1fM", $1/1024/1024  
            else if ($1 > 1024) printf "%.1fK", $1/1024
            else printf "%dB", $1
        }'
    fi
}

# Cross-platform file date
unparty_file_date() {
    local file="$1"
    if is_macos; then
        stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$file"
    else
        stat -c "%y" "$file" | cut -d' ' -f1,2 | cut -d'.' -f1
    fi
}

unparty_link() {
    local text="$1"
    echo -e "${PURPLE}🧠${NC} ${UNDERLINE}${CYAN}${text}${NC}"
}

# =============================================================================
# INITIALIZATION MESSAGE
# =============================================================================

if [ -n "$BASH_VERSION" ] && [ "${BASH_SOURCE[0]}" != "${0}" ]; then
    # Only show when sourced, not when executed directly
    echo -e "${DIM}${BRAND_COLOR}theunpartyrunway${NC}${DIM}${WHITE} - $(basename "$(pwd)")${NC}" >&2
fi