//! 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::{EmbedView, Post, ThreadViewPost},
};
use maud::{Markup, html};

pub fn thread(lang: Lang, env: &Env, thread: ThreadViewPost) -> Markup {
	let handle = format!("@{}", thread.post.author.handle);
	let display_name: &str = match &thread.post.author.display_name {
		None => &handle,
		Some(d) => d,
	};
	let created_at = thread.post.record.created_at;
	let timestamp = created_at.format("%+").to_string(); // ISO8601

	let profile_uri = format!("/profile/{}", thread.post.author.did);
	let canonical_url = env.base_url().join(&profile_uri).expect("valid url");
	let title = &format!(
		r#"{display_name}: "{}" - {}"#,
		thread.post.record.text,
		env.site_name()
	);

	let meta = templates::base::Meta {
		title,
		lang,
		og_type: templates::base::OgType::Article,
		content_locales: &thread.post.record.langs,
		profile_username: Some(&thread.post.author.handle),
		og_title: &format!("{display_name} ({handle})"),
		canonical_url: &canonical_url,
		og_description: thread.post.record.text.as_ref().into(),
		// TODO: Should our opengraph handle Embed::ExternalView too?
		og_images: match &thread.post.embed {
			Some(EmbedView::Images { images }) => &images
				.iter()
				.map(|i| OgMedia {
					content: &i.thumb,
					alt: &i.alt,
				})
				.collect::<Vec<_>>(),
			None | Some(_) => &[],
		},
		og_videos: match &thread.post.embed {
			Some(EmbedView::Video { playlist, alt, .. }) => Some(OgMedia {
				content: playlist,
				alt,
			}),
			None | Some(_) => None,
		},
		og_card: match &thread.post.embed {
			None => templates::base::OgCard::SummaryLargeImage,
			Some(_) => templates::base::OgCard::Summary,
		},
		og_published_time: Some(&timestamp),
		labels: &[("Posted At", &timestamp)],
	};
	let main = html! {
		h1 { (tr!(lang, "post.title")) }
		@if let Some(parent) = &thread.parent {
			@match parent {
				Post::ThreadView(p) => {
					(templates::post::regular(lang, false, true, &p.post))
				}
				Post::NotFound { .. } => "{not found}", // TODO: i18n
				Post::Blocked { .. } => "{blocked}",
			}
		}
		(templates::post::focus(lang, &thread))
		section {
			@if let Some(replies) = thread.post.reply_count {
				p {
					// TODO: Paginate instead of comparing with the current list (what we have loaded)
					@match usize::try_from(replies) {
						Err(_) => {
							// too many replies for usize comparison!! there must be more...
							a href="#" { "see more replies ->" } // TODO: i18n
						}
						Ok(replies) if replies > thread.replies.len() => {
							a href="#" { "see more replies ->" } // TODO: i18n
						}
						Ok(_) => "" // end of thread
					}
				}
			}
		}
	};

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