//! atproto-static-web   A simple web viewer for AT Proto.
//! Copyright (C) 2025  AverageHelper
//!
//! This program is free software: you can redistribute it and/or modify
//! it under the terms of the GNU General Public License as published by
//! the Free Software Foundation, either version 3 of the License, or
//! (at your option) any later version.
//!
//! This program is distributed in the hope that it will be useful,
//! but WITHOUT ANY WARRANTY; without even the implied warranty of
//! MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//! GNU General Public License for more details.
//!
//! You should have received a copy of the GNU General Public License
//! along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::{
	env::Env,
	server::lang::{Lang, tr},
	templates::{self, base::OgMedia},
	xrpc::{
		get_post_thread::{GetPostThreadError, ThreadViewPost},
		get_profile::ProfileViewDetailed,
	},
};
use maud::{Markup, html};

pub fn profile(
	lang: Lang,
	env: &Env,
	profile: ProfileViewDetailed,
	pinned: Option<Result<ThreadViewPost, GetPostThreadError>>,
) -> Markup {
	let handle = format!("@{}", profile.handle);
	let display_name = profile.display_name.as_ref().unwrap_or(&handle);
	let description = profile.description.unwrap_or_default();

	let profile_uri = format!("/profile/{}", profile.did);
	let canonical_url = env.base_url().join(&profile_uri).expect("valid url");
	let og_title = &format!("{display_name} ({handle})");
	let title = &format!("{og_title} - {}", env.site_name());

	let followers_uri = format!("{profile_uri}/followers");
	let follows_uri = format!("{profile_uri}/follows");

	let meta = templates::base::Meta {
		title,
		lang,
		og_type: templates::base::OgType::Profile,
		content_locales: &[oxilangtag::LanguageTag::parse(lang.to_string()).unwrap()],
		profile_username: Some(&profile.handle),
		og_title,
		canonical_url: &canonical_url,
		og_description: description.as_str().into(),
		og_images: match &profile.banner {
			Some(content) => &[OgMedia { content, alt: "" }],
			None => &[],
		},
		og_videos: None,
		og_card: templates::base::OgCard::Summary,
		og_published_time: None,
		labels: &[("Account DID", &profile.did.to_string())],
	};
	let main = html! {
		// TODO: Button to go "back" to /
		@match &profile.banner {
			Some(banner) => img class="banner" src=(banner) alt="" width="600" height="150";
			None => div class="banner-placeholder" {}
		}
		section class="profile" {
			@match &profile.avatar {
				Some(avatar) => img class="avatar" src=(avatar) alt="" width="90" height="90";
				None => img class="avatar" src="" alt="" width="90" height="90";
			}
			header class="profile" {
				section class="user" {
					h1 {
						a href=(profile_uri) { (display_name) }
					}
					span class="handle" {
						"@"
						span style="user-select:all" { (profile.handle) }
					}
				}
			}
			aside class="profile stats" {
				a href=(followers_uri) {
					span class="data" {
						@if let Some(followers) = profile.followers_count {
							(followers)
						} @else {
							(tr!(lang, "post.stats.unknown_value"))
						}
					}
					span class="label" { " "(tr!(lang, "profile.stats.followers_label")) }
				}
				a href=(follows_uri) {
					span class="data" {
						@if let Some(following) = profile.follows_count {
							(following)
						} @else {
							(tr!(lang, "post.stats.unknown_value"))
						}
					}
					span class="label" { " "(tr!(lang, "profile.stats.follows_label")) }
				}
				span {
					span class="data" {
						@if let Some(posts) = profile.posts_count {
							(posts)
						} @else {
							(tr!(lang, "post.stats.unknown_value"))
						}
					}
					span class="label" { " "(tr!(lang, "profile.stats.posts_label")) }
				}
			}
			blockquote {
				(description) // TODO: Need to find rich text manually here :(
			}
		}
		nav class="profile" {
			// TODO: CSS target tricks to hide the other tabs when one is selected; does lazy-img save us there?
			a id="posts" href="#posts" { (tr!(lang, "profile.section.posts")) }
			a id="media" href="#media" { (tr!(lang, "profile.section.media")) }
			a id="videos" href="#videos" { (tr!(lang, "profile.section.videos")) }
		}
		@match pinned {
			None => {} // no pin to show
			Some(Err(ref err)) => {
				p {
					(tr!(lang, "profile.error.load_pinned"))
					(err)
				}
			},
			Some(Ok(ref pinned)) => {
				(templates::post::regular(lang, true, false, &pinned.post))
			}
		}
		@if pinned.is_none() {
			article class="no-posts" {
				(maud::PreEscaped(include_str!("icons/weather-8.svg")))
				p { (tr!(lang, "profile.empty")) }
			}
		}
	};

	templates::base::base(env, meta, main)
}
