package ugh

import (
	"strings"
)

func parseSelectOptions(screen string, title string) (options []string, cursorIdx int) {
	lines := strings.Split(screen, "\n")
	titleIdx := -1
	for i, line := range lines {
		if strings.Contains(line, title) {
			titleIdx = i
			break
		}
	}
	if titleIdx < 0 {
		return nil, -1
	}

	cursorIdx = -1
	for i := titleIdx + 1; i < len(lines); i++ {
		line := lines[i]

		cleaned := stripBoxChars(line)
		cleaned = strings.TrimSpace(cleaned)

		if cleaned == "" {
			continue
		}

		if isHelpText(cleaned) {
			break
		}

		hasCursor := strings.HasPrefix(cleaned, ">")

		label := cleaned
		label = strings.TrimPrefix(label, "> ")
		label = strings.TrimPrefix(label, "> •")
		label = strings.TrimPrefix(label, "> ✓")
		label = strings.TrimPrefix(label, "> ✗")
		label = strings.TrimPrefix(label, "• ")
		label = strings.TrimPrefix(label, "✓ ")
		label = strings.TrimPrefix(label, "✗ ")
		label = strings.TrimSpace(label)

		if label == "" {
			continue
		}

		if hasCursor {
			cursorIdx = len(options)
		}
		options = append(options, label)
	}

	return options, cursorIdx
}

func stripBoxChars(s string) string {
	s = strings.ReplaceAll(s, "┃", " ")
	s = strings.ReplaceAll(s, "│", " ")
	s = strings.ReplaceAll(s, "║", " ")
	return s
}

func isHelpText(s string) bool {
	helpIndicators := []string{
		"enter submit", "enter next", "↑ up", "↓ down",
		"x toggle", "/ filter", "ctrl+", "tab ",
		"shift+tab", "ctrl+a select",
	}
	lower := strings.ToLower(s)
	for _, indicator := range helpIndicators {
		if strings.Contains(lower, indicator) {
			return true
		}
	}
	return false
}

func findCursorOption(screen string, title string) string {
	lines := strings.Split(screen, "\n")
	titleIdx := -1
	for i, line := range lines {
		if strings.Contains(line, title) {
			titleIdx = i
			break
		}
	}
	if titleIdx < 0 {
		return ""
	}

	for i := titleIdx + 1; i < len(lines); i++ {
		cleaned := stripBoxChars(lines[i])
		cleaned = strings.TrimSpace(cleaned)
		if cleaned == "" {
			continue
		}
		if isHelpText(cleaned) {
			break
		}
		if strings.HasPrefix(cleaned, ">") {
			label := strings.TrimPrefix(cleaned, "> ")
			label = strings.TrimPrefix(label, "• ")
			label = strings.TrimPrefix(label, "✓ ")
			label = strings.TrimPrefix(label, "✗ ")
			return strings.TrimSpace(label)
		}
	}
	return ""
}

func findOptionIndex(options []string, label string) int {
	for i, opt := range options {
		if strings.Contains(opt, label) {
			return i
		}
	}
	return -1
}
