import { useState, useEffect } from 'react';
import { useSidebar as useNewSidebar } from '../core/PageManager/SidebarProvider';
import { SidebarItem } from '../core/PageManager/pageInterface';
import { useLanguage } from '../providers/language/LanguageContext';

// Hook to get sidebar items from page configurations
export const useSidebarFromPageConfigs = (): { items: SidebarItem[]; isLoading: boolean } => {
    const { t } = useLanguage();
    const [refreshTrigger, setRefreshTrigger] = useState(0);
    
    // Use the new sidebar system
    const { sidebarItems: newSidebarItems, loading: newLoading, refreshSidebar } = useNewSidebar();
    
    // Listen for localStorage changes to refresh sidebar when sign-up status changes
    useEffect(() => {
        const handleStorageChange = (e: StorageEvent) => {
            if (e.key === 'speechSignUpData' || e.key === 'speechSignUpTimestamp') {
                setRefreshTrigger(prev => prev + 1);
            }
        };
        
        window.addEventListener('storage', handleStorageChange);
        
        // Also listen for changes in the same tab
        const handleCustomStorageChange = () => {
            setRefreshTrigger(prev => prev + 1);
        };
        
        // Custom event for same-tab changes
        window.addEventListener('speechSignUpChanged', handleCustomStorageChange);
        
        return () => {
            window.removeEventListener('storage', handleStorageChange);
            window.removeEventListener('speechSignUpChanged', handleCustomStorageChange);
        };
    }, []);
    
    // Refresh sidebar when trigger changes
    useEffect(() => {
        if (refreshTrigger > 0) {
            refreshSidebar();
        }
    }, [refreshTrigger, refreshSidebar]);
    
    // Map the items with translations
    const translatedItems = newSidebarItems.map(item => ({
        ...item,
        name: getTranslatedName(item.name, t)
    }));
    
    return { items: translatedItems, isLoading: newLoading };
};

// Helper function to get translated names
// This maps the page config names to translation keys
const getTranslatedName = (name: string, t: (key: string) => string): string => {
    const translationMap: Record<string, string> = {
        'Dashboard': t('nav.dashboard'),
        'Dateien': t('nav.files'),
        'Workflows': t('nav.workflows'),
        'Connections': t('nav.connections'),
        'Team Bereich': t('nav.team'),
        'Einstellungen': t('nav.settings'),
        'Test Sharepoint': t('nav.testSharepoint'),
        'Speech': t('nav.speech'),
        'Transkriptverwaltung': t('nav.transcript_management')
    };
    
    return translationMap[name] || name;
};

// Backward-compatible hook that returns just the items array
export const useSidebarItems = (): SidebarItem[] => {
    const { items } = useSidebarFromPageConfigs();
    return items;
};

export default useSidebarFromPageConfigs;
