import { signal } from '@preact/signals';
export const toasts = signal([]);
let toastId = 0;
export function pushToast(message, kind = 'info', durationMs = 4000) {
    const id = ++toastId;
    toasts.value = [...toasts.value, { id, kind, message }];
    if (durationMs > 0) {
        setTimeout(() => {
            toasts.value = toasts.value.filter((t) => t.id !== id);
        }, durationMs);
    }
}
export function dismissToast(id) {
    toasts.value = toasts.value.filter((t) => t.id !== id);
}
const DEFAULT_ROUTE = { view: 'overview', memoryTab: 'drafts' };
export const currentRoute = signal(readHashRoute());
export function ensureDefaultRoute() {
    const route = readHashRoute();
    const expected = routeToHash(route);
    if (window.location.hash !== expected) {
        window.history.replaceState(null, '', expected);
    }
}
function readHashRoute() {
    const hash = window.location.hash.replace(/^#\/?/, '').split('?')[0];
    const [viewPart, memoryTabPart] = hash.split('/');
    const view = parseView(viewPart);
    if (!view) {
        return DEFAULT_ROUTE;
    }
    if (view === 'memory' && memoryTabPart && !parseMemoryTab(memoryTabPart)) {
        return DEFAULT_ROUTE;
    }
    return {
        view,
        memoryTab: view === 'memory' ? parseMemoryTab(memoryTabPart) ?? 'drafts' : 'drafts',
    };
}
function parseView(value) {
    if (value === 'overview' || value === 'session' || value === 'quality' || value === 'memory' || value === 'guide') {
        return value;
    }
    return undefined;
}
function parseMemoryTab(value) {
    if (value === 'drafts'
        || value === 'knowledge'
        || value === 'gaps'
        || value === 'proposals'
        || value === 'conflicts'
        || value === 'risky'
        || value === 'errors') {
        return value;
    }
    return undefined;
}
export function navigate(target, memoryTab) {
    const route = normalizeTarget(target, memoryTab);
    const nextHash = routeToHash(route);
    if (window.location.hash !== nextHash) {
        window.location.hash = nextHash;
    }
    currentRoute.value = route;
}
function routeToHash(route) {
    return route.view === 'memory' ? `#/memory/${route.memoryTab}` : `#/${route.view}`;
}
function normalizeTarget(target, memoryTab) {
    if (typeof target === 'string') {
        return { view: target, memoryTab: target === 'memory' ? memoryTab ?? 'drafts' : currentRoute.value.memoryTab };
    }
    return { view: target.view, memoryTab: target.view === 'memory' ? target.memoryTab ?? 'drafts' : currentRoute.value.memoryTab };
}
window.addEventListener('hashchange', () => {
    currentRoute.value = readHashRoute();
});
