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

/**
 * Portable Text Embed block component
 *
 * Renders embeds from YouTube, Vimeo, Twitter, etc.
 */
export interface Props {
	node: {
		_type: "embed";
		_key: string;
		url: string;
		provider?: string;
		html?: string;
		caption?: string;
	};
}

const { node } = Astro.props;

if (!node?.url) {
	return null;
}

const { url: rawUrl, provider, html, caption } = node;
const url = sanitizeHref(rawUrl);

const YOUTUBE_ID_PATTERN = /(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
const VIMEO_ID_PATTERN = /vimeo\.com\/(\d+)/;

// Extract video ID for common providers
function getYouTubeId(input: string): string | null {
	const match = input.match(YOUTUBE_ID_PATTERN);
	return match?.[1] || null;
}

function getVimeoId(input: string): string | null {
	const match = input.match(VIMEO_ID_PATTERN);
	return match?.[1] || null;
}

const youtubeId = getYouTubeId(url);
const vimeoId = getVimeoId(url);

// Check if this is a self-hosted video or audio
const isSelfHostedVideo = provider === "video";
const isSelfHostedAudio = provider === "audio";
---

<figure class="emdash-embed">
	{
		isSelfHostedVideo ? (
			<div class="emdash-embed-video">
				<video controls preload="metadata">
					<source src={url} />
					Your browser does not support the video element.
				</video>
			</div>
		) : isSelfHostedAudio ? (
			<div class="emdash-embed-audio">
				<audio controls preload="metadata">
					<source src={url} />
					Your browser does not support the audio element.
				</audio>
			</div>
		) : youtubeId ? (
			<div class="emdash-embed-video">
				<iframe
					src={`https://www.youtube.com/embed/${youtubeId}`}
					title="YouTube video"
					allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
					allowfullscreen
				/>
			</div>
		) : vimeoId ? (
			<div class="emdash-embed-video">
				<iframe
					src={`https://player.vimeo.com/video/${vimeoId}`}
					title="Vimeo video"
					allow="autoplay; fullscreen; picture-in-picture"
					allowfullscreen
				/>
			</div>
		) : html ? (
			<div class="emdash-embed-html" set:html={sanitizeContent(html)} />
		) : (
			<a href={url} target="_blank" rel="noopener noreferrer">
				{url}
			</a>
		)
	}
	{caption && <figcaption>{caption}</figcaption>}
</figure>

<style>
	.emdash-embed {
		margin: 1.5rem 0;
	}
	.emdash-embed-video {
		position: relative;
		padding-bottom: 56.25%; /* 16:9 */
		height: 0;
		overflow: hidden;
	}
	.emdash-embed-video iframe,
	.emdash-embed-video video {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		border: 0;
	}
	.emdash-embed-audio {
		width: 100%;
	}
	.emdash-embed-audio audio {
		width: 100%;
	}
	.emdash-embed figcaption {
		font-size: 0.875rem;
		color: var(--emdash-caption-color, var(--color-muted, #666));
		margin-top: 0.5rem;
		text-align: center;
	}
</style>
