import { useEffect, useRef } from 'react'; import { GameEngine, setEventDefinitions, EVENT_DEFINITIONS } from '@ai-tycoon/game-engine'; import type { TickNotification } from '@ai-tycoon/game-engine'; import { useGameStore } from '@/store'; export function useGameLoop(skip = false) { const engineRef = useRef(null); const companyName = useGameStore((s) => s.meta.companyName); const gameSpeed = useGameStore((s) => s.meta.gameSpeed); useEffect(() => { if (!companyName || skip) return; setEventDefinitions(EVENT_DEFINITIONS); const engine = new GameEngine({ getState: () => { const state = useGameStore.getState(); return { meta: state.meta, economy: state.economy, infrastructure: state.infrastructure, compute: state.compute, research: state.research, models: state.models, market: state.market, competitors: state.competitors, talent: state.talent, data: state.data, reputation: state.reputation, events: state.events, achievements: state.achievements, }; }, setState: (partial) => { const notifications = (partial as Record)['_notifications'] as TickNotification[] | undefined; delete (partial as Record)['_notifications']; useGameStore.getState().updateState(partial); if (notifications?.length) { const store = useGameStore.getState(); for (const n of notifications) { store.addNotification({ title: n.title, message: n.message, type: n.type, tick: store.meta.tickCount, }); } } }, }); engineRef.current = engine; engine.start(); return () => { engine.stop(); engineRef.current = null; }; }, [companyName, skip]); useEffect(() => { if (engineRef.current) { engineRef.current.setSpeed(gameSpeed); } }, [gameSpeed]); }