---
import { sanitizeHref } from "../utils/url.js";

/**
 * Portable Text File block component
 *
 * Renders a downloadable file link from WordPress imports.
 */
export interface Props {
	node: {
		_type: "file";
		_key: string;
		url: string;
		filename?: string;
		showDownloadButton?: boolean;
	};
}

const { node } = Astro.props;
const { url: rawUrl, filename, showDownloadButton = true } = node ?? {};
const url = sanitizeHref(rawUrl);

// Extract filename from URL if not provided
const displayName = filename || url?.split("/").pop()?.split("?")[0] || "Download";
---

<div class="emdash-file">
	<a href={url} class="emdash-file__link" download={filename}>
		<svg
			class="emdash-file__icon"
			xmlns="http://www.w3.org/2000/svg"
			viewBox="0 0 24 24"
			fill="none"
			stroke="currentColor"
			stroke-width="2"
			stroke-linecap="round"
			stroke-linejoin="round"
		>
			<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
			<polyline points="14 2 14 8 20 8"></polyline>
		</svg>
		<span class="emdash-file__name">{displayName}</span>
	</a>
	{
		showDownloadButton && (
			<a href={url} class="emdash-file__download" download={filename} aria-label="Download file">
				<svg
					xmlns="http://www.w3.org/2000/svg"
					viewBox="0 0 24 24"
					fill="none"
					stroke="currentColor"
					stroke-width="2"
					stroke-linecap="round"
					stroke-linejoin="round"
				>
					<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
					<polyline points="7 10 12 15 17 10" />
					<line x1="12" y1="15" x2="12" y2="3" />
				</svg>
			</a>
		)
	}
</div>

<style>
	.emdash-file {
		display: flex;
		align-items: center;
		gap: 0.75rem;
		padding: 1rem;
		margin: 1rem 0;
		background-color: var(--emdash-file-bg, #f5f5f5);
		border-radius: 4px;
		border: 1px solid var(--emdash-file-border, #e0e0e0);
	}

	.emdash-file__link {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		flex: 1;
		text-decoration: none;
		color: var(--emdash-file-color, #333);
	}

	.emdash-file__link:hover {
		text-decoration: underline;
	}

	.emdash-file__icon {
		width: 1.5rem;
		height: 1.5rem;
		flex-shrink: 0;
		color: var(--emdash-file-icon-color, #666);
	}

	.emdash-file__name {
		font-weight: 500;
		word-break: break-all;
	}

	.emdash-file__download {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 2.5rem;
		height: 2.5rem;
		background-color: var(--emdash-button-bg, #0073aa);
		color: var(--emdash-button-color, #fff);
		border-radius: 4px;
		transition: background-color 0.2s;
	}

	.emdash-file__download:hover {
		background-color: var(--emdash-button-bg-hover, #005177);
	}

	.emdash-file__download svg {
		width: 1.25rem;
		height: 1.25rem;
	}
</style>
