import { ref, watch, type Component } from 'vue';
import { CommandLineIcon, SunIcon, CubeTransparentIcon } from '@heroicons/vue/24/outline';

export type Theme = 'titan' | 'eras' | 'loop42';

const STORAGE_KEY = 'hermes_theme';

/** Heroicon component per theme — used in nav, home page, and theme buttons */
export const THEME_ICONS: Record<Theme, Component> = {
    titan: CommandLineIcon,
    eras: SunIcon,
    loop42: CubeTransparentIcon,
};

/** Display name per theme */
export const THEME_NAMES: Record<Theme, string> = {
    titan: 'Titan',
    eras: 'ERAS',
    loop42: 'loop42',
};

/** Optional external logo per theme (e.g. customer branding). Null = use THEME_ICONS. */
export const THEME_LOGOS: Record<Theme, string | null> = {
    titan: null,
    eras: null,
    loop42: null,
};

// Map agent id → theme (unlisted agents default to 'titan')
export const AGENT_THEME_MAP: Record<string, Theme> = {
    eras: 'eras',
};

export function agentLogo(agentId: string): string | null {
    const t = AGENT_THEME_MAP[agentId] ?? 'titan';
    return THEME_LOGOS[t];
}

const stored = localStorage.getItem(STORAGE_KEY);
const theme = ref<Theme>(
    stored === 'workhorse' ? 'loop42' :   // migrate legacy name
    (stored as Theme) || 'loop42'
);

const THEME_FAVICONS: Record<Theme, string> = {
    titan: '/favicon-titan.svg',
    eras: '/favicon-eras.svg',
    loop42: '/favicon-loop42.svg',
};

function applyTheme(t: Theme) {
    if (t === 'titan') {
        document.documentElement.removeAttribute('data-theme');
    } else {
        document.documentElement.setAttribute('data-theme', t);
    }
    // Update favicon
    const link = document.querySelector('link[rel="icon"]') as HTMLLinkElement | null;
    if (link) link.href = THEME_FAVICONS[t] || '/favicon.svg';
}

// Apply on init
applyTheme(theme.value);

watch(theme, (t) => {
    applyTheme(t);
    localStorage.setItem(STORAGE_KEY, t);
});

export function useTheme() {
    function setTheme(t: Theme) { theme.value = t; }
    return { theme, setTheme };
}
