'use client';

// Video preview pane — composes the live `<video>` element, the letterbox
// background (color + optional blurred fill), the active subtitle overlay,
// and the playback transport bar.
//
// Heavy lifting lives in `./preview/*`:
//   findActiveVideo.ts — selects the topmost video clip at the playhead
//   usePlayback.ts     — rAF loop + <video> sync + ended handling

import { useMemo, useRef } from 'react';
import { Play, Pause, SkipBack, SkipForward } from 'lucide-react';
import { useEditor, selectActiveSubtitle, selectTimelineDuration } from '@/store/editor';
import { formatTimeShort } from '@/lib/media';
import { findActiveVideo } from './preview/findActiveVideo';
import { usePlayback } from './preview/usePlayback';
import type { SubtitleCue, SubtitlePosition, SubtitleStyle } from '@/types';

export function Preview() {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);

  const playing = useEditor((s) => s.playing);
  const setPlaying = useEditor((s) => s.setPlaying);
  const currentTime = useEditor((s) => s.currentTime);
  const setCurrentTime = useEditor((s) => s.setCurrentTime);
  const selection = useEditor((s) => s.selection);
  const tracks = useEditor((s) => s.tracks);
  const exportSettings = useEditor((s) => s.exportSettings);
  const subtitleStyle = useEditor((s) => s.subtitleStyle);
  const subtitle = useEditor(selectActiveSubtitle);
  const duration = useEditor(selectTimelineDuration);

  const activeVideo = useMemo(() => {
    const state = useEditor.getState();
    return findActiveVideo(state, currentTime);
  }, [currentTime, tracks, selection]);

  usePlayback({ videoRef, activeVideo, currentTime, playing });

  function togglePlay() {
    setPlaying(!useEditor.getState().playing);
  }
  function step(delta: number) {
    setCurrentTime(Math.max(0, currentTime + delta));
  }

  const bgColor = activeVideo?.background?.color ?? '#000000';
  const blur = activeVideo?.background?.blur ?? false;

  /** Merge per-cue style overrides onto the global subtitle style. */
  function resolveSubtitleStyle(cue?: SubtitleCue | null): SubtitleStyle | null {
    if (!cue) return null;
    return { ...subtitleStyle, ...(cue.style ?? {}) };
  }
  function subtitlePositionStyle(pos: SubtitlePosition): React.CSSProperties {
    if (pos === 'top') return { top: '8%', bottom: 'auto' };
    if (pos === 'middle') return { top: '50%', bottom: 'auto', transform: 'translateY(-50%)' };
    return { bottom: '8%', top: 'auto' };
  }

  return (
    <div className="h-full flex flex-col bg-capcut-black">
      <div
        ref={containerRef}
        className="flex-1 min-h-0 flex items-center justify-center relative overflow-hidden"
        style={{ backgroundColor: bgColor }}
      >
        {activeVideo ? (
          <div className="relative w-full h-full flex items-center justify-center">
            {blur && (
              <div
                className="absolute inset-0"
                style={{
                  backgroundImage: `url(${activeVideo.url})`,
                  backgroundSize: 'cover',
                  backgroundPosition: 'center',
                  filter: 'blur(24px) brightness(0.5)',
                  transform: 'scale(1.1)',
                }}
              />
            )}
            <video
              ref={videoRef}
              className="relative max-h-full max-w-full"
              playsInline
              muted={false}
              style={{ zIndex: 1 }}
            />
            {(() => {
              const ss = resolveSubtitleStyle(subtitle);
              if (!subtitle || !ss) return null;
              return (
                <div
                  className="absolute left-0 right-0 text-center pointer-events-none px-4"
                  style={{ ...subtitlePositionStyle(ss.position), zIndex: 2 }}
                >
                  <span
                    className="inline-block rounded"
                    style={{
                      fontFamily: ss.fontFamily,
                      fontSize: `${ss.fontSize}px`,
                      color: ss.color,
                      fontWeight: ss.bold ? 700 : 400,
                      backgroundColor: ss.background === 'none' ? 'transparent' : ss.background,
                      padding: ss.background === 'none' ? 0 : '6px 14px',
                      WebkitTextStroke: ss.outlineWidth > 0
                        ? `${ss.outlineWidth}px ${ss.outlineColor}`
                        : undefined,
                      textShadow: ss.outlineWidth > 0
                        ? undefined
                        : `0 0 ${Math.max(2, ss.outlineWidth)}px ${ss.outlineColor}`,
                      lineHeight: 1.3,
                      maxWidth: '90%',
                    }}
                  >
                    {subtitle.text}
                  </span>
                </div>
              );
            })()}
          </div>
        ) : (
          <div className="text-center text-capcut-muted max-w-sm px-6 animate-fade-in">
            <div className="mx-auto mb-4 w-20 h-20 rounded-full bg-gradient-to-br from-capcut-blue/20 to-capcut-purple/20 flex items-center justify-center ring-1 ring-capcut-border">
              <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="text-capcut-blue opacity-70">
                <polygon points="5 3 19 12 5 21 5 3" />
              </svg>
            </div>
            <p className="text-sm font-medium text-capcut-text">ลากไฟล์มาวางบนไทม์ไลน์</p>
            <p className="text-xs mt-1.5 opacity-70 leading-relaxed">
              หรือกดปุ่ม &quot;โหลดตัวอย่าง&quot; ที่แผงซ้ายเพื่อเริ่มต้นอย่างรวดเร็ว
            </p>
          </div>
        )}
      </div>

      <div className="h-14 border-t border-capcut-border bg-capcut-dark/80 glass flex items-center gap-2 px-4 shrink-0">
        <div className="flex items-center gap-1">
          <button
            type="button"
            onClick={() => setCurrentTime(0)}
            className="tip w-9 h-9 rounded-lg bg-transparent hover:bg-capcut-surface text-capcut-muted hover:text-capcut-text flex items-center justify-center transition-base"
            data-tip="ไปจุดเริ่มต้น"
          >
            <SkipBack size={15} />
          </button>
          <button
            type="button"
            onClick={() => step(-1)}
            className="tip h-9 px-2.5 rounded-lg bg-transparent hover:bg-capcut-surface text-capcut-muted hover:text-capcut-text flex items-center justify-center text-xs font-mono transition-base"
            data-tip="ย้อนกลับ 1 วินาที (J)"
          >
            −1s
          </button>
        </div>

        <button
          type="button"
          onClick={togglePlay}
          className="tip w-12 h-12 rounded-full bg-gradient-to-b from-capcut-blue to-capcut-blueDark hover:from-capcut-blueLight hover:to-capcut-blue text-white flex items-center justify-center transition-base shadow-glow-blue mx-1"
          data-tip={playing ? 'หยุดเล่น (Space)' : 'เล่น (Space)'}
        >
          {playing ? <Pause size={22} /> : <Play size={22} className="ml-0.5" />}
        </button>

        <div className="flex items-center gap-1">
          <button
            type="button"
            onClick={() => step(1)}
            className="tip h-9 px-2.5 rounded-lg bg-transparent hover:bg-capcut-surface text-capcut-muted hover:text-capcut-text flex items-center justify-center text-xs font-mono transition-base"
            data-tip="ไปข้างหน้า 1 วินาที (L)"
          >
            +1s
          </button>
          <button
            type="button"
            onClick={() => setCurrentTime(Math.max(0, duration))}
            className="tip w-9 h-9 rounded-lg bg-transparent hover:bg-capcut-surface text-capcut-muted hover:text-capcut-text flex items-center justify-center transition-base"
            data-tip="ไปจุดสิ้นสุด"
          >
            <SkipForward size={15} />
          </button>
        </div>

        <div className="w-px h-6 bg-capcut-border mx-2" />

        <div className="text-xs font-mono px-3 py-1 bg-capcut-surface rounded-md border border-capcut-border/60">
          <span className="text-capcut-text font-semibold">{formatTimeShort(currentTime)}</span>
          <span className="mx-1.5 text-capcut-subtle">/</span>
          <span className="text-capcut-muted">{formatTimeShort(duration)}</span>
        </div>

        <div className="flex-1" />

        <div className="hidden lg:flex items-center gap-1.5 text-[11px]">
          <span className="px-2 py-1 bg-capcut-surface rounded-md border border-capcut-border/60 font-mono text-capcut-muted">
            {exportSettings.width}×{exportSettings.height}
          </span>
          <span className="px-2 py-1 bg-capcut-surface rounded-md border border-capcut-border/60 font-mono text-capcut-muted">
            {exportSettings.fps}fps
          </span>
          <div
            className="w-5 h-5 rounded border border-capcut-border/60"
            style={{ backgroundColor: bgColor }}
            title={`พื้นหลัง ${bgColor}`}
          />
        </div>
      </div>
    </div>
  );
}