package app

import (
	
)

type browser struct {
	AppUpdatable bool

	anchorClick      Func
	popState         Func
	navigationFromJS Func
	appUpdate        Func
	appInstallChange Func
	appResize        Func
	resizeTimer      *time.Timer
}

func ( *browser) ( Context,  func(any)) {
	.handleAnchorClick()
	.handlePopState()
	.handleNavigationFromJS()
	.handleAppUpdate(, )
	.handleAppInstallChange(, )
	.handleAppResize(, )
}

func ( *browser) ( Context) {
	.anchorClick = FuncOf(func( Value,  []Value) any {
		.dispatch(func() {
			 := Event{Value: [0]}

			for  := .Get("target"); .Truthy();  = .Get("parentElement") {
				switch .Get("tagName").String() {
				case "A":
					if  := .Get("metaKey"); .Truthy() && .Bool() {
						return
					}

					if  := .Get("ctrlKey"); .Truthy() && .Bool() {
						return
					}

					if  := .Call("getAttribute", "download"); !.IsNull() {
						return
					}

					switch .Get("target").String() {
					case "_blank":
						return
					}

					.PreventDefault()
					if  := .Get("href"); .Truthy() {
						.Navigate(.Get("href").String())
					}
					return

				case "BODY":
					return
				}
			}
		})
		return nil
	})
	Window().Set("onclick", .anchorClick)
}

func ( *browser) ( Context) {
	.popState = FuncOf(func( Value,  []Value) any {
		.dispatch(func() {
			.navigate(Window().URL(), false)
		})
		return nil
	})
	Window().Set("onpopstate", .popState)
}

func ( *browser) ( Context) {
	.navigationFromJS = FuncOf(func( Value,  []Value) any {
		.dispatch(func() {
			.Navigate([0].String())
		})
		return nil
	})
	Window().Set("goappNav", .navigationFromJS)
}

func ( *browser) ( Context,  func(any)) {
	 := func() {
		.dispatch(func() {
			.AppUpdatable = true
			(appUpdate{})
		})
		.defere(func() {
			Log(Window().URL().Hostname() + " has been updated, reload to see changes")
		})
	}

	.appUpdate = FuncOf(func( Value,  []Value) any {
		()
		return nil
	})
	Window().Set("goappOnUpdate", .appUpdate)

	if Window().Get("goappUpdatedBeforeWasmLoaded").Truthy() {
		()
	}
}

func ( *browser) ( Context,  func(any)) {
	 := func() {
		.dispatch(func() {
			(appInstallChange{})
		})
	}

	.appInstallChange = FuncOf(func( Value,  []Value) any {
		()
		return nil
	})
	Window().Set("goappOnAppInstallChange", .appInstallChange)

	if Window().Get("goappAppInstallChangedBeforeWasmLoaded").Truthy() {
		()
	}
}

func ( *browser) ( Context,  func(any)) {
	const  = time.Millisecond * 250

	.appResize = FuncOf(func( Value,  []Value) any {
		.dispatch(func() {
			if .resizeTimer != nil {
				.resizeTimer.Stop()
				.resizeTimer.Reset()
				return
			}

			.resizeTimer = time.AfterFunc(, func() {
				.dispatch(func() {
					(resize{})
				})
			})
		})
		return nil
	})
	Window().Set("onresize", .appResize)
}