package app

import (
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
)

const (
	defaultThemeColor = "#2d2c2c"
)

// Handler configures an HTTP handler to serve HTML pages that initialize a
// Go WebAssembly (WASM) application along with its resources. It includes
// configurations for PWA features, offline support, auto-update, and more.
type Handler struct {
	// Name specifies the display name of the web app, used where space permits.
	Name string

	// ShortName is an abbreviated app name for limited display areas.
	ShortName string

	// Icon represents the app icon used for PWA, favicon, and the default
	// "not found" component. Attributes like crossorigin can be appended after
	// a space.
	Icon Icon

	// BackgroundColor sets a placeholder background color for the app page
	// before stylesheets load. Defaults to "#2d2c2c".
	BackgroundColor string

	// ThemeColor specifies the app's theme color, affecting OS-level UI elements
	// like the PWA title bar. Defaults to "#2d2c2c".
	ThemeColor string

	// LoadingLabel shows text during page load, with "{progress}" for progress.
	// Defaults to "{progress}%".
	LoadingLabel string

	// Lang defines the primary language of the app page. Defaults to "en".
	Lang string

	// Libraries are custom libraries to load with the page.
	Libraries []Library

	// Title sets the title of the app page.
	Title string

	// Description provides a summary of the page's content, used as default
	// meta description and og:description.
	Description string

	// Domain specifies the domain name for resolving page metadata like
	// 'og:url'.
	Domain string

	// Author lists the authors of the page.
	Author string

	// Keywords are words or phrases associated with the page.
	Keywords []string

	// Image specifies the default image path used by social networks.
	// Attributes like crossorigin can be appended after a space.
	Image string

	// Styles lists CSS files for the page, supporting local and external
	// resources. Attributes like crossorigin can be appended after a space.
	Styles []string

	// Fonts lists font files to preload, improving performance and visual
	// readiness. Attributes like crossorigin can be appended after a space.
	Fonts []string

	// Scripts lists JavaScript files for the page. Attributes like crossorigin,
	// async, and defer can be appended, separated with a space.
	Scripts []string

	// CacheableResources specifies extra static resources to cache for offline
	// access. Icon, Styles and Scripts are already cached by default.
	// Attributes like crossorigin can be appended after a space.
	CacheableResources []string

	// RawHeaders contains extra HTML headers for the page's <head> section.
	RawHeaders []string

	// HTML returns the page's HTML element. Defaults to app.Html().
	HTML func() HTMLHtml

	// Body returns the page's body element. Defaults to app.Body().
	Body func() HTMLBody

	// Env passes environment variables to the PWA. Note: Reserved keys
	// (GOAPP_VERSION, GOAPP_GOAPP_STATIC_RESOURCES_URL) cannot be
	// overridden and are used for internal configuration.
	Env map[string]string

	// InternalURLs lists URLs to open within the app, overriding default behavior
	// for external domains.
	InternalURLs []string

	// Preconnect specifies origins to preconnect to, speeding up future loads.
	// Attributes like crossorigin can be appended after a space.
	Preconnect []string

	// ProxyResources maps custom paths to static resources. /robots.txt,
	// /sitemap.xml, and /ads.txt, which are proxied by default.
	ProxyResources []ProxyResource

	// Resources resolves paths for static resources, specifically handling
	// paths prefixed with "/web/". Defaults to app.LocalDir("").
	Resources ResourceResolver

	// StartURL defines the initial URL the PWA opens when launched from the
	// home screen or app icon. It should be a relative path (e.g., "/") and
	// typically points to the root of the app. Defaults to "/".
	StartURL string

	// Version defines the app's version. It's crucial for determining if an
	// update is available. Must be set in live environments to avoid recurring
	// updates. Auto-generated by default for local development updates.
	Version string

	// WasmContentLength indicates the byte length of the WASM file for progress
	// calculation. Falls back to WasmContentLengthHeader if unset.
	WasmContentLength string

	// WasmContentLengthHeader specifies the HTTP header for the WASM file's
	// content length. Defaults to "Content-Length".
	WasmContentLengthHeader string

	// ServiceWorkerTemplate defines the app-worker.js template, defaulting
	// to DefaultAppWorkerJS. Modifications are discouraged to avoid potential
	// issues with go-app functionality.
	ServiceWorkerTemplate string

	once                 sync.Once
	etag                 string
	libraries            map[string][]byte
	proxyResources       map[string]ProxyResource
	cachedProxyResources *memoryCache
	cachedPWAResources   *memoryCache
}

