<!--
Phase 28 — right-pane for stand-alone messages (system mail, admin
notifications, and the caller's own paid-tier broadcasts). The pane
is read-only: no reply box, no per-recipient context. Soft-delete is
available for incoming rows that the caller has read.
-->
<script lang="ts">
	import { onMount } from "svelte";

	import { i18n } from "$lib/i18n/index.svelte";
	import { mailStore, type MailStandalone } from "$lib/mail-store.svelte";
	import { systemTitleKey } from "./system-titles";

	let { entry }: { entry: MailStandalone } = $props();

	let showOriginal = $state(false);

	const incoming = $derived(entry.message.recipientUserName !== "" && entry.message.senderKind !== "player");

	onMount(() => {
		if (incoming && entry.message.readAt === null) {
			void mailStore.markRead(entry.message.messageId);
		}
	});

	const displayBody = $derived(
		entry.message.translatedBody && !showOriginal
			? entry.message.translatedBody
			: entry.message.body,
	);
	const displaySubject = $derived(
		entry.message.translatedSubject && !showOriginal
			? entry.message.translatedSubject
			: entry.message.subject,
	);

	const headerKey = $derived.by(() => {
		const m = entry.message;
		if (m.senderKind === "system") {
			return systemTitleKey(m);
		}
		if (m.senderKind === "admin") {
			return "game.mail.admin.title" as const;
		}
		return "game.mail.broadcast.title" as const;
	});
</script>

<div class="standalone" data-testid="mail-system-item">
	<h3 class="title">{i18n.t(headerKey)}</h3>
	{#if displaySubject}
		<div class="subject">{displaySubject}</div>
	{/if}
	<p class="body">{displayBody}</p>
	{#if entry.message.translatedBody}
		<button
			type="button"
			class="toggle"
			onclick={() => (showOriginal = !showOriginal)}
		>
			{showOriginal ? i18n.t("game.mail.show_translation") : i18n.t("game.mail.show_original")}
		</button>
	{/if}
	{#if incoming}
		<button
			type="button"
			class="delete"
			onclick={() => mailStore.softDelete(entry.message.messageId)}
			data-testid="mail-system-delete"
		>
			{i18n.t("game.mail.delete_action")}
		</button>
	{/if}
</div>

<style>
	.standalone {
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
	}
	.title {
		margin: 0;
		font-size: 1rem;
		color: var(--color-warning);
	}
	.subject {
		font-weight: 700;
	}
	.body {
		margin: 0;
		white-space: pre-wrap;
	}
	.toggle,
	.delete {
		align-self: flex-start;
		font: inherit;
		padding: 0.2rem 0.5rem;
		border: 1px solid var(--color-border);
		background: transparent;
		color: inherit;
		border-radius: 4px;
		cursor: pointer;
		font-size: 0.8rem;
	}
</style>
