use assetserver::Asset;
use axum::Router;
use maud::{DOCTYPE, Markup, PreEscaped, html};
use tracing::info;

use crate::{
	components::misc::FarLink,
	page::{Page, PageServer},
	pages,
	routes::assets::Styles_Main,
};

pub mod assets;

pub(super) fn router() -> Router<()> {
	let (asset_prefix, asset_router) = assets::asset_router();
	info!("Serving assets at {asset_prefix}");

	let server = build_server().into_router();

	Router::new().merge(server).nest(asset_prefix, asset_router)
}

fn build_server() -> PageServer {
	PageServer::new(Box::new(page_wrapper))
		.add_page("/", pages::index())
		.add_page("/links", pages::links())
		.add_page("/whats-a-betalupi", pages::betalupi())
		.add_page("/handouts", pages::handouts())
}

fn page_wrapper(page: &Page) -> Markup {
	html! {
		(DOCTYPE)
		html {
			head {
				meta charset="UTF" {}
				meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" {}
				meta content="text/html; charset=UTF-8" http-equiv="content-type" {}
				meta property="og:type" content="website" {}

				link rel="stylesheet" href=(Styles_Main::URL) {}

				(&page.meta)
				title { (PreEscaped(page.meta.title.clone())) }
			}

			body {
				div class="wrapper" {
					main { ( page.generate_html() ) }

					footer {
						hr class = "footline" {}
						div class = "footContainer" {
							p {
								"This site was built by hand using "
								(FarLink("https://rust-lang.org", "Rust"))
								", "
								(FarLink("https://maud.lambda.xyz", "Maud"))
								", "
								(FarLink("https://github.com/connorskees/grass", "Grass"))
								", and "
								(FarLink("https://docs.rs/axum/latest/axum", "Axum"))
								"."
							}
						}
					}
				}
			}
		}
	}
}

#[test]
fn server_builds_without_panic() {
	// Catches some runtime errors thrown by axum,
	// e.g bad route nesting or routes not starting with "/"
	let _server = build_server().into_router();
}