func ( *Handler) () {
	.initVersion()
	.initStaticResources()
	.initLibraries()
	.initLinks()
	.initServiceWorker()
	.initIcon()
	.initPWA()
	.initPageContent()
	.initPWAResources()
	.initProxyResources()
}

func ( *Handler) () {
	if .Version == "" {
		 := time.Now().UTC().String()
		.Version = fmt.Sprintf(`%x`, sha1.Sum([]byte()))
	}
	.etag = `"` + .Version + `"`
}

func ( *Handler) () {
	if .Resources == nil {
		.Resources = LocalDir("")
	}
}

func ( *Handler) () {
	 := make(map[string][]byte)
	for ,  := range .Libraries {
		,  := .Styles()
		if !strings.HasPrefix(, "/") || len() == 0 {
			continue
		}
		[] = []byte()
	}
	.libraries = 
}

func ( *Handler) () {
	 := []string{"/app.css"}
	for  := range .libraries {
		 = append(, )
	}
	.Styles = append(, .Styles...)
}

func ( *Handler) () {
	if .ServiceWorkerTemplate == "" {
		.ServiceWorkerTemplate = DefaultAppWorkerJS
	}
}

func ( *Handler) () {
	if .Icon.Default == "" {
		.Icon.Default = "https://raw.githubusercontent.com/maxence-charriere/go-app/master/docs/web/icon.png"
		.Icon.Large = "https://raw.githubusercontent.com/maxence-charriere/go-app/master/docs/web/icon.png"
	}

	if .Icon.Maskable == "" {
		.Icon.Maskable = .Icon.Default
	}

	if .Icon.SVG == "" {
		.Icon.SVG = "https://raw.githubusercontent.com/maxence-charriere/go-app/master/docs/web/icon.svg"
	}
}

func ( *Handler) () {
	if .Name == "" && .ShortName == "" && .Title == "" {
		.Name = "App PWA"
	}
	if .ShortName == "" {
		.ShortName = .Name
	}
	if .Name == "" {
		.Name = .ShortName
	}

	if .BackgroundColor == "" {
		.BackgroundColor = defaultThemeColor
	}
	if .ThemeColor == "" {
		.ThemeColor = defaultThemeColor
	}

	if .Lang == "" {
		.Lang = "en"
	}

	if .LoadingLabel == "" {
		.LoadingLabel = "{progress}%"
	}

	if .StartURL == "" {
		.StartURL = "/"
	}
}

func ( *Handler) () {
	if .HTML == nil {
		.HTML = Html
	}

	if .Body == nil {
		.Body = Body
	}

}

func ( *Handler) () {
	.cachedPWAResources = newMemoryCache(5)

	.cachedPWAResources.Set(cacheItem{
		Path:        "/wasm_exec.js",
		ContentType: "application/javascript",
		Body:        []byte(wasmExecJS()),
	})

	.cachedPWAResources.Set(cacheItem{
		Path:        "/app.js",
		ContentType: "application/javascript",
		Body:        .makeAppJS(),
	})

	// h.cachedPWAResources.Set(cacheItem{
	// 	Path:        "/app-worker.js",
	// 	ContentType: "application/javascript",
	// 	Body:        h.makeAppWorkerJS(),
	// })

	.cachedPWAResources.Set(cacheItem{
		Path:        "/manifest.webmanifest",
		ContentType: "application/manifest+json",
		Body:        .makeManifestJSON(),
	})

	.cachedPWAResources.Set(cacheItem{
		Path:        "/app.css",
		ContentType: "text/css",
		Body:        []byte(appCSS),
	})
}

