import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { render } from '@testing-library/svelte';
import { setTheme } from '$lib/stores/theme.svelte';
import Probe from './__test__/Probe.svelte';

describe('applyMetaThemeColor', () => {
	beforeEach(() => {
		document.head.innerHTML = '';
	});

	afterEach(() => {
		document.head.innerHTML = '';
		// Reset to a known baseline; setTheme persists to localStorage,
		// but each test starts with head cleared anyway.
		setTheme('dark');
	});

	it('creates a meta[name="theme-color"]:not([media]) on mount with the dark hex', () => {
		setTheme('dark');
		render(Probe);
		const meta = document.querySelector<HTMLMetaElement>(
			'meta[name="theme-color"]:not([media])'
		);
		expect(meta).not.toBeNull();
		expect(meta!.content).toBe('#14171A');
	});

	it('updates the meta content when the resolved theme flips to light', async () => {
		setTheme('dark');
		render(Probe);
		setTheme('light');
		await Promise.resolve();
		const meta = document.querySelector<HTMLMetaElement>(
			'meta[name="theme-color"]:not([media])'
		);
		expect(meta).not.toBeNull();
		expect(meta!.content).toBe('#F8F5EE');
	});

	it('reuses an existing meta tag instead of stacking duplicates', async () => {
		setTheme('dark');
		render(Probe);
		setTheme('light');
		await Promise.resolve();
		setTheme('dark');
		await Promise.resolve();
		const metas = document.querySelectorAll('meta[name="theme-color"]:not([media])');
		expect(metas.length).toBe(1);
	});
});
