package editor

import (
	"pad/internal/ui"
)

// SampleText is a static lorem-ipsum text used for display-only testing.
// Roughly 3 KB, filling a few pages of the editor.
const SampleText = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architectus qui exercitationem ullam corporis suscipit dolorum et saepe fugiat. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.

Neque porro consequatur autem velbeat viciis quam autem voluptas minus odio voluptatem. Quis autem vel natus autem sequis dolor tempor. Ut enim minima voluptate et quis autem sequia dolor tempor. Sed autem quia dolor sed consequat et voluptate autem sequia dolor tempor. Nemo enim sed consequat et voluptate autem sequia dolor tempor.

The quick brown fox jumps over the lazy dog. This is a short line to test how the editor handles lines that are much shorter than the wrap width. Some lines will be very long and wrap many times, while others fit on a single line easily.

Attitulam velis, te sum quae dolorem sequia dolor tempor. Ut enim minima voluptate et quis autem sequia dolor tempor. Sed autem quia dolor sed consequat et voluptate autem sequia dolor tempor. Nemo enim sed consequat et voluptate autem sequia dolor tempor.

There are also words that are extremelylonganddonothaveanywhitespacesinwhichcasewithheuristicswrappingthewholewordwilloverflowthewrapwidthratherthanbeingbrokenmidcharacter. This is expected behavior for a text editor — long identifiers, URLs, or concatenated text should stay on one line even if they exceed the viewport width.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Two words: antidisestablishmentarianism and floccinauciniphilolipaecpelagioodontophont索菲乌斯 are examples of long words that may overflow the wrap width.