func ( *Handler) () []byte {
	if .Env == nil {
		.Env = make(map[string]string)
	}
	,  := json.Marshal(.InternalURLs)
	.Env["GOAPP_INTERNAL_URLS"] = string()
	.Env["GOAPP_VERSION"] = .Version
	.Env["GOAPP_STATIC_RESOURCES_URL"] = .Resources.Resolve("/web")
	.Env["GOAPP_ROOT_PREFIX"] = .Resources.Resolve("/")

	for ,  := range .Env {
		if  := os.Setenv(, );  != nil {
			Log(errors.New("setting app env variable failed").
				WithTag("name", ).
				WithTag("value", ).
				Wrap())
		}
	}

	 := fmt.Sprintf("?v=%d", time.Now().UnixNano())
	 := appJS
	 = strings.ReplaceAll(, "{{.Env}}", jsonString(.Env))
	 = strings.ReplaceAll(, "{{.LoadingLabel}}", .LoadingLabel)
	 = strings.ReplaceAll(, "{{.Wasm}}", .Resources.Resolve("/web/app.wasm")+)
	 = strings.ReplaceAll(, "{{.WasmContentLength}}", .WasmContentLength)
	 = strings.ReplaceAll(, "{{.WasmContentLengthHeader}}", .WasmContentLengthHeader)
	 = strings.ReplaceAll(, "goappInitServiceWorker();", "//goappInitServiceWorker();")
	return []byte()
}

func ( *Handler) () []byte {
	 := make(map[string]struct{})
	 := func( ...string) {
		for ,  := range  {
			if  := parseHTTPResource(); .URL != "" {
				[.URL] = struct{}{}
			}
		}
	}
	(
		"/app.css",
		"/app.js",
		"/manifest.webmanifest",
		"/wasm_exec.js",
		"/web/app.wasm",
		"/",
	)
	(.Fonts...)
	(.Icon.Default, .Icon.Large, .Icon.Maskable)
	(.Styles...)
	(.Scripts...)
	(.CacheableResources...)

	 := make([]string, 0, len())
	for  := range  {
		 = append(, .Resources.Resolve())
	}
	sort.Slice(, func(,  int) bool {
		return strings.Compare([], []) > 0
	})

	 := .ServiceWorkerTemplate
	 = strings.ReplaceAll(, "{{.Version}}", .Version)
	 = strings.ReplaceAll(, "{{.ResourcesToCache}}", jsonString())
	return []byte()
}

func ( *Handler) () []byte {
	type  struct {
		     string `json:"src"`
		    string `json:"type"`
		 string `json:"purpose"`
		   string `json:"sizes"`
	}

	var  []
	if  := .Resources.Resolve(.Icon.Maskable);  != "" {
		 = append(, {
			:     ,
			:    "image/png",
			: "maskable",
			:   "512x512",
		})
	}
	if  := .Resources.Resolve(.Icon.SVG);  != "" {
		 = append(, {
			:   ,
			:  "image/svg+xml",
			: "any",
		})
	}
	if  := .Resources.Resolve(.Icon.Large);  != "" {
		 = append(, {
			:   ,
			:  "image/png",
			: "512x512",
		})
	}
	 = append(, {
		:   .Resources.Resolve(.Icon.Default),
		:  "image/png",
		: "192x192",
	})

	 := struct {
		       string         `json:"short_name"`
		            string         `json:"name"`
		     string         `json:"description"`
		           string         `json:"scope"`
		        string         `json:"start_url"`
		 string         `json:"background_color"`
		      string         `json:"theme_color"`
		         string         `json:"display"`
		           [] `json:"icons"`
	}{
		:       .ShortName,
		:            .Name,
		:     .Description,
		:           "/",
		:        .Resources.Resolve(.StartURL),
		: .BackgroundColor,
		:      .ThemeColor,
		:         "standalone",
		:           ,
	}

	,  := json.Marshal()
	if  != nil {
		panic(errors.New("encoding manifest failed").Wrap())
	}
	return 
}

