import React, { useCallback, useEffect, useRef, useState } from 'react';

const DURATION = 30;

function IconPlay() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
      <path d="M8 5v14l11-7z" />
    </svg>
  );
}

function IconPause() {
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
      <path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z" />
    </svg>
  );
}

export default function TrainingVideoPlayer({ completed, watchedSeconds, onProgress, onComplete, debugComplete }) {
  const [playing, setPlaying] = useState(false);
  const [current, setCurrent] = useState(watchedSeconds || 0);
  const timerRef = useRef(null);

  const stopTimer = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  useEffect(() => {
    const handleVisibility = () => {
      if (document.hidden) setPlaying(false);
    };
    document.addEventListener('visibilitychange', handleVisibility);
    return () => document.removeEventListener('visibilitychange', handleVisibility);
  }, []);

  useEffect(() => {
    if (!playing || completed) {
      stopTimer();
      return undefined;
    }
    timerRef.current = setInterval(() => {
      setCurrent((prev) => {
        const next = Math.min(prev + 1, DURATION);
        onProgress?.(next);
        if (next >= DURATION) {
          setPlaying(false);
          onComplete?.();
        }
        return next;
      });
    }, 1000);
    return () => stopTimer();
  }, [playing, completed, onProgress, onComplete, stopTimer]);

  useEffect(() => {
    if (debugComplete && !completed) {
      setCurrent(DURATION);
      onProgress?.(DURATION);
      onComplete?.();
    }
  }, [debugComplete, completed, onProgress, onComplete]);

  useEffect(() => {
    if (completed) setCurrent(DURATION);
  }, [completed]);

  const togglePlay = () => {
    if (completed) return;
    setPlaying((p) => !p);
  };

  const progress = (current / DURATION) * 100;
  const formatTime = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;

  return (
    <div className="dt-video-player">
      <div className="dt-video-screen">
        <div className="dt-video-overlay">
          <div style={{ fontSize: 18, fontWeight: 600 }}>氢能重卡安全驾驶培训</div>
          <div style={{ fontSize: 13, opacity: 0.8 }}>预计时长 30 秒</div>
          {!playing && !completed && (
            <button type="button" className="dt-video-play-btn" onClick={togglePlay} style={{ width: 56, height: 56, fontSize: 24 }}>
              <IconPlay />
            </button>
          )}
        </div>
      </div>
      <div className="dt-video-controls">
        <button type="button" className="dt-video-play-btn" onClick={togglePlay} disabled={completed}>
          {playing ? <IconPause /> : <IconPlay />}
        </button>
        <div className="dt-video-progress">
          <div className="dt-video-progress-fill" style={{ width: `${progress}%` }} />
        </div>
        <span style={{ color: '#fff', fontSize: 12, flexShrink: 0 }}>
          {formatTime(current)}/{formatTime(DURATION)}
        </span>
      </div>
    </div>
  );
}
