import { useRef, useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import type { GenerationTask } from '../types';
import { AmbientBackground } from './AmbientBackground';
import { ConfirmModal } from './ConfirmModal';
import { ImageLightbox } from './ImageLightbox';
import { useInputBarStore } from '../store/inputBar';
import { renderPromptWithMentions } from './GenerationCard';
import { tosThumb, rewriteTosUrl } from '../lib/api';
import styles from './VideoDetailModal.module.css';

interface Props {
  task: GenerationTask | null;
  onClose: () => void;
  onReEdit?: (id: string) => void;
  onRegenerate?: (id: string) => void;
  onDelete?: (id: string) => void;
  onToggleFavorite?: (id: string) => void;
  hideReEdit?: boolean;
  onPrev?: () => void;
  onNext?: () => void;
  hasPrev?: boolean;
  hasNext?: boolean;
}

export function VideoDetailModal({ task, onClose, onReEdit, onRegenerate, onDelete, onToggleFavorite, onPrev, onNext, hasPrev, hasNext, hideReEdit }: Props) {
  const navigate = useNavigate();
  const videoRef = useRef<HTMLVideoElement>(null);
  const videoContainerRef = useRef<HTMLDivElement>(null);
  const videoAreaRef = useRef<HTMLDivElement>(null);
  const progressRef = useRef<HTMLDivElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [showControls, setShowControls] = useState(true);
  const [volume, setVolume] = useState(1);
  const [isMuted, setIsMuted] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [showMoreMenu, setShowMoreMenu] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
  const [refMediaPreview, setRefMediaPreview] = useState<{ url: string; type: 'video' | 'audio' } | null>(null);
  const [fitSize, setFitSize] = useState<{ w: number; h: number } | null>(null);
  const [intrinsicRatio, setIntrinsicRatio] = useState<number | null>(null);
  const moreMenuRef = useRef<HTMLDivElement>(null);
  const hideTimerRef = useRef<ReturnType<typeof setTimeout>>();

  // Parse aspect ratio from task
  const arNum = useMemo(() => {
    const ar = task?.aspectRatio || '16:9';
    const parts = ar.split(':').map(Number);
    return (parts[0] && parts[1]) ? parts[0] / parts[1] : (intrinsicRatio || 16 / 9);
  }, [task?.aspectRatio, intrinsicRatio]);

  // Compute container size to fit aspect ratio within videoArea
  useEffect(() => {
    const el = videoAreaRef.current;
    if (!el || !task) return;
    const ro = new ResizeObserver(([entry]) => {
      const { width: aw, height: ah } = entry.contentRect;
      let w = aw;
      let h = w / arNum;
      if (h > ah) { h = ah; w = h * arNum; }
      setFitSize({ w, h });
    });
    ro.observe(el);
    return () => ro.disconnect();
  }, [arNum, task]);

  // ESC to close
  useEffect(() => {
    if (!task) return;
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', handleKey);
      document.body.style.overflow = '';
    };
  }, [task, onClose]);

  // Close more menu on outside click
  useEffect(() => {
    if (!showMoreMenu) return;
    const handleClick = (e: MouseEvent) => {
      if (moreMenuRef.current && !moreMenuRef.current.contains(e.target as Node)) {
        setShowMoreMenu(false);
      }
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, [showMoreMenu]);

  // Reset playback state when task changes (for prev/next navigation)
  useEffect(() => {
    if (!task) return;
    const v = videoRef.current;
    if (v) {
      v.pause();
      v.currentTime = 0;
    }
    setIsPlaying(false);
    setCurrentTime(0);
    setDuration(0);
    setShowMoreMenu(false);
    setIntrinsicRatio(null);
  }, [task?.id]);

  // Track fullscreen changes
  useEffect(() => {
    const handler = () => setIsFullscreen(!!document.fullscreenElement);
    document.addEventListener('fullscreenchange', handler);
    return () => document.removeEventListener('fullscreenchange', handler);
  }, []);

  const scheduleHideControls = useCallback(() => {
    if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
    setShowControls(true);
    hideTimerRef.current = setTimeout(() => {
      if (isPlaying) setShowControls(false);
    }, 3000);
  }, [isPlaying]);

  const togglePlay = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) {
      v.play().catch(() => {});
    } else {
      v.pause();
    }
  };

  const handleTimeUpdate = () => {
    const v = videoRef.current;
    if (v) setCurrentTime(v.currentTime);
  };

  const handleLoadedMetadata = () => {
    const v = videoRef.current;
    if (v) {
      setDuration(v.duration);
      if (v.videoWidth && v.videoHeight) {
        setIntrinsicRatio(v.videoWidth / v.videoHeight);
      }
    }
  };

  const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const v = videoRef.current;
    const bar = progressRef.current;
    if (!v || !bar) return;
    const rect = bar.getBoundingClientRect();
    const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
    v.currentTime = ratio * v.duration;
  };

  const toggleMute = () => {
    const v = videoRef.current;
    if (!v) return;
    const newMuted = !isMuted;
    v.muted = newMuted;
    setIsMuted(newMuted);
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = parseFloat(e.target.value);
    setVolume(val);
    if (videoRef.current) {
      videoRef.current.volume = val;
      videoRef.current.muted = val === 0;
    }
    setIsMuted(val === 0);
  };

  const toggleFullscreen = () => {
    const el = videoContainerRef.current;
    if (!el) return;
    if (document.fullscreenElement) {
      document.exitFullscreen().catch(() => {});
    } else {
      el.requestFullscreen().catch(() => {});
    }
  };

  const handleDownload = async () => {
    if (!task?.resultUrl) return;
    try {
      const res = await fetch(task.resultUrl);
      const blob = await res.blob();
      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = `airdrama-${task.id}.mp4`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
    } catch {
      const a = document.createElement('a');
      a.href = task.resultUrl;
      a.download = `airdrama-${task.id}.mp4`;
      a.click();
    }
  };

  const handleReEdit = () => {
    if (!task) return;
    if (onReEdit) {
      onReEdit(task.id);
      onClose();
    } else {
      // Fallback (asset page → reEdit): 跟 store/generation.ts:reEdit 对齐,
      // 用 setState 一次性批量灌入所有相关字段。
      // 关键 bug 修复:之前只 setPrompt 不写 editorHtml,PromptInput 渲染 editorHtml,
      // 所以编辑器是空的(只回填了图片素材)。
      const store = useInputBarStore.getState();
      store.reset();
      if (task.mode && store.mode !== task.mode) {
        store.switchMode(task.mode as 'universal' | 'keyframe');
      }
      const refs = (task.references || [])
        .filter(r => r.previewUrl && !r.isAssetRef)
        .map(r => ({
          id: r.id,
          type: r.type as 'image' | 'video' | 'audio',
          previewUrl: r.previewUrl,
          label: r.label,
          tosUrl: r.previewUrl,
        }));
      useInputBarStore.setState({
        prompt: task.prompt || '',
        editorHtml: task.editorHtml || task.prompt || '',
        model: (task.model as 'seedance_2.0' | 'seedance_2.0_fast') || 'seedance_2.0',
        aspectRatio: (task.aspectRatio as any) || '16:9',
        duration: task.duration ?? 5,
        resolution: task.resolution || '720p',
        references: refs,
        assetMentions: task.assetMentions || [],
      });
      onClose();
      navigate('/app');
    }
  };

  const handleRegenerate = () => {
    if (task && onRegenerate) {
      onRegenerate(task.id);
      onClose();
    }
  };

  const handleDelete = () => {
    setConfirmDelete(true);
    setShowMoreMenu(false);
  };

  const doDelete = () => {
    if (task && onDelete) {
      onDelete(task.id);
      onClose();
    }
    setConfirmDelete(false);
  };

  const formatTime = (s: number) => {
    const m = Math.floor(s / 60);
    const sec = Math.floor(s % 60);
    return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
  };

  if (!task) return null;

  const progress = duration > 0 ? (currentTime / duration) * 100 : 0;
  const modelLabel = task.model === 'seedance_2.0' ? 'AirDrama' : 'AirDrama Fast';
  const modeLabel = task.mode === 'universal' ? '全能参考' : '首尾帧';
  const effectiveVolume = isMuted ? 0 : volume;

  return (
    <div className={styles.overlay} onClick={onClose}>
      <AmbientBackground />
      <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
        {/* Left: Video player area — clicking blank space closes modal */}
        <div
          className={styles.playerSection}
          onClick={onClose}
          onMouseMove={scheduleHideControls}
          onMouseEnter={scheduleHideControls}
        >
          {/* Close button — top-right corner of player section */}
          <button className={styles.closeBtn} onClick={onClose}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>

          {/* Video area — centers the aspect-ratio-aware player */}
          <div ref={videoAreaRef} className={styles.videoArea}>
          <div
            ref={videoContainerRef}
            className={styles.videoContainer}
            style={fitSize ? { width: fitSize.w, height: fitSize.h } : undefined}
            onClick={(e) => { e.stopPropagation(); togglePlay(); }}
          >
            <video
              ref={videoRef}
              src={rewriteTosUrl(task.resultUrl)}
              poster={task.thumbnailUrl ? rewriteTosUrl(task.thumbnailUrl) : undefined}
              className={styles.video}
              onTimeUpdate={handleTimeUpdate}
              onLoadedMetadata={handleLoadedMetadata}
              onPlay={() => setIsPlaying(true)}
              onPause={() => setIsPlaying(false)}
              preload="auto"
            />

            {/* Full controls bar — inside rounded container */}
            <div
              className={`${styles.controls} ${showControls ? styles.controlsVisible : ''}`}
              onClick={(e) => e.stopPropagation()}
            >
              {/* Progress bar (full width, top of controls) */}
              <div
                ref={progressRef}
                className={styles.progressTrack}
                onClick={handleProgressClick}
              >
                <div className={styles.progressFill} style={{ width: `${progress}%` }} />
              </div>

              {/* Controls row */}
              <div className={styles.controlsRow}>
                {/* Play/Pause */}
                <button className={styles.controlBtn} onClick={togglePlay}>
                  {isPlaying ? (
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                      <rect x="6" y="4" width="4" height="16" rx="1" />
                      <rect x="14" y="4" width="4" height="16" rx="1" />
                    </svg>
                  ) : (
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                      <polygon points="5 3 19 12 5 21 5 3" />
                    </svg>
                  )}
                </button>

                {/* Time */}
                <span className={styles.timeDisplay}>
                  {formatTime(currentTime)} / {formatTime(duration)}
                </span>

                {/* Spacer */}
                <div className={styles.controlsSpacer} />

                {/* Volume */}
                <div className={styles.volumeControl}>
                  <button className={styles.controlBtn} onClick={toggleMute}>
                    {effectiveVolume === 0 ? (
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" fill="currentColor" stroke="none" />
                        <line x1="23" y1="9" x2="17" y2="15" />
                        <line x1="17" y1="9" x2="23" y2="15" />
                      </svg>
                    ) : effectiveVolume < 0.5 ? (
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" fill="currentColor" stroke="none" />
                        <path d="M15.54 8.46a5 5 0 0 1 0 7.07" />
                      </svg>
                    ) : (
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                        <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" fill="currentColor" stroke="none" />
                        <path d="M15.54 8.46a5 5 0 0 1 0 7.07" />
                        <path d="M19.07 4.93a10 10 0 0 1 0 14.14" />
                      </svg>
                    )}
                  </button>
                  <input
                    type="range"
                    min="0"
                    max="1"
                    step="0.01"
                    value={effectiveVolume}
                    onChange={handleVolumeChange}
                    className={styles.volumeSlider}
                  />
                </div>

                {/* Fullscreen */}
                <button className={styles.controlBtn} onClick={toggleFullscreen}>
                  {isFullscreen ? (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                      <path d="M8 3v3a2 2 0 0 1-2 2H3" />
                      <path d="M21 8h-3a2 2 0 0 1-2-2V3" />
                      <path d="M3 16h3a2 2 0 0 1 2 2v3" />
                      <path d="M16 21v-3a2 2 0 0 1 2-2h3" />
                    </svg>
                  ) : (
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                      <path d="M8 3H5a2 2 0 0 0-2 2v3" />
                      <path d="M21 8V5a2 2 0 0 0-2-2h-3" />
                      <path d="M3 16v3a2 2 0 0 0 2 2h3" />
                      <path d="M16 21h3a2 2 0 0 0 2-2v-3" />
                    </svg>
                  )}
                </button>
              </div>
            </div>
          </div>
          </div>

          {/* Prev/Next navigation arrows — outside video container */}
          {(onPrev || onNext) && (
            <div className={styles.navArrows}>
              <button
                className={`${styles.navArrowBtn} ${!hasPrev ? styles.navArrowDisabled : ''}`}
                onClick={(e) => { e.stopPropagation(); hasPrev && onPrev?.(); }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <polyline points="18 15 12 9 6 15" />
                </svg>
              </button>
              <button
                className={`${styles.navArrowBtn} ${!hasNext ? styles.navArrowDisabled : ''}`}
                onClick={(e) => { e.stopPropagation(); hasNext && onNext?.(); }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <polyline points="6 9 12 15 18 9" />
                </svg>
              </button>
            </div>
          )}
        </div>

        {/* Right: Info panel */}
        <div className={styles.infoPanel}>
          {/* Header: download left, favorite + more right */}
          <div className={styles.infoPanelHeader}>
            <button className={styles.downloadBtn} onClick={handleDownload}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
                <polyline points="7 10 12 15 17 10" />
                <line x1="12" y1="15" x2="12" y2="3" />
              </svg>
              下载
            </button>
            <div className={styles.headerIcons}>
              <button
                className={styles.iconBtn}
                title={task.isFavorited ? '取消收藏' : '收藏'}
                onClick={() => task && onToggleFavorite?.(task.id)}
              >
                <svg width="18" height="18" viewBox="0 0 24 24" fill={task.isFavorited ? '#faad14' : 'none'} stroke={task.isFavorited ? '#faad14' : 'currentColor'} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" />
                </svg>
              </button>
              <div className={styles.moreMenuWrap} ref={moreMenuRef}>
                <button className={styles.iconBtn} onClick={() => setShowMoreMenu(!showMoreMenu)}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                    <circle cx="12" cy="5" r="1.5" />
                    <circle cx="12" cy="12" r="1.5" />
                    <circle cx="12" cy="19" r="1.5" />
                  </svg>
                </button>
                {showMoreMenu && (
                  <div className={styles.moreDropdown}>
                    <button className={styles.moreDropdownItem} onClick={handleDelete}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                        <polyline points="3 6 5 6 21 6" />
                        <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
                      </svg>
                      删除
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Scrollable content: prompt + references */}
          <div className={styles.infoPanelContent}>
            <div className={styles.promptSection}>
              <div className={styles.sectionLabel}>视频提示词</div>
              <p className={styles.promptText}>{renderPromptWithMentions(task.prompt || '(无文字描述)', task.assetMentions || [], task.references)}</p>
            </div>

            {task.references.length > 0 && (
              <div className={styles.refSection}>
                <div className={styles.refGrid}>
                  {task.references.map((ref) => (
                    <div key={ref.id} className={styles.refItem}>
                      <div style={{ position: 'relative', width: 56, height: 56 }}>
                        {ref.type === 'video' && !ref.isAssetRef ? (
                          <video src={rewriteTosUrl(ref.previewUrl)} className={styles.refImg} muted style={{ cursor: 'pointer' }} onClick={() => ref.previewUrl && setRefMediaPreview({ url: ref.previewUrl, type: 'video' })} />
                        ) : ref.type === 'audio' ? (
                          <div className={styles.refAudioPlaceholder} style={{ cursor: 'pointer' }} onClick={() => ref.previewUrl && setRefMediaPreview({ url: ref.previewUrl, type: 'audio' })}>
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
                              <path d="M9 18V5l12-2v13" />
                              <circle cx="6" cy="18" r="3" />
                              <circle cx="18" cy="16" r="3" />
                            </svg>
                          </div>
                        ) : ref.previewUrl ? (
                          <img src={tosThumb(ref.previewUrl, 300)} alt={ref.label} className={styles.refImg} style={{ cursor: 'zoom-in' }} onClick={() => setLightboxSrc(ref.previewUrl)} onError={(e) => { (e.target as HTMLImageElement).style.display = 'none'; }} />
                        ) : (
                          <div className={styles.refAudioPlaceholder} style={{ fontSize: 12, color: 'var(--color-text-disabled)' }}>无预览</div>
                        )}
                        {ref.previewUrl && (
                          <a href={ref.previewUrl} download={ref.label} target="_blank" rel="noopener noreferrer"
                            style={{ position: 'absolute', bottom: 2, right: 2, width: 18, height: 18, borderRadius: 3, background: 'var(--color-shadow-modal)', color: 'var(--color-on-overlay)', fontSize: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', textDecoration: 'none' }}
                            onClick={(e) => e.stopPropagation()}
                          >↓</a>
                        )}
                      </div>
                      <span className={styles.refLabel}>{ref.label}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Re-edit button above info bar */}
          {!hideReEdit && <div style={{ padding: '16px 24px 12px' }}>
              <button className={styles.cardBtn} onClick={handleReEdit} style={{ width: '100%', justifyContent: 'center' }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                </svg>
                重新编辑
              </button>
            </div>}

          {/* Fixed bottom: info bar + actions card */}
          <div className={styles.infoPanelBottom}>
            <div className={styles.infoBar} style={{ flexWrap: 'wrap', rowGap: 6 }}>
              <span>{modeLabel}</span>
              <span className={styles.infoBarDot} />
              <span>{modelLabel}</span>
              <span className={styles.infoBarDot} />
              <span>{task.duration}s</span>
              <span className={styles.infoBarDot} />
              <span>{task.aspectRatio}</span>
              <span className={styles.infoBarDot} />
              <span>{task.resolution.toUpperCase()}</span>
              {(task.tokensConsumed ?? 0) > 0 && (
                <>
                  <span>{(task.tokensConsumed ?? 0).toLocaleString()} tokens</span>
                  <span className={styles.infoBarDot} />
                  <span>¥{(task.costAmount ?? 0).toFixed(2)}</span>
                </>
              )}
              {(task.seed ?? -1) > 0 && (
                <>
                  <span className={styles.infoBarDot} />
                  <span>种子值: {task.seed}</span>
                </>
              )}
            </div>

          </div>
        </div>

        <ConfirmModal
          open={confirmDelete}
          title="删除视频"
          message="确定要删除这条生成记录吗？此操作不可撤销。"
          confirmText="删除"
          danger
          onConfirm={doDelete}
          onCancel={() => setConfirmDelete(false)}
        />
        <ImageLightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} />
        {refMediaPreview && (
          <div style={{ position: 'fixed', inset: 0, background: 'var(--color-overlay-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 10002 }} onClick={() => setRefMediaPreview(null)}>
            <div style={{ position: 'relative', background: 'var(--color-bg-modal)', borderRadius: 12, padding: 24, border: '1px solid var(--color-border-modal)' }} onClick={(e) => e.stopPropagation()}>
              <button style={{ position: 'absolute', top: 8, right: 12, background: 'none', border: 'none', color: 'var(--color-text-tertiary)', fontSize: 16, cursor: 'pointer' }} onClick={() => setRefMediaPreview(null)}>✕</button>
              {refMediaPreview.type === 'video' ? (
                <video src={rewriteTosUrl(refMediaPreview.url)} controls autoPlay style={{ maxWidth: '80vw', maxHeight: '70vh', borderRadius: 8 }} />
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px 40px', color: 'var(--color-text-tertiary)' }}>
                  <div style={{ fontSize: 48, marginBottom: 16 }}>♫</div>
                  <audio src={rewriteTosUrl(refMediaPreview.url)} controls autoPlay style={{ width: 320 }} />
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