func ( *Handler) () {
	.cachedProxyResources = newMemoryCache(len(.ProxyResources))
	 := make(map[string]ProxyResource)

	for ,  := range .ProxyResources {
		switch .Path {
		case "/wasm_exec.js",
			"/goapp.js",
			"/app.js",
			"/app-worker.js",
			"/manifest.json",
			"/manifest.webmanifest",
			"/app.css",
			"/app.wasm",
			"/goapp.wasm",
			"/":
			continue

		default:
			if strings.HasPrefix(.Path, "/") && strings.HasPrefix(.ResourcePath, "/web/") {
				[.Path] = 
			}
		}
	}

	if ,  := ["/robots.txt"]; ! {
		["/robots.txt"] = ProxyResource{
			Path:         "/robots.txt",
			ResourcePath: "/web/robots.txt",
		}
	}
	if ,  := ["/sitemap.xml"]; ! {
		["/sitemap.xml"] = ProxyResource{
			Path:         "/sitemap.xml",
			ResourcePath: "/web/sitemap.xml",
		}
	}
	if ,  := ["/ads.txt"]; ! {
		["/ads.txt"] = ProxyResource{
			Path:         "/ads.txt",
			ResourcePath: "/web/ads.txt",
		}
	}

	.proxyResources = 
}

func ( *Handler) ( http.ResponseWriter,  *http.Request) {
	.once.Do(.init)

	.Header().Set("Cache-Control", "no-cache")
	.Header().Set("ETag", .etag)

	 := .Header.Get("If-None-Match")
	if  == .etag {
		.WriteHeader(http.StatusNotModified)
		return
	}

	 := .URL.Path
	if strings.HasPrefix(, "/"+.Version+"/") {
		 = strings.TrimPrefix(, "/"+.Version)
	}

	,  := .Resources.(http.Handler)
	if  && strings.HasPrefix(, "/web/") {
		.ServeHTTP(, )
		return
	}

	switch  {
	case "/goapp.js":
		 = "/app.js"

	case "/manifest.json":
		 = "/manifest.webmanifest"

	case "/app.wasm", "/goapp.wasm":
		if  {
			 := *
			.URL.Path = .Resources.Resolve("/web/app.wasm")
			.ServeHTTP(, &)
			return
		}
		.WriteHeader(http.StatusNotFound)
		return

	}

	if ,  := .cachedPWAResources.Get();  {
		.serveCachedItem(, )
		return
	}

	if ,  := .proxyResources[];  {
		.serveProxyResource(, , )
		return
	}

	if ,  := .libraries[];  {
		.serveLibrary(, , )
		return
	}

	.servePage(, )
}

func ( *Handler) ( http.ResponseWriter,  cacheItem) {
	.Header().Set("Content-Length", strconv.Itoa(.Len()))
	.Header().Set("Content-Type", .ContentType)

	if .ContentEncoding != "" {
		.Header().Set("Content-Encoding", .ContentEncoding)
	}

	.WriteHeader(http.StatusOK)
	.Write(.Body)
}

func ( *Handler) ( ProxyResource,  http.ResponseWriter,  *http.Request) {
	var  string
	if ,  := .Resources.(http.Handler);  {
		var  string
		if .TLS != nil {
			 = "https://"
		} else {
			 = "http://"
		}
		 =  + .Host + .ResourcePath
	} else {
		 = .Resources.Resolve(.ResourcePath)
	}

	if ,  := .cachedProxyResources.Get(.Path);  {
		.serveCachedItem(, )
		return
	}

	,  := http.Get()
	if  != nil {
		.WriteHeader(http.StatusInternalServerError)
		Log(errors.New("getting proxy static resource failed").
			WithTag("url", ).
			WithTag("proxy-path", .Path).
			WithTag("static-resource-path", .ResourcePath).
			Wrap(),
		)
		return
	}
	defer .Body.Close()

	if .StatusCode != http.StatusOK {
		.WriteHeader(http.StatusNotFound)
		return
	}

	,  := io.ReadAll(.Body)
	if  != nil {
		.WriteHeader(http.StatusInternalServerError)
		Log(errors.New("reading proxy static resource failed").
			WithTag("url", ).
			WithTag("proxy-path", .Path).
			WithTag("static-resource-path", .ResourcePath).
			Wrap(),
		)
		return
	}

	 := cacheItem{
		Path:            .Path,
		ContentType:     .Header.Get("Content-Type"),
		ContentEncoding: .Header.Get("Content-Encoding"),
		Body:            ,
	}
	.cachedProxyResources.Set()
	.serveCachedItem(, )
}

