(function () {
  'use strict';

  const tk = {
    bgPage: '#0f0f0f', bgCard: '#1a1a1a', bgCardAlt: '#141414', bgInput: '#111',
    bgHover: '#222', bgSunken: '#0a0a0a', bgOverlay: 'rgba(0,0,0,0.75)',
    border: '#2a2a2a', borderSubtle: '#1e1e1e',
    textPrimary: '#f5f5f5', textSecondary: '#aaaaaa', textMuted: '#666',
    textDisabled: '#444', accent: '#00ff00', accentText: '#000',
    error: '#ff4444',
  };

  const DEFAULT_VIDEO_WIDTH = 1920;
  const DEFAULT_VIDEO_HEIGHT = 1080;
  const MAX_VOLUME = 100;

  function generateId() { return 'ann-' + Date.now() + '-' + Math.random().toString(36).slice(2, 7); }

  // ── Stub window.api ──────────────────────────────────────────────────────────

  const api = {
    fetchReviewProjects: () => Promise.resolve({ projects: DEMO_REVIEW_PROJECTS }),
    getWatchUrl: (projectId) => Promise.resolve({ url: null }),
    claimReviewProject: (projectId) => Promise.resolve({ success: true }),
    saveAnnotation: (projectId, ann) => Promise.resolve({ success: true, id: generateId() }),
    deleteAnnotation: (projectId, annId) => Promise.resolve({ success: true }),
    submitReview: (projectId) => Promise.resolve({ success: true }),
    releaseProject: (projectId) => Promise.resolve({ success: true }),
  };

  // ── Demo data ────────────────────────────────────────────────────────────────

  const DEMO_REVIEW_PROJECTS = [
    {
      id: 'proj-1', title: 'Brand Launch Campaign v2',
      status: 'pending_review', clientName: 'Acme Corp',
      duration_seconds: 87, file_size_bytes: 245000000,
      urgency: 'urgent',
      thumbnail_url: 'https://picsum.photos/seed/vlsrv1/400/225',
      submitted_at: '2026-06-04T10:00:00Z',
      preferred_speciality: 'Commercial',
      creator_note: 'Please check the opening title sequence — timing feels off.',
    },
    {
      id: 'proj-2', title: 'Q2 Product Demo Reel',
      status: 'in_review', clientName: 'TechStart Inc',
      duration_seconds: 124, file_size_bytes: 512000000,
      urgency: 'soon',
      thumbnail_url: 'https://picsum.photos/seed/vlsrv2/400/225',
      submitted_at: '2026-06-03T09:30:00Z',
      reviewerName: 'You',
    },
    {
      id: 'proj-3', title: 'Social Media Reel Pack',
      status: 'pending_review', clientName: 'Fashion Brand',
      duration_seconds: 30, file_size_bytes: 98000000,
      urgency: null,
      thumbnail_url: 'https://picsum.photos/seed/vlsrv3/400/225',
      submitted_at: '2026-06-02T17:00:00Z',
      creator_note: 'Three 10s reels — transitions need to be snappier.',
    },
    {
      id: 'proj-4', title: 'Event Recap Highlights',
      status: 'pending_review', clientName: 'EventCo',
      duration_seconds: 215, file_size_bytes: 1200000000,
      urgency: null,
      thumbnail_url: 'https://picsum.photos/seed/vlsrv4/400/225',
      submitted_at: '2026-06-01T14:00:00Z',
    },
  ];

  const TOOLS = [
    { id: 'cursor', label: 'Cursor', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="m4 4 7.07 17 2.51-7.39L21 11.07z"/></svg> },
    { id: 'point', label: 'Point', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg> },
    { id: 'region', label: 'Region', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/></svg> },
    { id: 'range', label: 'Range', icon: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M8 3 4 7l4 4"/><path d="M4 7h16"/><path d="m16 21 4-4-4-4"/><path d="M20 17H4"/></svg> },
  ];

  const css = `
    .vls-ed-rv { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: ${tk.bgPage}; color: ${tk.textPrimary}; display: flex; flex-direction: column; width: 100%; height: 100%; min-height: 0; }
    .vls-ed-rv-topbar { display: flex; align-items: center; gap: 10px; padding: 10px 16px; background: ${tk.bgCard}; border-bottom: 1px solid ${tk.border}; flex-shrink: 0; }
    .vls-ed-rv-btn { padding: 6px 12px; border-radius: 5px; border: 1px solid ${tk.border}; background: ${tk.bgHover}; color: ${tk.textSecondary}; font-size: 12px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; }
    .vls-ed-rv-btn:hover { background: #2a2a2a; color: ${tk.textPrimary}; }
    .vls-ed-rv-btn.primary { background: ${tk.accent}; color: #000; border-color: ${tk.accent}; }
    .vls-ed-rv-btn.danger { border-color: rgba(255,68,68,0.4); color: ${tk.error}; background: transparent; }
    .vls-ed-rv-btn.active { border-color: rgba(0,255,0,0.5); color: ${tk.accent}; background: rgba(0,255,0,0.06); }
    .vls-ed-rv-btn:disabled { opacity: 0.4; cursor: not-allowed; }
    .vls-ed-rv-body { flex: 1; display: flex; min-height: 0; overflow: hidden; }
    .vls-ed-rv-main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
    .vls-ed-rv-video-area { flex: 1; background: #000; display: flex; align-items: center; justify-content: center; position: relative; min-height: 0; overflow: hidden; }
    .vls-ed-rv-sidebar { width: 300px; background: ${tk.bgCard}; border-left: 1px solid ${tk.border}; display: flex; flex-direction: column; min-height: 0; flex-shrink: 0; }
    .vls-ed-rv-controls { padding: 8px 14px; background: ${tk.bgCardAlt}; border-top: 1px solid ${tk.border}; display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
    .vls-ed-rv-timeline { padding: 10px 14px; background: ${tk.bgSunken}; border-top: 1px solid ${tk.border}; flex-shrink: 0; height: 72px; position: relative; cursor: pointer; }
    .vls-ed-rv-ann-item { padding: 10px 12px; border-bottom: 1px solid ${tk.border}; cursor: pointer; }
    .vls-ed-rv-ann-item:hover { background: ${tk.bgHover}; }
    .vls-ed-rv-ann-item.selected { background: rgba(0,255,0,0.05); border-left: 3px solid ${tk.accent}; }
    .vls-ed-rv-project-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; padding: 24px; }
    .vls-ed-rv-project-card { background: ${tk.bgCard}; border: 1px solid ${tk.border}; border-radius: 10px; overflow: hidden; cursor: pointer; transition: border-color 0.15s; }
    .vls-ed-rv-project-card:hover { border-color: rgba(0,255,0,0.3); }
    .vls-ed-rv-project-thumb { height: 160px; background: #111; display: flex; align-items: center; justify-content: center; position: relative; }
    .vls-ed-rv-project-info { padding: 14px; }
    .vls-ed-rv-badge { display: inline-block; padding: 2px 8px; border-radius: 12px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .vls-ed-rv-input { padding: 7px 10px; background: ${tk.bgInput}; border: 1px solid ${tk.border}; border-radius: 4px; color: ${tk.textPrimary}; font-size: 12px; outline: none; }
    .vls-ed-rv-input:focus { border-color: rgba(0,255,0,0.4); }
    .vls-ed-rv-submitted { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; gap: 16px; padding: 40px; text-align: center; }
  `;

  // ── Sub-components ────────────────────────────────────────────────────────────

  function StatusBadge({ status }) {
    const config = { pending_review: ['#f59e0b','Pending Review'], in_review: ['#3b82f6','In Review'], submitted: ['#22c55e','Submitted'], changes_requested: ['#ef4444','Changes Needed'] };
    const [color, label] = config[status] || ['#888', status];
    return <span className="vls-ed-rv-badge" style={{ background: color + '22', color, border: `1px solid ${color}44` }}>{label}</span>;
  }

  function formatDuration(secs) {
    const m = Math.floor(secs / 60);
    const s = Math.floor(secs % 60);
    return `${m}:${String(s).padStart(2, '0')}`;
  }

  function formatTimecode(s) {
    const safe = Math.max(0, s || 0);
    const m = Math.floor(safe / 60);
    const sec = Math.floor(safe % 60);
    const fr = Math.round((safe % 1) * 30);
    return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}:${String(fr).padStart(2, '0')}`;
  }

  // ── AnnotationOverlay ────────────────────────────────────────────────────────

  function AnnotationOverlay({ annotations, selectedId, activeTool, videoWidth, videoHeight, onAddAnnotation, onSelectAnnotation, currentTime }) {
    const [dragging, setDragging] = React.useState(null);
    const containerRef = React.useRef(null);

    const getRelativePos = (e) => {
      const rect = containerRef.current.getBoundingClientRect();
      return {
        x: (e.clientX - rect.left) / rect.width,
        y: (e.clientY - rect.top) / rect.height,
      };
    };

    const handleMouseDown = (e) => {
      if (activeTool === 'cursor') return;
      e.preventDefault();
      const pos = getRelativePos(e);
      if (activeTool === 'point') {
        onAddAnnotation({ type: 'point', x: pos.x, y: pos.y, time: currentTime, text: '' });
      } else if (activeTool === 'region') {
        setDragging({ startX: pos.x, startY: pos.y, currentX: pos.x, currentY: pos.y });
      }
    };

    const handleMouseMove = (e) => {
      if (!dragging) return;
      const pos = getRelativePos(e);
      setDragging(prev => ({ ...prev, currentX: pos.x, currentY: pos.y }));
    };

    const handleMouseUp = (e) => {
      if (!dragging) return;
      const pos = getRelativePos(e);
      const x = Math.min(dragging.startX, pos.x);
      const y = Math.min(dragging.startY, pos.y);
      const w = Math.abs(pos.x - dragging.startX);
      const h = Math.abs(pos.y - dragging.startY);
      if (w > 0.01 && h > 0.01) {
        onAddAnnotation({ type: 'region', x, y, width: w, height: h, time: currentTime, text: '' });
      }
      setDragging(null);
    };

    return (
      <div
        ref={containerRef}
        style={{ position: 'absolute', inset: 0, cursor: activeTool === 'cursor' ? 'default' : 'crosshair' }}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
      >
        {annotations.filter(a => a.type === 'point' || a.type === 'region').map(ann => {
          const isSelected = ann.id === selectedId;
          if (ann.type === 'point') {
            return (
              <div key={ann.id} onClick={() => onSelectAnnotation(ann.id)} style={{ position: 'absolute', left: `${ann.x * 100}%`, top: `${ann.y * 100}%`, transform: 'translate(-50%,-50%)', width: 20, height: 20, borderRadius: '50%', background: isSelected ? '#facc15' : 'rgba(250,204,21,0.7)', border: `2px solid ${isSelected ? '#fff' : 'rgba(255,255,255,0.5)'}`, cursor: 'pointer', boxShadow: isSelected ? '0 0 0 3px rgba(250,204,21,0.3)' : 'none', zIndex: 10 }} />
            );
          }
          if (ann.type === 'region') {
            return (
              <div key={ann.id} onClick={() => onSelectAnnotation(ann.id)} style={{ position: 'absolute', left: `${ann.x * 100}%`, top: `${ann.y * 100}%`, width: `${ann.width * 100}%`, height: `${ann.height * 100}%`, border: `2px solid ${isSelected ? '#22d3ee' : 'rgba(34,211,238,0.6)'}`, background: isSelected ? 'rgba(34,211,238,0.08)' : 'rgba(34,211,238,0.04)', cursor: 'pointer', zIndex: 10 }} />
            );
          }
          return null;
        })}
        {dragging && (
          <div style={{ position: 'absolute', left: `${Math.min(dragging.startX, dragging.currentX) * 100}%`, top: `${Math.min(dragging.startY, dragging.currentY) * 100}%`, width: `${Math.abs(dragging.currentX - dragging.startX) * 100}%`, height: `${Math.abs(dragging.currentY - dragging.startY) * 100}%`, border: '2px dashed #22d3ee', background: 'rgba(34,211,238,0.06)', pointerEvents: 'none', zIndex: 20 }} />
        )}
      </div>
    );
  }

  // ── Main component ────────────────────────────────────────────────────────────

  function ReviewerModeReal() {
    const [screen, setScreen] = React.useState('project_list');
    const [projects, setProjects] = React.useState(DEMO_REVIEW_PROJECTS);
    const [activeProject, setActiveProject] = React.useState(null);
    const [annotations, setAnnotations] = React.useState([]);
    const [selectedAnnotationId, setSelectedAnnotationId] = React.useState(null);
    const [activeTool, setActiveTool] = React.useState('cursor');
    const [isPlaying, setIsPlaying] = React.useState(false);
    const [currentTime, setCurrentTime] = React.useState(0);
    const [duration, setDuration] = React.useState(30);
    const [volume, setVolume] = React.useState(80);
    const [playbackRate, setPlaybackRate] = React.useState(1);
    const [showSpeedMenu, setShowSpeedMenu] = React.useState(false);
    const [reviewerName, setReviewerName] = React.useState('Demo Reviewer');
    const [isSubmitting, setIsSubmitting] = React.useState(false);
    const [submitted, setSubmitted] = React.useState(false);
    const [showLeaveDialog, setShowLeaveDialog] = React.useState(false);
    const [editingAnnotationId, setEditingAnnotationId] = React.useState(null);
    const [editingText, setEditingText] = React.useState('');
    const [rating, setRating] = React.useState(0);
    const [generalFeedback, setGeneralFeedback] = React.useState('');
    const [searchQuery, setSearchQuery] = React.useState('');
    const playIntervalRef = React.useRef(null);

    // Simulate playback
    React.useEffect(() => {
      if (isPlaying) {
        playIntervalRef.current = setInterval(() => {
          setCurrentTime(prev => {
            const next = prev + 0.1 * playbackRate;
            if (next >= duration) { setIsPlaying(false); return duration; }
            return next;
          });
        }, 100);
      } else {
        clearInterval(playIntervalRef.current);
      }
      return () => clearInterval(playIntervalRef.current);
    }, [isPlaying, playbackRate, duration]);

    const handleOpenProject = (project) => {
      api.claimReviewProject(project.id);
      setActiveProject(project);
      setDuration(project.duration_seconds || 30);
      setRating(0);
      setGeneralFeedback('');
      setAnnotations([]);
      setCurrentTime(0);
      setSubmitted(false);
      setScreen('editor_review');
    };

    const handleBack = () => {
      if (annotations.some(a => !a.savedToServer)) {
        setShowLeaveDialog(true);
      } else {
        setScreen('project_list');
        setActiveProject(null);
        setAnnotations([]);
      }
    };

    const confirmLeave = () => {
      api.releaseProject(activeProject?.id);
      setShowLeaveDialog(false);
      setScreen('project_list');
      setActiveProject(null);
      setAnnotations([]);
    };

    const handleAddAnnotation = (annData) => {
      const id = generateId();
      const newAnn = { ...annData, id, createdAt: new Date().toISOString(), reviewerName, savedToServer: false };
      setAnnotations(prev => [...prev, newAnn]);
      setSelectedAnnotationId(id);
      setEditingAnnotationId(id);
      setEditingText('');
      api.saveAnnotation(activeProject?.id, newAnn);
    };

    const handleDeleteAnnotation = (id) => {
      api.deleteAnnotation(activeProject?.id, id);
      setAnnotations(prev => prev.filter(a => a.id !== id));
      if (selectedAnnotationId === id) setSelectedAnnotationId(null);
    };

    const handleSaveAnnotationText = (id) => {
      setAnnotations(prev => prev.map(a => a.id === id ? { ...a, text: editingText, savedToServer: true } : a));
      setEditingAnnotationId(null);
    };

    const handleSubmitReview = () => {
      setIsSubmitting(true);
      api.submitReview(activeProject?.id).then(() => {
        setIsSubmitting(false);
        setSubmitted(true);
      });
    };

    const timelineAnnotations = React.useMemo(() => {
      return annotations.filter(a => a.type === 'range' || typeof a.time === 'number');
    }, [annotations]);

    const selectedAnnotation = annotations.find(a => a.id === selectedAnnotationId);

    // ── Project list screen ────────────────────────────────────────────────────

    if (screen === 'project_list') {
      const filtered = searchQuery ? projects.filter(p => p.title.toLowerCase().includes(searchQuery.toLowerCase()) || p.clientName?.toLowerCase().includes(searchQuery.toLowerCase())) : projects;
      return (
        <div className="vls-ed-rv" style={{ height: '100%' }}>
          <style>{css}</style>
          <div className="vls-ed-rv-topbar">
            <span style={{ fontWeight: 700, fontSize: 15, color: tk.accent }}>Review Portal</span>
            <div style={{ flex: 1 }} />
            <input className="vls-ed-rv-input" placeholder="Search projects..." value={searchQuery} onChange={e => setSearchQuery(e.target.value)} style={{ width: 200 }} />
            <span style={{ fontSize: 12, color: tk.textMuted }}>Reviewer: <strong style={{ color: tk.textPrimary }}>{reviewerName}</strong></span>
          </div>
          <div style={{ flex: 1, overflow: 'auto' }}>
            {filtered.length === 0 ? (
              <div style={{ padding: 40, textAlign: 'center', color: tk.textDisabled }}>No projects found</div>
            ) : (
              <div className="vls-ed-rv-project-grid">
                {filtered.map(project => (
                  <div key={project.id} className="vls-ed-rv-project-card" onClick={() => handleOpenProject(project)}>
                    <div className="vls-ed-rv-project-thumb">
                      {project.thumbnail_url ? (
                        <img src={project.thumbnail_url} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                      ) : (
                        <div style={{ fontSize: 28, opacity: 0.3 }}>▶</div>
                      )}
                      <div style={{ position: 'absolute', top: 8, left: 8, display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                        <StatusBadge status={project.status} />
                        {project.urgency === 'urgent' && <span className="vls-ed-rv-badge" style={{ background: 'rgba(255,82,82,0.2)', color: '#ff5252', border: '1px solid rgba(255,82,82,0.5)' }}>URGENT</span>}
                        {project.urgency === 'soon' && <span className="vls-ed-rv-badge" style={{ background: 'rgba(255,193,7,0.15)', color: '#ffc107', border: '1px solid rgba(255,193,7,0.4)' }}>SOON</span>}
                      </div>
                      <div style={{ position: 'absolute', bottom: 8, right: 8, background: 'rgba(0,0,0,0.8)', padding: '2px 6px', borderRadius: 4, fontSize: 11, color: '#fff', fontWeight: 600 }}>{formatDuration(project.duration_seconds || 0)}</div>
                    </div>
                    <div className="vls-ed-rv-project-info">
                      <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4 }}>{project.title}</div>
                      <div style={{ fontSize: 12, color: tk.textMuted, marginBottom: 6 }}>{project.clientName}</div>
                      {project.creator_note && (
                        <div style={{ fontSize: 11, color: tk.textSecondary, fontStyle: 'italic', background: tk.bgInput, border: `1px solid ${tk.borderSubtle}`, borderRadius: 4, padding: '5px 7px', marginBottom: 8, lineHeight: 1.5 }}>
                          "{project.creator_note}"
                        </div>
                      )}
                      <div style={{ display: 'flex', gap: 10, marginBottom: 8, flexWrap: 'wrap' }}>
                        {project.file_size_bytes && (
                          <span style={{ fontSize: 11, color: tk.textMuted }}>{project.file_size_bytes >= 1e9 ? `${(project.file_size_bytes/1e9).toFixed(1)} GB` : `${Math.round(project.file_size_bytes/1e6)} MB`}</span>
                        )}
                        {project.submitted_at && (
                          <span style={{ fontSize: 11, color: tk.textMuted }}>{new Date(project.submitted_at).toLocaleDateString()}</span>
                        )}
                        {project.preferred_speciality && (
                          <span style={{ fontSize: 11, color: '#ffc107' }}>{project.preferred_speciality}</span>
                        )}
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                        <button className="vls-ed-rv-btn primary" style={{ padding: '4px 10px', fontSize: 11 }} onClick={e => { e.stopPropagation(); handleOpenProject(project); }}>Review</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      );
    }

    // ── Submitted screen ───────────────────────────────────────────────────────

    if (submitted) {
      return (
        <div className="vls-ed-rv" style={{ height: '100%' }}>
          <style>{css}</style>
          <div className="vls-ed-rv-submitted">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke={tk.accent} strokeWidth="1.25">
              <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/>
              <polyline points="22 4 12 14.01 9 11.01"/>
            </svg>
            <div style={{ fontSize: 22, fontWeight: 700 }}>Review Submitted</div>
            <div style={{ color: tk.textMuted, fontSize: 14, maxWidth: 340 }}>Your review of <strong style={{ color: tk.textPrimary }}>{activeProject?.title}</strong> has been submitted successfully.</div>
            <div style={{ color: tk.textMuted, fontSize: 13 }}>{annotations.length} annotation{annotations.length !== 1 ? 's' : ''} included.</div>
            <button className="vls-ed-rv-btn primary" onClick={() => { setScreen('project_list'); setActiveProject(null); setAnnotations([]); setSubmitted(false); }}>Back to Projects</button>
          </div>
        </div>
      );
    }

    // ── Editor/review screen ───────────────────────────────────────────────────

    const progressPct = duration > 0 ? (currentTime / duration) * 100 : 0;

    return (
      <div className="vls-ed-rv" style={{ height: '100%' }}>
        <style>{css}</style>

        {/* Top bar */}
        <div className="vls-ed-rv-topbar">
          <button className="vls-ed-rv-btn" onClick={handleBack}>← Back</button>
          <span style={{ fontWeight: 700, fontSize: 14, marginLeft: 6 }}>{activeProject?.title}</span>
          <StatusBadge status={activeProject?.status} />
          <div style={{ flex: 1 }} />
          {/* Tools */}
          <div style={{ display: 'flex', gap: 4 }}>
            {TOOLS.map(tool => (
              <button key={tool.id} className={`vls-ed-rv-btn${activeTool === tool.id ? ' active' : ''}`} onClick={() => setActiveTool(tool.id)} title={tool.label} style={{ padding: '5px 8px' }}>
                {tool.icon}
              </button>
            ))}
          </div>
          <button className="vls-ed-rv-btn primary" onClick={handleSubmitReview} disabled={isSubmitting} style={{ marginLeft: 8 }}>
            {isSubmitting ? 'Submitting...' : 'Submit Review'}
          </button>
        </div>

        <div className="vls-ed-rv-body">
          {/* Main area */}
          <div className="vls-ed-rv-main">
            {/* Video area */}
            <div className="vls-ed-rv-video-area">
              <div style={{ width: '100%', height: '100%', position: 'relative' }}>
                <img
                  src={`https://picsum.photos/seed/${activeProject?.id || 'rvdemo'}/1280/720`}
                  alt="Video preview"
                  style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', userSelect: 'none', pointerEvents: 'none' }}
                  draggable={false}
                />
                {/* Play/pause overlay */}
                {!isPlaying && (
                  <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.2)', pointerEvents: 'none' }}>
                    <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'rgba(0,0,0,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}>
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="white"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                    </div>
                  </div>
                )}
                {/* Progress bar at bottom */}
                <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 3, background: 'rgba(0,0,0,0.4)' }}>
                  <div style={{ height: '100%', width: `${progressPct}%`, background: tk.accent, transition: 'width 0.1s linear' }} />
                </div>
                {/* Annotation overlay */}
                <AnnotationOverlay
                  annotations={annotations}
                  selectedId={selectedAnnotationId}
                  activeTool={activeTool}
                  videoWidth={DEFAULT_VIDEO_WIDTH}
                  videoHeight={DEFAULT_VIDEO_HEIGHT}
                  onAddAnnotation={handleAddAnnotation}
                  onSelectAnnotation={setSelectedAnnotationId}
                  currentTime={currentTime}
                />
              </div>
            </div>

            {/* Playback controls */}
            <div className="vls-ed-rv-controls">
              <button className="vls-ed-rv-btn" onClick={() => setCurrentTime(0)} title="Stop" style={{ padding: '5px 8px' }}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><rect x="3" y="3" width="18" height="18" rx="2"/></svg>
              </button>
              <button className="vls-ed-rv-btn" onClick={() => setIsPlaying(p => !p)} style={{ padding: '5px 12px' }}>
                {isPlaying ? (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>
                ) : (
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>
                )}
              </button>
              <span style={{ fontFamily: 'monospace', fontSize: 12, color: tk.accent, minWidth: 80 }}>{formatTimecode(currentTime)}</span>
              <span style={{ fontSize: 11, color: tk.textMuted }}>/ {formatTimecode(duration)}</span>
              <div style={{ flex: 1 }} />
              {/* Volume */}
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={tk.textMuted} strokeWidth="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"/></svg>
              <input type="range" min={0} max={MAX_VOLUME} value={volume} onChange={e => setVolume(Number(e.target.value))} style={{ width: 70, accentColor: '#00ff00', cursor: 'pointer' }} />
              {/* Speed */}
              <div style={{ position: 'relative' }}>
                <button className="vls-ed-rv-btn" onClick={() => setShowSpeedMenu(s => !s)} style={{ padding: '4px 8px', fontSize: 11 }}>{playbackRate}x</button>
                {showSpeedMenu && (
                  <div style={{ position: 'absolute', bottom: '100%', right: 0, background: tk.bgCard, border: `1px solid ${tk.border}`, borderRadius: 6, padding: 4, marginBottom: 4, zIndex: 100 }}>
                    {[0.25, 0.5, 0.75, 1, 1.25, 1.5, 2].map(r => (
                      <button key={r} className="vls-ed-rv-btn" onClick={() => { setPlaybackRate(r); setShowSpeedMenu(false); }} style={{ display: 'block', width: '100%', textAlign: 'center', padding: '4px 16px', fontSize: 12, ...(r === playbackRate ? { color: tk.accent } : {}) }}>{r}x</button>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* Timeline */}
            <div className="vls-ed-rv-timeline" onClick={e => {
              const rect = e.currentTarget.getBoundingClientRect();
              setCurrentTime(((e.clientX - rect.left) / rect.width) * duration);
            }}>
              <div style={{ position: 'absolute', inset: 0, paddingTop: 8, paddingBottom: 8, paddingLeft: 10, paddingRight: 10 }}>
                {/* Track background */}
                <div style={{ height: 6, background: tk.bgHover, borderRadius: 3, position: 'relative', marginTop: 18 }}>
                  {/* Progress */}
                  <div style={{ height: '100%', width: `${progressPct}%`, background: tk.accent, borderRadius: 3, transition: 'width 0.1s' }} />
                  {/* Playhead */}
                  <div style={{ position: 'absolute', top: -8, left: `${progressPct}%`, transform: 'translateX(-50%)', width: 2, height: 22, background: '#fff', borderRadius: 1 }} />
                </div>
                {/* Annotation markers */}
                {timelineAnnotations.map(ann => {
                  const timePct = duration > 0 ? (ann.time / duration) * 100 : 0;
                  const color = ann.type === 'point' ? '#facc15' : ann.type === 'range' ? '#fb923c' : '#22d3ee';
                  return (
                    <div key={ann.id} onClick={e => { e.stopPropagation(); setSelectedAnnotationId(ann.id); setCurrentTime(ann.time); }} style={{ position: 'absolute', top: 10, left: `calc(${timePct}% + 10px)`, transform: 'translateX(-50%)', width: 8, height: 8, borderRadius: '50%', background: color, cursor: 'pointer', border: ann.id === selectedAnnotationId ? '2px solid #fff' : '1px solid rgba(255,255,255,0.3)' }} />
                  );
                })}
              </div>
            </div>
          </div>

          {/* Sidebar */}
          <div className="vls-ed-rv-sidebar">
            <div style={{ padding: '10px 12px', borderBottom: `1px solid ${tk.border}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexShrink: 0 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: tk.accent }}>Annotations ({annotations.length})</span>
              {selectedAnnotationId && (
                <button className="vls-ed-rv-btn danger" style={{ padding: '3px 8px', fontSize: 10 }} onClick={() => handleDeleteAnnotation(selectedAnnotationId)}>Delete</button>
              )}
            </div>
            <div style={{ flex: 1, overflow: 'auto' }}>
              {annotations.length === 0 && (
                <div style={{ padding: 20, color: tk.textDisabled, fontSize: 12, textAlign: 'center', lineHeight: 1.5 }}>
                  Use the tools above to add annotations.<br /><br />
                  <strong style={{ color: tk.textMuted }}>Point</strong> — click on the video<br />
                  <strong style={{ color: tk.textMuted }}>Region</strong> — drag to highlight an area<br />
                  <strong style={{ color: tk.textMuted }}>Range</strong> — not yet available in web
                </div>
              )}
              {annotations.map(ann => {
                const isSelected = ann.id === selectedAnnotationId;
                const isEditing = editingAnnotationId === ann.id;
                const color = ann.type === 'point' ? '#facc15' : ann.type === 'range' ? '#fb923c' : '#22d3ee';
                return (
                  <div key={ann.id} className={`vls-ed-rv-ann-item${isSelected ? ' selected' : ''}`} onClick={() => { setSelectedAnnotationId(ann.id); setCurrentTime(ann.time); }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                      <span style={{ width: 8, height: 8, borderRadius: '50%', background: color, flexShrink: 0, display: 'inline-block' }} />
                      <span style={{ fontSize: 10, fontFamily: 'monospace', color: tk.textMuted }}>{formatTimecode(ann.time || 0)}</span>
                      <span style={{ fontSize: 10, color: tk.textMuted, textTransform: 'capitalize' }}>{ann.type}</span>
                    </div>
                    {isEditing ? (
                      <div onClick={e => e.stopPropagation()}>
                        <textarea
                          autoFocus
                          value={editingText}
                          onChange={e => setEditingText(e.target.value)}
                          placeholder="Add a note..."
                          rows={3}
                          style={{ width: '100%', boxSizing: 'border-box', background: tk.bgInput, border: `1px solid ${tk.border}`, borderRadius: 4, color: tk.textPrimary, fontSize: 12, padding: '5px 7px', resize: 'vertical', outline: 'none', fontFamily: 'inherit' }}
                        />
                        <div style={{ display: 'flex', gap: 4, marginTop: 4 }}>
                          <button className="vls-ed-rv-btn primary" style={{ flex: 1, padding: '4px', fontSize: 11 }} onClick={() => handleSaveAnnotationText(ann.id)}>Save</button>
                          <button className="vls-ed-rv-btn" style={{ flex: 1, padding: '4px', fontSize: 11 }} onClick={() => { setEditingAnnotationId(null); }}>Cancel</button>
                        </div>
                      </div>
                    ) : (
                      <div>
                        <div style={{ fontSize: 12, color: ann.text ? tk.textSecondary : tk.textDisabled, lineHeight: 1.4, marginBottom: isSelected ? 4 : 0 }}>{ann.text || <em>No note</em>}</div>
                        {isSelected && (
                          <button className="vls-ed-rv-btn" style={{ padding: '3px 8px', fontSize: 10, marginTop: 4 }} onClick={e => { e.stopPropagation(); setEditingAnnotationId(ann.id); setEditingText(ann.text || ''); }}>Edit note</button>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
            {/* Rating + general feedback */}
            <div style={{ padding: '10px 12px', borderTop: `1px solid ${tk.border}`, flexShrink: 0 }}>
              <div style={{ fontSize: 11, color: tk.textMuted, marginBottom: 6 }}>Overall Rating</div>
              <div style={{ display: 'flex', gap: 4, marginBottom: 10 }}>
                {[1,2,3,4,5].map(n => (
                  <button key={n} onClick={() => setRating(n)}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 20, padding: 0, lineHeight: 1,
                      color: n <= rating ? '#facc15' : tk.textDisabled,
                      filter: n <= rating ? 'drop-shadow(0 0 4px rgba(250,204,21,0.5))' : 'none',
                      transition: 'color 0.1s' }}>★</button>
                ))}
              </div>
              <div style={{ fontSize: 11, color: tk.textMuted, marginBottom: 4 }}>General feedback</div>
              <textarea
                value={generalFeedback}
                onChange={e => setGeneralFeedback(e.target.value)}
                placeholder="Overall notes for the creator..."
                rows={3}
                style={{ width: '100%', boxSizing: 'border-box', background: tk.bgInput, border: `1px solid ${tk.border}`, borderRadius: 4, color: tk.textPrimary, fontSize: 11, padding: '5px 7px', resize: 'vertical', outline: 'none', fontFamily: 'inherit' }}
              />
            </div>
            {/* Reviewer info */}
            <div style={{ padding: '10px 12px', borderTop: `1px solid ${tk.border}`, flexShrink: 0 }}>
              <div style={{ fontSize: 11, color: tk.textMuted, marginBottom: 4 }}>Reviewing as</div>
              <input className="vls-ed-rv-input" value={reviewerName} onChange={e => setReviewerName(e.target.value)} style={{ width: '100%', boxSizing: 'border-box' }} />
            </div>
          </div>
        </div>

        {/* Leave dialog */}
        {showLeaveDialog && (
          <div style={{ position: 'fixed', inset: 0, background: tk.bgOverlay, display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 999 }}>
            <div style={{ background: tk.bgCard, border: `1px solid ${tk.border}`, borderRadius: 10, padding: 24, width: 340, textAlign: 'center' }}>
              <div style={{ fontSize: 16, fontWeight: 700, marginBottom: 8 }}>Leave Review?</div>
              <div style={{ fontSize: 13, color: tk.textMuted, marginBottom: 20 }}>You have unsaved annotations. Are you sure you want to leave?</div>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
                <button className="vls-ed-rv-btn" onClick={() => setShowLeaveDialog(false)}>Stay</button>
                <button className="vls-ed-rv-btn danger" onClick={confirmLeave}>Leave anyway</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  }

  window.ReviewerModeReal = ReviewerModeReal;
})();
