import { usePage } from '@inertiajs/react';
import { useEffect } from 'react';

type Theme = { primary?: string; accent?: string; background?: string };

function validColor(value: unknown, fallback: string): string {
    return typeof value === 'string' && /^#[0-9a-f]{6}$/i.test(value) ? value : fallback;
}

function shade(hex: string, amount: number): string {
    const channel = (offset: number) => Math.max(0, Math.min(255, parseInt(hex.slice(offset, offset + 2), 16) + amount)).toString(16).padStart(2, '0');
    return `#${channel(1)}${channel(3)}${channel(5)}`;
}

function rgbChannels(hex: string): string {
    return [1, 3, 5].map((offset) => parseInt(hex.slice(offset, offset + 2), 16)).join(', ');
}

export function ThemeStyle() {
    const { navigation } = usePage<{
        navigation?: {
            companyName?: string | null;
            companyFaviconUrl?: string | null;
            theme?: Theme;
        };
    }>().props;
    const primary = validColor(navigation?.theme?.primary, '#52bb0b');
    const accent = validColor(navigation?.theme?.accent, '#197343');
    const background = validColor(navigation?.theme?.background, '#f5fbf1');
    const primaryDark = shade(primary, -32);

    useEffect(() => {
        const companyName = navigation?.companyName ?? 'Agus Setiawan Development';
        const syncTitle = () => {
            const currentTitle = document.title.trim();
            if (!currentTitle) return;
            const pageTitle = currentTitle.split(' - ')[0] || 'HRIS';
            const nextTitle = `${pageTitle} - ${companyName}`;
            if (currentTitle !== nextTitle) document.title = nextTitle;
        };
        syncTitle();
        const observer = new MutationObserver(syncTitle);
        observer.observe(document.head, { childList: true, characterData: true, subtree: true });

        const faviconUrl = navigation?.companyFaviconUrl;
        if (faviconUrl) {
            document
                .querySelectorAll<HTMLLinkElement>('link[rel="icon"], link[rel="apple-touch-icon"]')
                .forEach((icon) => {
                    icon.href = faviconUrl;
                    icon.removeAttribute('type');
                });
        }
        return () => observer.disconnect();
    }, [navigation?.companyFaviconUrl, navigation?.companyName]);

    return <style>{`:root{--primary:${primary};--primary-rgb:${rgbChannels(primary)};--primary-dark:${primaryDark};--primary-dark-rgb:${rgbChannels(primaryDark)};--primary-soft:${primary}18;--accent-blue:${accent};--accent-blue-rgb:${rgbChannels(accent)};--background:${background};--mobile-background:${background};}`}</style>;
}
