#!/usr/bin/env bash
# br-capture: Interactive br issue capture via gum
# Launched from tmux popup (prefix + i)

set -euo pipefail

# Parse args
QUICK_MODE=false
while [[ $# -gt 0 ]]; do
    case "$1" in
        -q|--quick) QUICK_MODE=true; shift ;;
        *) shift ;;
    esac
done

# Colors
RED=196
GREEN=82
DIM=245

# Header banner
gum style --border rounded --padding "0 1" "New Issue"
echo

# Check tracker initialized
if [[ ! -d .beads ]]; then
    gum style --foreground "$RED" --bold "Error: Not in a br-initialized directory"
    gum style --foreground "$DIM" "Run 'br init' to initialize the tracker here"
    read -n 1 -s -r -p "Press any key to close..."
    exit 1
fi

# Title (required)
gum style --foreground "$DIM" "Step 1/4"
TITLE=$(gum input --placeholder "Issue title..." --width 70 --header "Title")
[[ -z "$TITLE" ]] && exit 0

if $QUICK_MODE; then
    # Quick mode: use defaults
    TYPE="task"
    PRIORITY="P2"
    DESC=""
else
    # Type selection with task as default
    gum style --foreground "$DIM" "Step 2/4"
    TYPE=$(gum choose --header "Type" --selected "task" \
        "task" "bug" "feature" "epic" "chore")

    # Priority selection with P2 as default
    gum style --foreground "$DIM" "Step 3/4"
    PRIORITY_FULL=$(gum choose --header "Priority" --selected "P2 (Medium)" \
        "P0 (Critical)" \
        "P1 (High)" \
        "P2 (Medium)" \
        "P3 (Low)" \
        "P4 (Backlog)")
    PRIORITY=$(echo "$PRIORITY_FULL" | cut -d' ' -f1)

    # Description (optional - just press Enter to skip)
    gum style --foreground "$DIM" "Step 4/4"
    DESC=$(gum write \
      --header "Description (optional)" \
      --placeholder "Add details... (Ctrl+D to finish)" \
      --width 70 \
      --height 8 \
      --show-help)
fi

# Build command
CMD=(br create --silent --title "$TITLE" --type "$TYPE" --priority "$PRIORITY")
[[ -n "$DESC" ]] && CMD+=(--description "$DESC")

# Create issue directly (no confirmation prompt)
if OUTPUT=$(gum spin --spinner dot --title "Creating issue..." -- "${CMD[@]}" 2>&1); then
    ISSUE_ID=$(printf '%s\n' "$OUTPUT" | awk 'NF { print; exit }' | tr -d '\r')
    if [[ -n "$ISSUE_ID" ]]; then
        echo "$ISSUE_ID" | pbcopy
        gum style --foreground "$GREEN" --bold "✓ Created: $ISSUE_ID (copied to clipboard)"
    else
        gum style --foreground "$GREEN" --bold "Issue created"
        echo "$OUTPUT"
    fi
    sleep 1
else
    gum style --foreground "$RED" --bold "Error creating issue:"
    echo "$OUTPUT"
    read -n 1 -s -r -p "Press any key to close..."
    exit 1
fi