In conclusion, this sample text provides a variety of line lengths, word lengths, and paragraph structures to exercise the word wrap implementation. Short lines, long lines, very long words, normal words, empty lines — all present here.`

// EditorFontSize is the font size used for editor text.
const EditorFontSize = 14 // unit.Sp

// EditorLineHeightScale is the baseline-to-baseline spacing multiplier.
const EditorLineHeightScale = 1.2

// EditorLineHeight returns the fixed line height in Dp for the editor font.
func EditorLineHeight() ui.Dp {
	return ui.Dp(float32(EditorFontSize) * EditorLineHeightScale)
}

// State holds all application state owned by the logic goroutine.
type State struct {
	PixelWidth       int   // raw pixel width from Gio ConfigEvent
	PixelHeight      int   // raw pixel height from Gio ConfigEvent
	scale            float32
	WordWrap         bool
	ScrollOffset     ui.Dp // vertical scroll position in Dp
	LastLineY        ui.Dp // last line baseline offset from text origin, from renderer
	MaxScroll        ui.Dp // max scroll offset (content height - viewport height)
	Elems            []ui.Element
}

func NewState() *State {
	return &State{scale: 1.0}
}

func (s *State) SetScale(scale float32) {
	s.scale = scale
}

func (s *State) Scale() float32 {
	return s.scale
}

// layout converts stored pixel dimensions to Dp using the current scale
// and computes the element tree. Called only when a frame is needed.
func (s *State) layout() []ui.Element {
	dpW := ui.ToDp(ui.Px(s.PixelWidth), s.scale)
	dpH := ui.ToDp(ui.Px(s.PixelHeight), s.scale)
	s.Elems = EditorLayout(dpW, dpH, s.WordWrap)
	return s.Elems
}

// ToggleWordWrap toggles the word wrap setting.
func ToggleWordWrap(data any) {
	TheState.WordWrap = !TheState.WordWrap
}

// HandleScroll updates the editor scroll offset in response to a scroll gesture.
// The delta is in pixels (from gesture.Scroll.Update). Convert to Dp.
// Clamped to [0, MaxScroll] so content doesn't scroll past its ends.
func HandleScroll(data any) {
	delta := data.(int) // pixels
	TheState.ScrollOffset += ui.ToDp(ui.Px(delta), TheState.scale)
	if TheState.ScrollOffset < 0 {
		TheState.ScrollOffset = 0
	}
	if TheState.ScrollOffset > TheState.MaxScroll {
		TheState.ScrollOffset = TheState.MaxScroll
	}
}

// EditorLayout computes the element tree for the editor page.
func EditorLayout(screenWidth, screenHeight ui.Dp, wordWrap bool) []ui.Element {
	margin := ui.Dp(10)

	// --- Top bar: filename on row 1, icons on row 2 ---
	statusBarRegion := ui.Region{
		X: margin, Y: margin,
		W: screenWidth - margin*2,
		H: ui.Dp(52),
	}
	statusBarW := statusBarRegion.W
	statusBar := ui.NewContainer(
		statusBarRegion,
		ui.Color{R: 230, G: 230, B: 230, A: 255},
		[]ui.Element{
			// Row 1: filename
			ui.NewLabel("a very long file name that probably will eventually need to be truncated.txt", 14, ui.Region{X: 0, Y: ui.Dp(2), W: statusBarW, H: ui.Dp(20)}, ui.AlignStart, "", nil),
			// Row 2: cut, copy, paste icons
			ui.NewIcon("cut", ui.Region{X: ui.Dp(0), Y: ui.Dp(28), W: ui.IconSize, H: ui.IconSize}, 0),
			ui.NewIcon("copy", ui.Region{X: ui.Dp(48), Y: ui.Dp(28), W: ui.IconSize, H: ui.IconSize}, 0),
			ui.NewIcon("paste", ui.Region{X: ui.Dp(96), Y: ui.Dp(28), W: ui.IconSize, H: ui.IconSize}, 0),
		},
	)

	// --- Bottom bar ---
	bottomBarHeight := ui.BottomBarHeight
	bottomBarY := screenHeight - margin - bottomBarHeight
	bottomBarRegion := ui.Region{
		X: margin, Y: bottomBarY,
		W: screenWidth - margin*2,
		H: bottomBarHeight,
	}
	bottomBarW := bottomBarRegion.W
	wrapText := "Wrap: Off"
	if wordWrap {
		wrapText = "Wrap: On"
	}
	bottomBar := ui.NewContainer(
		bottomBarRegion,
		ui.Color{R: 230, G: 230, B: 230, A: 255},
		[]ui.Element{
			ui.NewLabel("Ln 47, Col 12", 12, ui.Region{X: 0, Y: ui.Dp(2), W: bottomBarW, H: ui.Dp(20)}, ui.AlignStart, "", nil),
			ui.NewLabel("1024 / 50000", 12, ui.Region{X: 0, Y: ui.Dp(2), W: bottomBarW, H: ui.Dp(20)}, ui.AlignCenter, "", nil),
			ui.NewLabel(wrapText, 12, ui.Region{X: 0, Y: ui.Dp(2), W: bottomBarW, H: ui.Dp(20)}, ui.AlignEnd, "wrap", []ui.Interaction{
				{Gesture: ui.Tap, Handler: ToggleWordWrap},
			}),
		},
	)

	// --- Editor text area ---
	editorY := statusBarRegion.Y + statusBarRegion.H
	editorH := bottomBarRegion.Y - editorY
	editorRegion := ui.Region{
		X: margin, Y: editorY,
		W: screenWidth - margin*2,
		H: editorH,
	}
	// Compute max scroll offset from the last line baseline reported by the renderer.
	// lastLineY is the shaper's Y value for the last line's baseline.
	// Add bottom padding (half line height) so last line isn't flush with the bottom bar.
	maxScroll := TheState.LastLineY - editorRegion.H + EditorLineHeight()/2
	if maxScroll < 0 {
		maxScroll = 0
	}
	TheState.MaxScroll = maxScroll

	editor := ui.NewTextField(
		SampleText,
		editorRegion,
		editorRegion.W,
		TheState.ScrollOffset,
		[]ui.Interaction{{Gesture: ui.Scroll, Handler: HandleScroll}},
	)

	return []ui.Element{statusBar, editor, bottomBar}
}
