/* 초 → MM:SS / HH:MM:SS */
function fmtTime(sec) {
  if (!isFinite(sec) || sec < 0) return '0:00';
  const h = Math.floor(sec / 3600);
  const m = Math.floor((sec % 3600) / 60);
  const s = Math.floor(sec % 60);
  if (h > 0) return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
  return `${m}:${String(s).padStart(2,'0')}`;
}

function VideoPlayerModal({ lecture, onClose }) {
  const { lang } = useT();
  const videoRef = useRef(null);
  const wrapRef  = useRef(null);
  const progRef  = useRef(null);

  const [playing,   setPlaying]   = useState(false);
  const [loading,   setLoading]   = useState(true);
  const [buffering, setBuffering] = useState(false);
  const [currentT,  setCurrentT]  = useState(0);
  const [duration,  setDuration]  = useState(0);
  const [buffered,  setBuffered]  = useState(0);
  const [volume,    setVolume]    = useState(1);
  const [muted,     setMuted]     = useState(false);
  const [isFS,      setIsFS]      = useState(false);
  const [seeking,   setSeeking]   = useState(false);
  const [videoErr,  setVideoErr]  = useState(false);
  const [errDetail, setErrDetail] = useState('');
  const [hoverSec,  setHoverSec]  = useState(null);

  /* 영상 URL: BASE_URL + folder + "/" + file */
  const videoSrc = nasUrl(lecture.folder, lecture.file);

  /* 이중언어 헬퍼 */
  const L = (field) => (typeof field === 'object' ? (field[lang] ?? field.ko) : field);

  /* body scroll lock */
  useEffect(() => {
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = ''; };
  }, []);

  /* fullscreen change */
  useEffect(() => {
    const onFS = () => setIsFS(!!document.fullscreenElement);
    document.addEventListener('fullscreenchange', onFS);
    return () => document.removeEventListener('fullscreenchange', onFS);
  }, []);

  /* keyboard shortcuts */
  useEffect(() => {
    const onKey = (e) => {
      if (['INPUT','TEXTAREA'].includes(e.target.tagName)) return;
      const v = videoRef.current;
      if (!v) return;
      if (e.key === ' ' || e.key === 'k') { e.preventDefault(); togglePlay(); }
      if (e.key === 'ArrowRight') { e.preventDefault(); v.currentTime = Math.min(v.duration||0, v.currentTime + 10); }
      if (e.key === 'ArrowLeft')  { e.preventDefault(); v.currentTime = Math.max(0, v.currentTime - 10); }
      if (e.key === 'm') toggleMute();
      if (e.key === 'f') toggleFS();
      if (e.key === 'Escape') onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [playing, muted]);

  /* video events */
  const onLoadedMeta = () => { const v=videoRef.current; if(v){setDuration(v.duration);setLoading(false);} };
  const onTimeUpdate = () => {
    const v = videoRef.current;
    if (!v || seeking) return;
    setCurrentT(v.currentTime);
    if (v.buffered.length > 0)
      setBuffered((v.buffered.end(v.buffered.length-1) / v.duration) * 100);
  };
  const onWaiting = () => setBuffering(true);
  const onCanPlay = () => { setLoading(false); setBuffering(false); };
  const onPlay    = () => setPlaying(true);
  const onPause   = () => setPlaying(false);
  const onEnded   = () => setPlaying(false);
  const onError   = (e) => {
    const v    = e.target;
    const code = v?.error?.code ?? -1;
    const LABELS = { 1:'ABORTED', 2:'NETWORK', 3:'DECODE', 4:'SRC_NOT_SUPPORTED' };
    const label  = LABELS[code] ?? 'UNKNOWN';
    /* 콘솔에 URL + 에러 코드만 간결하게 출력 */
    console.error(`[Video] ERR_${label} (code=${code})`, v?.error?.message ?? '', '|', videoSrc);
    const msg = code === 2 ? '네트워크 오류 — 서버 연결을 확인하세요'
              : code === 3 ? '디코딩 오류 — 파일이 손상됐을 수 있습니다'
              : code === 4 ? '파일을 찾을 수 없거나 형식을 지원하지 않습니다'
              : '영상을 불러올 수 없습니다';
    setErrDetail(msg);
    setVideoErr(true); setLoading(false); setBuffering(false);
  };

  /* controls */
  const togglePlay = useCallback(() => {
    const v = videoRef.current;
    if (!v) return;
    playing ? v.pause() : v.play().catch(()=>{});
  }, [playing]);

  const toggleMute = useCallback(() => {
    const v = videoRef.current;
    if (!v) return;
    v.muted = !v.muted; setMuted(v.muted);
  }, []);

  const onVolumeSlider = (e) => {
    const v = videoRef.current; if (!v) return;
    const val = parseFloat(e.target.value);
    v.volume = val; v.muted = val === 0;
    setVolume(val); setMuted(val === 0);
  };

  const toggleFS = useCallback(() => {
    const wrap = wrapRef.current; if (!wrap) return;
    document.fullscreenElement
      ? document.exitFullscreen().catch(()=>{})
      : wrap.requestFullscreen().catch(()=>{});
  }, []);

  /* seek */
  const calcPct = (e) => {
    const bar = progRef.current; if (!bar) return 0;
    const rect = bar.getBoundingClientRect();
    return Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
  };
  const seekTo = (e) => {
    const v = videoRef.current; if (!v||!v.duration) return;
    v.currentTime = calcPct(e) * v.duration; setCurrentT(v.currentTime);
  };
  const onProgMouseDown  = (e) => { e.preventDefault(); setSeeking(true); seekTo(e); };
  const onProgMouseMove  = (e) => {
    if (seeking) seekTo(e);
    if (duration > 0) setHoverSec(calcPct(e) * duration);
  };
  const onProgMouseLeave = () => { setSeeking(false); setHoverSec(null); };
  const onProgMouseUp    = () => setSeeking(false);

  const progress    = duration > 0 ? (currentT / duration) * 100 : 0;
  const volIcon     = muted || volume === 0 ? 'fa-volume-mute'
                    : volume < 0.5 ? 'fa-volume-down' : 'fa-volume-up';
  const showSpinner = (loading || buffering) && !videoErr;

  return (
    <div
      className="fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-2 sm:p-4"
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="bg-navy-900 rounded-2xl overflow-hidden w-full max-w-4xl shadow-2xl flex flex-col"
           style={{ maxHeight:'95vh' }}>

        {/* Player wrap */}
        <div ref={wrapRef}
             className={`video-player-wrap flex-shrink-0 ${!playing ? 'vp-paused' : ''}`}
             onMouseUp={onProgMouseUp}
             onMouseLeave={onProgMouseLeave}>

          {/* ── video element ── */}
          {!videoErr ? (
            <video
              key={videoSrc}
              ref={videoRef}
              poster={lecture.thumbnail}
              preload="auto"
              playsInline
              onLoadedMetadata={onLoadedMeta}
              onTimeUpdate={onTimeUpdate}
              onWaiting={onWaiting}
              onCanPlay={onCanPlay}
              onPlay={onPlay}
              onPause={onPause}
              onEnded={onEnded}
              onError={onError}
              style={{ width:'100%', maxHeight:'480px', objectFit:'contain', background:'#000', display:'block' }}
            >
              <source src={videoSrc} type="video/mp4" />
            </video>
          ) : (
            <div className="flex items-center justify-center bg-gray-950 text-white/50 text-sm"
                 style={{ height:'320px' }}>
              <div className="text-center px-6">
                <i className="fas fa-exclamation-triangle text-4xl mb-4 block text-amber-400"></i>
                <p className="font-semibold text-white/70 mb-1">{errDetail}</p>
                <p className="text-xs text-white/20 font-mono break-all mt-2">{videoSrc}</p>
                <button
                  onClick={() => { setVideoErr(false); setErrDetail(''); setLoading(true); }}
                  className="mt-4 px-4 py-1.5 rounded-full bg-white/10 hover:bg-white/20 text-white/70 text-xs transition"
                >
                  <i className="fas fa-redo mr-1"></i> 다시 시도
                </button>
              </div>
            </div>
          )}

          {/* ── Spinner (initial load + buffering) ── */}
          {showSpinner && (
            <div className="vp-spinner-overlay">
              <div style={{ textAlign:'center' }}>
                <div className="vp-spinner" style={{ margin:'0 auto 10px' }} />
                <span style={{ color:'rgba(255,255,255,0.55)', fontSize:'11px' }}>
                  {loading ? '영상 불러오는 중…' : '버퍼링 중…'}
                </span>
              </div>
            </div>
          )}

          {/* ── Big play button ── */}
          {!playing && !showSpinner && !videoErr && (
            <div className="vp-bigplay" onClick={togglePlay}>
              <div className="vp-bigplay-btn">
                <i className="fas fa-play text-white text-xl ml-1" />
              </div>
            </div>
          )}

          {/* ── Controls bar ── */}
          <div className="vp-controls">
            {/* Progress bar */}
            <div ref={progRef} className="vp-progress-wrap"
                 onMouseDown={onProgMouseDown}
                 onMouseMove={onProgMouseMove}>
              <div className="vp-buffered" style={{ width:`${buffered}%` }} />
              <div className="vp-progress-fill" style={{ width:`${progress}%` }}>
                <div className="vp-progress-thumb" />
              </div>
              {hoverSec !== null && duration > 0 && (
                <div style={{
                  position:'absolute', bottom:'14px',
                  left:`${(hoverSec/duration)*100}%`,
                  transform:'translateX(-50%)',
                  background:'rgba(15,23,42,0.92)',
                  color:'#fff', fontSize:'10px', padding:'2px 6px',
                  borderRadius:'4px', pointerEvents:'none', whiteSpace:'nowrap',
                }}>
                  {fmtTime(hoverSec)}
                </div>
              )}
            </div>

            {/* Bottom row */}
            <div className="flex items-center gap-2">
              {/* Play/Pause */}
              <button onClick={togglePlay} title={playing ? '일시정지 (K)' : '재생 (K)'}
                className="w-8 h-8 flex items-center justify-center text-white hover:text-white/70 transition-colors flex-shrink-0">
                <i className={`fas ${playing ? 'fa-pause' : 'fa-play'} text-sm ${!playing?'ml-px':''}`} />
              </button>
              {/* Mute */}
              <button onClick={toggleMute} title="음소거 (M)"
                className="w-8 h-8 flex items-center justify-center text-white hover:text-white/70 transition-colors flex-shrink-0">
                <i className={`fas ${volIcon} text-sm`} />
              </button>
              {/* Volume slider */}
              <input type="range" min="0" max="1" step="0.02"
                value={muted ? 0 : volume} onChange={onVolumeSlider}
                className="vp-volume-slider" title="음량" />
              {/* Time display */}
              <span className="text-white/60 text-xs tabular-nums flex-shrink-0 ml-1">
                {fmtTime(currentT)} <span className="text-white/25">/</span> {fmtTime(duration)}
              </span>
              <div className="flex-1" />
              {/* -10s */}
              <button onClick={() => { const v=videoRef.current; if(v) v.currentTime=Math.max(0,v.currentTime-10); }}
                title="-10초 (←)"
                className="flex items-center gap-0.5 text-white hover:text-white/70 transition-colors text-xs flex-shrink-0 px-1">
                <i className="fas fa-rotate-left text-xs" /><span>10</span>
              </button>
              {/* +10s */}
              <button onClick={() => { const v=videoRef.current; if(v) v.currentTime=Math.min(v.duration||0,v.currentTime+10); }}
                title="+10초 (→)"
                className="flex items-center gap-0.5 text-white hover:text-white/70 transition-colors text-xs flex-shrink-0 px-1">
                <span>10</span><i className="fas fa-rotate-right text-xs" />
              </button>
              {/* Fullscreen */}
              <button onClick={toggleFS} title="전체화면 (F)"
                className="w-8 h-8 flex items-center justify-center text-white hover:text-white/70 transition-colors flex-shrink-0">
                <i className={`fas ${isFS ? 'fa-compress' : 'fa-expand'} text-sm`} />
              </button>
            </div>
          </div>
        </div>{/* end video-player-wrap */}

        {/* Info panel — dark theme matching #0f172a */}
        <div className="border-t border-white/10 px-6 py-5 flex-shrink-0 overflow-y-auto" style={{ maxHeight:'220px' }}>
          <div className="flex items-start justify-between gap-4">
            <div className="min-w-0 flex-1">
              <span className="badge text-xs font-semibold px-2.5 py-1 rounded bg-white/10 text-white/80 mb-3 inline-block tracking-wide">
                {lecture.category}
              </span>
              <h2 className="font-gothic text-white text-lg font-bold leading-snug mb-1">
                {lecture.title}
              </h2>
              {lecture.description && (
                <p className="text-white/50 text-sm leading-relaxed mb-3">{lecture.description ?? ""}</p>
              )}
              <div className="flex flex-wrap gap-x-5 gap-y-1 text-xs text-white/40">
                <span><i className="fas fa-user mr-1.5" />{lecture.speaker ?? ""}</span>
                <span><i className="fas fa-university mr-1.5" />{lecture.affiliation ?? ""}</span>
                <span><i className="fas fa-calendar mr-1.5" />{lecture.date}</span>
                {lecture.duration && <span><i className="fas fa-clock mr-1.5" />{lecture.duration}</span>}
              </div>
              <p className="text-white/20 text-[10px] mt-3 hidden sm:block tracking-wide">
                <i className="fas fa-keyboard mr-1.5" />
                Space / K : 재생·정지 &nbsp;·&nbsp; &#x2190; / &#x2192; : 10초 &nbsp;·&nbsp; M : 음소거 &nbsp;·&nbsp; F : 전체화면 &nbsp;·&nbsp; Esc : 닫기
              </p>
            </div>
            <button onClick={onClose} title="닫기 (Esc)"
              className="flex-shrink-0 w-9 h-9 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center text-white/60 hover:text-white transition-colors">
              <i className="fas fa-times text-sm" />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

