import { useEffect, type ReactNode } from 'react';
import { useLocation } from 'react-router';
import { Sidebar } from './sidebar';
import { SipProvider } from '@/providers/sip-provider';
import { CallWidget } from '@/components/call-desk/call-widget';
import { useAuth } from '@/providers/auth-provider';

interface AppShellProps {
    children: ReactNode;
}

export const AppShell = ({ children }: AppShellProps) => {
    const { pathname } = useLocation();
    const { isCCAgent } = useAuth();

    // Heartbeat: keep agent session alive in Redis (CC agents only)
    useEffect(() => {
        if (!isCCAgent) return;

        const beat = () => {
            const token = localStorage.getItem('helix_access_token');
            if (token) {
                const apiUrl = import.meta.env.VITE_API_URL ?? 'http://localhost:4100';
                fetch(`${apiUrl}/auth/heartbeat`, {
                    method: 'POST',
                    headers: { Authorization: `Bearer ${token}` },
                }).catch(() => {});
            }
        };

        const interval = setInterval(beat, 5 * 60 * 1000);
        return () => clearInterval(interval);
    }, [isCCAgent]);

    return (
        <SipProvider>
            <div className="flex h-screen bg-primary">
                <Sidebar activeUrl={pathname} />
                <main className="flex flex-1 flex-col overflow-hidden">{children}</main>
                {isCCAgent && pathname !== '/' && pathname !== '/call-desk' && <CallWidget />}
            </div>
        </SipProvider>
    );
};