func ( *Handler) ( http.ResponseWriter,  *http.Request) {
	if  := routes.routed(.URL.Path); ! {
		http.NotFound(, )
		return
	}

	 := context.Background()

	 := *.URL
	.Scheme = "http"

	 := makeRequestPage(&, .Resources.Resolve)
	.SetTitle(.Title)
	.SetLang(.Lang)
	.SetDescription(.Description)
	.SetAuthor(.Author)
	.SetKeywords(.Keywords...)
	.SetLoadingLabel(strings.ReplaceAll(.LoadingLabel, "{progress}", "0"))
	.SetImage(.Image)

	 := newEngine(,
		&routes,
		.Resources.Resolve,
		&,
		actionHandlers,
	)
	.Navigate(.URL(), false)
	.ConsumeAll()

	 := .Icon.SVG
	if  == "" {
		 = .Icon.Default
	}

	 := fmt.Sprintf("?v=%d", time.Now().UnixNano())
	var  bytes.Buffer
	 := .Encode(&, .HTML().
		Lang(.Lang()).
		privateBody(
			Head().Body(
				Meta().Charset("UTF-8"),
				Meta().
					Name("author").
					Content(.Author()),
				Meta().
					Name("description").
					Content(.Description()),
				If(.Keywords() != "", func() UI {
					return Meta().
						Name("keywords").
						Content(.Keywords())
				}),
				Meta().
					Name("theme-color").
					Content(.ThemeColor),
				Meta().
					Name("viewport").
					Content("width=device-width, initial-scale=1, viewport-fit=cover"),
				Meta().
					Name("mobile-web-app-capable").
					Content("yes"),
				Meta().
					Property("og:url").
					Content(resolveOGResource(.Domain, .Resources.Resolve(.URL().Path))),
				Meta().
					Property("og:title").
					Content(.Title()),
				Meta().
					Property("og:description").
					Content(.Description()),
				Meta().
					Property("og:type").
					Content("website"),
				Meta().
					Property("og:image").
					Content(resolveOGResource(.Domain, .Image())),
				Range(.twitterCardMap).Map(func( string) UI {
					 := .twitterCardMap[]
					if  == "" {
						return nil
					}
					if  == "twitter:image" {
						 = resolveOGResource(.Domain, )
					}
					return Meta().
						Name().
						Content()
				}),
				Title().Text(.Title()),
				If(.canonicalLink != "", func() UI {
					return Link().
						Rel("canonical").
						Href(resolveOGResource(.Domain, .canonicalLink))
				}),
				Range(.Preconnect).Slice(func( int) UI {
					if  := parseHTTPResource(.Preconnect[]); .URL != "" {
						return .toLink().Rel("preconnect")
					}
					return nil
				}),
				Range(.Fonts).Slice(func( int) UI {
					if  := parseHTTPResource(.Fonts[]); .URL != "" {
						return .toLink().
							Type("font/" + strings.TrimPrefix(filepath.Ext(.URL), ".")).
							Rel("preload").
							As("font")
					}
					return nil
				}),
				Range(.Preloads()).Slice(func( int) UI {
					 := .Preloads()[]
					if .Href == "" || .As == "" {
						return nil
					}

					if  := parseHTTPResource(.Href); .URL != "" {
						return .toLink().
							Type(.Type).
							Rel("preload").
							As(.As).
							FetchPriority(.FetchPriority)
					}
					return nil
				}),
				Link().
					Rel("icon").
					Href(),
				Link().
					Rel("apple-touch-icon").
					Href(.Icon.Maskable),
				Link().
					Rel("manifest").
					Href("/manifest.webmanifest"),
				Range(.Styles).Slice(func( int) UI {
					if  := parseHTTPResource(.Styles[]); .URL != "" {
						return .toLink().
							Type("text/css").
							Rel("stylesheet")
					}
					return nil
				}),
				Script().
					Defer(true).
					Src("/wasm_exec.js"),
				Script().
					Defer(true).
					Src("/app.js"+),
				Range(.Scripts).Slice(func( int) UI {
					if  := parseHTTPResource(.Scripts[]); .URL != "" {
						return .toScript()
					}
					return nil

				}),
				Range(.RawHeaders).Slice(func( int) UI {
					return Raw(.RawHeaders[])
				}),
			),
			.Body().privateBody(
				Aside().
					ID("app-wasm-loader").
					Class("goapp-app-info").
					Body(
						Img().
							ID("app-wasm-loader-icon").
							Class("goapp-logo goapp-spin").
							Alt("wasm loader icon").
							Src(.Icon.Default),
						P().
							ID("app-wasm-loader-label").
							Class("goapp-label").
							Text(.loadingLabel),
					),
			),
		))
	if  != nil {
		Log(errors.New("encoding html document failed").Wrap())
		.WriteHeader(http.StatusInternalServerError)
		return
	}

	.Header().Set("Content-Length", strconv.Itoa(.Len()))
	.Header().Set("Content-Type", "text/html")
	.Write(.Bytes())
}

