package tui

import (
	"bufio"
	"math/rand"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/charmbracelet/lipgloss"
)

// LoadASCIIArt reads a random .txt file from staticPath and returns it
// rendered with a color gradient. Pass nil for colors to use DefaultGradientColors.
// Returns "" if no .txt files are found or on any error.
func LoadASCIIArt(staticPath string, colors []lipgloss.Color) string {
	files, err := os.ReadDir(staticPath)
	if err != nil {
		return ""
	}

	var txtFiles []string
	for _, f := range files {
		if !f.IsDir() && strings.HasSuffix(f.Name(), ".txt") {
			txtFiles = append(txtFiles, f.Name())
		}
	}
	if len(txtFiles) == 0 {
		return ""
	}

	rng := rand.New(rand.NewSource(time.Now().UnixNano()))
	selected := txtFiles[rng.Intn(len(txtFiles))]

	file, err := os.Open(filepath.Join(staticPath, selected))
	if err != nil {
		return ""
	}
	defer file.Close()

	var lines []string
	sc := bufio.NewScanner(file)
	for sc.Scan() {
		lines = append(lines, sc.Text())
	}

	if len(lines) == 0 {
		return ""
	}
	return ApplyGradient(lines, colors)
}
