import { useState, useEffect, useRef } from 'react'; import { Section } from '../types/Conversation'; export const useScrollTimer = (sections: Section[]) => { const [activeIndex, setActiveIndex] = useState(0); const timerRef = useRef(null); const startTimer = () => { if (sections.length <= 1) return; const nextSection = () => { setActiveIndex((prevIndex) => (prevIndex + 1) % sections.length); }; // Clear any existing timer if (timerRef.current !== null) { window.clearTimeout(timerRef.current); } // Set new timer based on current section's duration const currentDuration = sections[activeIndex]?.duration || 10; timerRef.current = window.setTimeout(nextSection, currentDuration * 1000); }; // Start/restart timer when activeIndex changes or component mounts useEffect(() => { startTimer(); // Cleanup timer on unmount return () => { if (timerRef.current !== null) { window.clearTimeout(timerRef.current); } }; }, [activeIndex, sections]); const goToSection = (index: number) => { if (index >= 0 && index < sections.length) { setActiveIndex(index); } }; return { activeIndex, goToSection }; };