package app

import (
	"strings"

	"charm.land/lipgloss/v2"
)

// ideacard.go renders the cross-session idea board (OverlayIdeas): the ideas the router
// captured while the operator rubber-ducked, each removable. Modeled on the artifact
// viewer's list shell, but ideas are short notes so there is no separate content pane.

// ideaListRows is how many idea rows fit in the board (the rest is title + hints).
func (m Model) ideaListRows() int {
	rows := m.height*70/100 - 5
	if rows < 1 {
		rows = 1
	}
	if rows > len(m.ideas) {
		rows = len(m.ideas)
	}
	if rows < 1 {
		rows = 1
	}
	return rows
}

func (m Model) ideasModal() string {
	t := m.theme
	w := m.modalWidth()

	var b strings.Builder
	b.WriteString(m.titleLine("ideas"))
	if len(m.ideas) > 0 {
		b.WriteString(mbg(t, "   ("+itoa(m.ideasIndex+1)+"/"+itoa(len(m.ideas))+")", t.P.Faint))
	}
	b.WriteString(mbg(t, "   · captured while rubber-ducking", t.P.Faint) + "\n\n")

	if m.ideasLoading {
		b.WriteString(mbg(t, "  loading…", t.P.Faint) + "\n")
		b.WriteString("\n" + modalHints(t, [][2]string{{"esc", "close"}}))
		return t.Overlay.Width(w).Render(b.String())
	}
	if len(m.ideas) == 0 {
		b.WriteString(mbg(t, "  no ideas yet — they're saved as you think out loud with the router", t.P.Faint) + "\n")
		b.WriteString("\n" + modalHints(t, [][2]string{{"esc", "close"}}))
		return t.Overlay.Width(w).Render(b.String())
	}

	// Windowed list, keeping the selected row in view.
	rows := m.ideaListRows()
	off := 0
	if len(m.ideas) > rows {
		off = m.ideasIndex - rows/2
		if off < 0 {
			off = 0
		}
		if off > len(m.ideas)-rows {
			off = len(m.ideas) - rows
		}
	}
	end := off + rows
	if end > len(m.ideas) {
		end = len(m.ideas)
	}
	textW := w - 8
	for i := off; i < end; i++ {
		marker := mbg(t, "  ", t.P.BgPanel)
		fg := t.P.Fg
		if i == m.ideasIndex {
			marker = lipgloss.NewStyle().Foreground(t.P.Accent).Background(t.P.BgPanel).Render("▸ ")
			fg = t.P.FgStrong
		}
		text := strings.ReplaceAll(m.ideas[i].Text, "\n", " ")
		b.WriteString(marker + lipgloss.NewStyle().Foreground(fg).Background(t.P.BgPanel).Render(clip(text, textW)) + "\n")
	}

	b.WriteString("\n" + modalHints(t, [][2]string{
		{"↑↓", "move"}, {"x", "remove"}, {"esc", "close"},
	}))
	return t.Overlay.Width(w).Render(b.String())
}
