import { router } from '@inertiajs/react';
import type { BrandTheme } from '@/types/branding';

const STYLE_ID = 'brand-theme';
const FONTS_LINK_ID = 'brand-fonts';

/**
 * Mirrors the server-rendered `<style id="brand-theme">` and font link so the
 * theme follows client-side navigation (e.g. staff moving between a client
 * and their own pages).
 */
export function applyBrandTheme(theme: BrandTheme): void {
    let style = document.getElementById(STYLE_ID);

    if (!style) {
        style = document.createElement('style');
        style.id = STYLE_ID;
    }

    style.textContent = theme.css;
    // Re-append so the overrides stay after the app stylesheet Vite injects in dev.
    document.head.appendChild(style);

    let fontsLink = document.getElementById(
        FONTS_LINK_ID,
    ) as HTMLLinkElement | null;

    if (theme.fontsHref === null) {
        fontsLink?.remove();

        return;
    }

    if (!fontsLink) {
        fontsLink = document.createElement('link');
        fontsLink.id = FONTS_LINK_ID;
        fontsLink.rel = 'stylesheet';
        document.head.appendChild(fontsLink);
    }

    if (fontsLink.getAttribute('href') !== theme.fontsHref) {
        fontsLink.setAttribute('href', theme.fontsHref);
    }
}

export function initializeBrandTheme(): void {
    router.on('navigate', (event) => {
        const theme = event.detail.page.props.theme;

        if (theme) {
            applyBrandTheme(theme);
        }
    });
}
