/**
 * Animation Controller for Chunked Streaming
 */

export class ChunkedAnimationController {
    constructor() {
        this.animationState = {
            playing: false,
            currentTime: 0,
            startTime: 0,
            endTime: 0,
            speed: 1,
            lastFrameTime: 0
        };
        
        this.animationFrame = null;
        this.onTimeUpdate = null;
        this.onPlayStateChange = null;
    }

    /**
     * 애니메이션 시간 범위 설정
     */
    setTimeRange(startTime, endTime) {
        this.animationState.startTime = startTime;
        this.animationState.endTime = endTime;
        this.animationState.currentTime = startTime;
        
        // console.debug('Animation time range set:', { startTime, endTime });
    }

    /**
     * 애니메이션 재생/일시정지 토글
     */
    togglePlay() {
        this.animationState.playing = !this.animationState.playing;
        
        if (this.animationState.playing) {
            this.start();
        } else {
            this.stop();
        }
        
        this.onPlayStateChange?.(this.animationState.playing);
    }

    /**
     * 애니메이션 시작
     */
    start() {
        if (this.animationState.playing) {
            this.animationState.lastFrameTime = performance.now();
            this.animate();
        }
    }

    /**
     * 애니메이션 강제 시작 (디버깅용)
     */
    forceStart() {
        this.animationState.lastFrameTime = performance.now();
        this.animate();
    }

    /**
     * 애니메이션 중지
     */
    stop() {
        if (this.animationFrame) {
            cancelAnimationFrame(this.animationFrame);
            this.animationFrame = null;
        }
    }

    /**
     * 애니메이션 프레임 처리
     */
    animate() {
        if (!this.animationState.playing) return;
        
        const now = performance.now();
        const deltaTime = now - this.animationState.lastFrameTime;
        this.animationState.lastFrameTime = now;
        
        // 시간 범위 검증
        if (this.animationState.startTime === 0 || this.animationState.endTime === 0) {
            // 시간 범위가 설정되지 않으면 애니메이션 중지
            console.warn('Animation time range not set');
            this.animationState.playing = false;
            this.onPlayStateChange?.(false);
            return;
        }
        
        // 시간 업데이트
        this.animationState.currentTime += deltaTime * this.animationState.speed;
        
        // 루프 처리
        if (this.animationState.currentTime > this.animationState.endTime) {
            this.animationState.currentTime = this.animationState.startTime;
        }
        
        this.onTimeUpdate?.(this.animationState.currentTime);
        
        this.animationFrame = requestAnimationFrame(() => this.animate());
    }

    /**
     * 애니메이션 속도 설정
     */
    setSpeed(speed) {
        this.animationState.speed = speed;
    }

    /**
     * 현재 시간 설정 (타임라인 슬라이더에서 사용)
     */
    setCurrentTime(time) {
        this.animationState.currentTime = time;
        this.onTimeUpdate?.(this.animationState.currentTime);
    }

    /**
     * 슬라이더 진행률로 시간 설정
     */
    setTimeFromProgress(progress) {
        if (!this.animationState.startTime || !this.animationState.endTime) return;
        
        const time = this.animationState.startTime + 
                    (this.animationState.endTime - this.animationState.startTime) * (progress / 100);
        this.setCurrentTime(time);
    }

    /**
     * 현재 진행률 계산
     */
    getProgress() {
        if (!this.animationState.startTime || !this.animationState.endTime) return 0;
        
        return (this.animationState.currentTime - this.animationState.startTime) / 
               (this.animationState.endTime - this.animationState.startTime) * 100;
    }

    /**
     * 전체 초기화
     */
    reset() {
        this.stop();
        this.animationState = {
            playing: false,
            currentTime: 0,
            startTime: 0,
            endTime: 0,
            speed: 1,
            lastFrameTime: 0
        };
    }

    /**
     * 이벤트 핸들러 설정
     */
    setEventHandlers(handlers) {
        this.onTimeUpdate = handlers.onTimeUpdate;
        this.onPlayStateChange = handlers.onPlayStateChange;
    }

    /**
     * 재생 상태 반환
     */
    isPlaying() {
        return this.animationState.playing;
    }

    /**
     * 현재 시간 반환
     */
    getCurrentTime() {
        return this.animationState.currentTime;
    }

    /**
     * 시간 범위 반환
     */
    getTimeRange() {
        return {
            startTime: this.animationState.startTime,
            endTime: this.animationState.endTime
        };
    }

    /**
     * 애니메이션 속도 반환
     */
    getSpeed() {
        return this.animationState.speed;
    }

    /**
     * 타임라인 데이터 생성
     */
    getTimelineData() {
        const currentDate = new Date(this.animationState.currentTime);
        const startDate = new Date(this.animationState.startTime);
        const endDate = new Date(this.animationState.endTime);
        
        return {
            progress: this.getProgress(),
            currentDate: currentDate.toLocaleDateString('ko-KR', { 
                year: 'numeric', month: '2-digit', day: '2-digit' 
            }),
            currentTime: currentDate.toLocaleTimeString(),
            startTime: startDate.toLocaleTimeString(),
            endTime: endDate.toLocaleTimeString()
        };
    }

    /**
     * 애니메이션 상태 디버깅
     */
    debugState() {
        return {
            playing: this.animationState.playing,
            currentTime: new Date(this.animationState.currentTime).toISOString(),
            startTime: new Date(this.animationState.startTime).toISOString(),
            endTime: new Date(this.animationState.endTime).toISOString(),
            speed: this.animationState.speed,
            hasTimeRange: this.animationState.startTime !== 0 && this.animationState.endTime !== 0
        };
    }
}