<!-- @component
MetaPixel integrates the Meta (Facebook) Pixel into your Svelte application,
allowing you to track page views and custom events while respecting user consent
for tracking. The component manages the lifecycle of the Meta Pixel script and
PixelControl interface.
-->

<script lang="ts">
	import { onMount } from 'svelte';

	import type { TrackingManager } from '../tracking.svelte.ts';
	import { onNavigate } from '$app/navigation';
	import { PixelControl, type PixelControlOptions } from './pixel-control.ts';
	import { ensureFbc, type EnsureFbcOptions } from './fbc.ts';

	interface Props {
		/**
		 * Tracking manager to handle user consent for tracking. If omitted
		 * tracking is disabled by default until consent is granted via
		 * PixelControl.grantConsent().
		 */
		trackingManager?: TrackingManager;

		/** Meta Pixel ID */
		pixelID: string;

		/** Meta Pixel Options */
		pixelOptions?: PixelControlOptions;

		/**
		 * Controls whether page views are automatically tracked by this
		 * component (default: true).
		 */
		autoPageView?: boolean;
	}

	let { pixelID, pixelOptions, autoPageView = true, trackingManager }: Props = $props();

	let pixel = $state<PixelControl | null>(null);

	const fbcOptions: EnsureFbcOptions = {
		sameSite: 'Lax'
	};

	onMount(() => {
		if (!trackingManager) {
			throw new Error('MetaPixel component requires a TrackingManager to manage consent.');
		}
		pixel = PixelControl.initialize(trackingManager, pixelID, pixelOptions);

		trackingManager.runWithConsent(() => {
			if (autoPageView && pixel) {
				pixel.pageView();
				ensureFbc(fbcOptions);
			}
		});
	});

	onNavigate(() => {
		trackingManager?.runWithConsent(() => {
			if (autoPageView && pixel) {
				pixel.pageView();
				ensureFbc(fbcOptions);
			}
		});
	});

	export const getPixelControl = (): PixelControl => {
		if (!pixel) {
			throw new Error('MetaPixel component has not been initialized yet, wait for onMount.');
		}
		return pixel;
	};
</script>
