package page

import "git.haelnorr.com/h/oslstats/internal/view/layout"
import "strconv"

// Original Error template (keep for backwards compatibility where needed)
templ Error(code int, err string, message string) {
	@ErrorWithDetails(code, err, message, "")
}

// Enhanced Error template with optional details section
templ ErrorWithDetails(code int, err string, message string, details string) {
	@layout.Global(err) {
		<div class="grid mt-24 left-0 right-0 top-0 bottom-0 place-content-center bg-base px-4">
			<div class="text-center max-w-2xl mx-auto">
				<h1 class="text-9xl text-text">{ strconv.Itoa(code) }</h1>
				<p class="text-2xl font-bold tracking-tight text-subtext1 sm:text-4xl">{ err }</p>
				// Always show the message from hws.HWSError.Message
				<p class="mt-4 text-subtext0">{ message }</p>
				// Conditionally show technical details in dropdown
				if details != "" {
					<div class="mt-8 text-left">
						<details class="bg-surface0 rounded-lg p-4 text-right">
							<summary class="text-left cursor-pointer text-subtext1 font-semibold select-none hover:text-text">
								Details
								<span class="text-xs text-subtext0 ml-2">(click to expand)</span>
							</summary>
							<div class="text-left mt-4 relative">
								<pre id="details" class="text-xs text-subtext0 font-mono whitespace-pre-wrap break-all bg-mantle p-4 rounded overflow-x-auto">{ details }</pre>
							</div>
							<button
								onclick="copyToClipboard('details')"
								id="copyButton"
								class="mt-2 bg-mauve text-crust px-3 py-1 rounded text-xs hover:bg-mauve/75 transition hover:cursor-pointer"
								title="Copy to clipboard"
							>
								Copy
							</button>
						</details>
					</div>
				}
				<a href="/" class="mt-6 inline-block rounded-lg bg-mauve px-5 py-3 text-sm text-crust transition hover:bg-mauve/75">
					Go to homepage
				</a>
			</div>
		</div>
		if details != "" {
			<script>
				function copyToClipboard(id) {
					var details = document.getElementById(id).innerText;
					var button = document.getElementById("copyButton");
					navigator.clipboard
						.writeText(details)
						.then(function () {
							button.innerText = "Copied!";
							setTimeout(function () {
								button.innerText = "Copy";
							}, 2000);
						})
						.catch(function (err) {
							console.error("Failed to copy:", err);
							button.innerText = "Failed";
						});
				}
			</script>
		}
	}
}
