import { usePage } from '@inertiajs/react';
import { useLayoutEffect } from 'react';
import type { SharedProps } from '@/types';

/**
 * Applies the organisation's app colour scheme (Profile → App appearance) by overriding the
 * theme's CSS variables on <html>, so buttons, links, focus rings and highlights all follow it,
 * including dialogs and menus rendered outside the layout.
 */
export function useAppTheme() {
    const a = usePage<SharedProps>().props.appearance;
    useLayoutEffect(() => {
        if (!a) return;
        const root = document.documentElement.style;
        const vars: Record<string, string> = {
            '--color-accent': a.accent, '--color-accent-fill': a.accent_fill ?? a.accent, '--color-accent-hover': a.accent_hover, '--color-accent-soft': a.accent_soft,
            '--color-accent-ink': a.accent_ink, '--color-accent-ring': a.accent_ring, '--color-link': a.link, '--color-link-hover': a.link_hover,
        };
        Object.entries(vars).forEach(([k, v]) => root.setProperty(k, v));
        document.getElementById('nprogress')?.style.setProperty('--inertia-progress', a.accent);
    }, [a?.accent, a?.accent_fill, a?.accent_hover, a?.accent_soft, a?.accent_ink, a?.accent_ring, a?.link, a?.link_hover]);
    return a;
}

/** The app logo (or the default dot + "Spin Group Quotes" wordmark) for the top-left of the nav. */
export function AppBrand({ large = false }: { large?: boolean }) {
    const { appearance, appName } = usePage<SharedProps>().props;
    if (appearance?.logo_url) {
        return <img src={appearance.logo_url} alt={appName} className={large ? 'h-9 w-auto max-w-[220px] object-contain' : 'h-7 w-auto max-w-[180px] object-contain'} data-testid="app-logo" />;
    }
    return (
        <span className="flex items-center gap-2">
            <span className={`inline-block rounded-full bg-accent ${large ? 'h-7 w-7' : 'h-6 w-6'}`} aria-hidden />
            <span className={large ? 'whitespace-nowrap text-[17px] font-bold tracking-tight' : 'hidden whitespace-nowrap font-bold tracking-tight sm:inline'}>{appName}</span>
        </span>
    );
}