func ( *Handler) ( http.ResponseWriter,  *http.Request,  []byte) {
	.Header().Set("Content-Length", strconv.Itoa(len()))
	.Header().Set("Content-Type", "text/css")
	.Write()
}

// Icon represents a square image utilized in various contexts, such as the
// application icon, favicon, and loading icon. Paths specified for icons
// are relative to the root directory unless stated otherwise.
type Icon struct {
	// Default specifies the path or URL to a square image/png file with a
	// dimension of 192x192 pixels. Represents the standard application icon.
	Default string

	// Large indicates the path or URL to a larger square image/png file,
	// required to be 512x512 pixels. Used for high-resolution displays.
	Large string

	// SVG specifies the path or URL to an SVG file, providing vector-based
	// imagery for scalable application icons. Ideal for responsive design.
	SVG string

	// Maskable specifies the path or URL to an adaptive icon designed for various
	// operating system shapes. This icon must be a PNG image with 512x512 pixels.
	//
	// Used in PWA manifests and as meta tags for Apple browsers, these icons adapt
	// to device or browser shape requirements, avoiding unsightly cropping.
	//
	// To convert existing icons to a maskable format, visit
	// https://maskable.app/editor. This tool simplifies creating icons that meet
	// maskable specifications.
	//
	// If not specified, Icon.Default is used as a fallback. Specifying a maskable
	// icon enhances user experience on platforms supporting adaptive icons.
	Maskable string
}

func isRemoteLocation( string) bool {
	return strings.HasPrefix(, "https://") ||
		strings.HasPrefix(, "http://")
}

func isStaticResourcePath( string) bool {
	return strings.HasPrefix(, "/web/") ||
		strings.HasPrefix(, "web/")
}

type httpResource struct {
	URL         string
	LoadingMode string
	CrossOrigin string
}

func ( httpResource) () HTMLLink {
	 := Link().Href(.URL)
	if .CrossOrigin != "" {
		 = .CrossOrigin(strings.Trim(.CrossOrigin, "true"))
	}
	return 
}

func ( httpResource) () HTMLScript {
	 := Script().Src(.URL)
	if .CrossOrigin != "" {
		 = .CrossOrigin(strings.Trim(.CrossOrigin, "true"))
	}

	switch .LoadingMode {
	case "defer":
		 = .Defer(true)

	case "async":
		 = .Async(true)
	}
	return 
}

func parseHTTPResource( string) httpResource {
	var  httpResource
	for ,  := range strings.Split(, " ") {
		if  = strings.TrimSpace();  == "" {
			continue
		}

		switch  := strings.ToLower(); {
		case  == "crossorigin":
			.CrossOrigin = "true"

		case strings.HasPrefix(, "crossorigin="):
			.CrossOrigin = strings.TrimPrefix(, "crossorigin=")

		case  == "defer",
			 == "async":
			.LoadingMode = 

		default:
			.URL = 
		}
	}
	return 
}