import { browser } from '$app/environment';
import { fetchConfig } from './api';
import {
	FALLBACK_SITE_URL,
	FALLBACK_WEDDING_DATE,
	FALLBACK_CEREMONY_TIME,
	FALLBACK_RSVP_BY_DATE,
	FALLBACK_VENUE_NAME,
	FALLBACK_VENUE_ADDRESS,
	FALLBACK_RSVP_PHONE
} from './config';

export function createWeddingInfo() {
	let siteUrl = $state(FALLBACK_SITE_URL);
	let date = $state(new Date(FALLBACK_WEDDING_DATE));
	let ceremonyTime = $state(FALLBACK_CEREMONY_TIME);
	let rsvpByDate = $state(new Date(FALLBACK_RSVP_BY_DATE));
	let venueName = $state(FALLBACK_VENUE_NAME);
	let venueAddress = $state(FALLBACK_VENUE_ADDRESS);
	let rsvpPhone = $state(FALLBACK_RSVP_PHONE);

	$effect(() => {
		if (!browser) return;
		fetchConfig()
			.then((config) => {
				siteUrl = config.siteUrl;
				date = new Date(config.weddingDate);
				ceremonyTime = config.ceremonyTime;
				rsvpByDate = new Date(config.rsvpByDate);
				venueName = config.venueName;
				venueAddress = config.venueAddress;
				rsvpPhone = config.rsvpPhone;
			})
			.catch(() => {
				// keep the fallback values; the API may not be running yet in dev
			});
	});

	return {
		get siteUrl() {
			return siteUrl;
		},
		get date() {
			return date;
		},
		get ceremonyTime() {
			return ceremonyTime;
		},
		get rsvpByDate() {
			return rsvpByDate;
		},
		get venueName() {
			return venueName;
		},
		get venueAddress() {
			return venueAddress;
		},
		get rsvpPhone() {
			return rsvpPhone;
		}
	};
}

const dayDateFormatter = new Intl.DateTimeFormat('en-GB', {
	weekday: 'long',
	day: 'numeric',
	month: 'long',
	year: 'numeric'
});

export function formatFullDate(date: Date): string {
	return dayDateFormatter.format(date);
}
