File size: 24,389 Bytes
426a0c6
 
7550cfb
426a0c6
 
 
 
 
e05dd0a
426a0c6
 
697a6fa
 
426a0c6
 
 
 
 
 
 
 
697a6fa
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7550cfb
 
 
 
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7550cfb
 
c5e9fa0
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7550cfb
426a0c6
 
 
 
 
 
 
 
 
 
7550cfb
 
 
 
 
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e05dd0a
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7550cfb
 
426a0c6
 
 
7550cfb
 
 
 
 
 
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7550cfb
 
426a0c6
 
 
 
 
 
 
 
7550cfb
426a0c6
 
 
 
 
 
 
 
 
 
7550cfb
426a0c6
 
 
7550cfb
426a0c6
 
7550cfb
426a0c6
 
697a6fa
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
697a6fa
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
697a6fa
 
 
 
 
 
 
 
 
 
 
 
 
426a0c6
697a6fa
 
 
e05dd0a
697a6fa
 
 
e05dd0a
697a6fa
 
e05dd0a
 
 
426a0c6
 
697a6fa
 
 
 
 
 
 
426a0c6
 
 
 
 
 
 
697a6fa
 
426a0c6
 
697a6fa
 
426a0c6
697a6fa
426a0c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39d6a03
 
 
426a0c6
 
 
 
 
 
 
 
 
 
 
 
7550cfb
426a0c6
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import {SpatialAudio, parseFOAWav, clamp, wrapYaw} from './lib/foa.js';
import {Panorama} from './lib/panorama.js';
import {letters, newSession, canAnswer, submission, validSession, skipRemainingAudio} from './model.js';

const $ = id => document.getElementById(id);
const storageKey = 'panogen-mos-random-four-v1';
const video = $('video'), audio = new SpatialAudio();
let study, session, panorama, trial, draft, active, request, ready = false, saving = false;
let yaw = 0, pitch = 0, fov = 110, generation = 0, playbackGeneration = 0;
let lastMediaTime = null, lastPersist = 0, lastSync = 0, scrubbing = false, resumeAfterScrub = false;
let audioCache = new Map();
const heldRotationKeys = new Set();
let lastFrameTime = null;
const url = asset => '/media/' + encodeURIComponent(asset);

function error(message) { $('error').textContent = message; $('error').hidden = !message; }
function persist() {
  try { localStorage.setItem(storageKey, JSON.stringify(session)); }
  catch { $('save-status').textContent = 'Browser backup is unavailable. Your ratings will still be saved to the study server when you continue.'; }
}
function show(screen) {
  stopKeyboardRotation();
  for (const name of ['welcome', 'trial-screen', 'complete-screen']) $(name).hidden = name !== screen;
  window.scrollTo({top: 0, behavior: 'instant'});
}
function updatePose() {
  yaw = wrapYaw(yaw); pitch = clamp(pitch, -85, 85); fov = clamp(fov, 35, 120);
  if (draft) draft.pose = {yaw, pitch, fov};
  audio.setPose(yaw, pitch);
  $('pose-label').textContent = `${Math.round(yaw)}° yaw · ${Math.round(pitch)}° pitch · ${Math.round(fov)}° field of view`;
}
function applyGain() {
  audio.setGain((active?.gain_db || 0) + session.volume_db);
  $('volume').value = session.volume_db;
  $('volume-value').textContent = session.volume_db + ' dB';
}
function pause() {
  playbackGeneration++;
  video.pause(); audio.stop(); lastMediaTime = null;
  $('play').textContent = '▶ Play'; $('play').setAttribute('aria-label', 'Play current option');
}
async function play() {
  if (!ready) return;
  const token = ++playbackGeneration;
  try {
    if (trial.kind === 'audio') {
      await audio.initialize();
      await audio.context.resume();
    }
    if (token !== playbackGeneration || !ready) return;
    if (video.currentTime >= trial.duration - 0.02) video.currentTime = 0;
    await video.play();
    if (token !== playbackGeneration || !ready) return;
    $('play').textContent = 'Ⅱ Pause'; $('play').setAttribute('aria-label', 'Pause current option');
    $('playback-status').textContent = trial.kind === 'audio' ? 'Playing · sound follows your view' : 'Playing · silent video';
  } catch (e) { if (token === playbackGeneration) { pause(); error('Playback could not start: ' + e.message); } }
}
function syncAudio() {
  if (!ready || video.paused || video.seeking || video.readyState < 3 || trial.kind !== 'audio') return;
  audio.start(video.currentTime);
  if (audio.source) audio.source.stop(audio.context.currentTime + Math.max(0, trial.duration - video.currentTime));
}
function finishClip() {
  pause();
  if ($('loop').checked && ready) { video.currentTime = 0; play(); }
  else $('playback-status').textContent = 'Clip finished · replay or compare another option';
}

function updateChoices() {
  if (!trial) return;
  const assignment = session.option_order[trial.id];
  let played = 0;
  for (const id of assignment) {
    const row = $('choice-' + id), hasPlayed = (draft.reviewed_seconds[id] || 0) > 0;
    played += Number(hasPlayed);
    row.classList.toggle('active', active?.id === id);
    const rated = trial.questions.filter(q => Number.isInteger(draft.ratings[id]?.[q.id])).length;
    row.querySelector('small').textContent = rated === 3 ? '✓ Rated' : `${rated}/3 rated`;
    row.querySelector('button').setAttribute('aria-pressed', String(active?.id === id));
  }
  $('review-count').textContent = `${played} / ${assignment.length} played`;
  for (const card of $('questions').children) card.hidden = card.dataset.candidate !== active?.id;
  for (const input of $('questions').querySelectorAll('input')) {
    input.checked = draft.ratings[input.dataset.candidate]?.[input.dataset.criterion] === Number(input.value);
    input.disabled = saving || session.pending_trial === trial.id;
  }
  const answered = assignment.reduce((sum, id) => sum + trial.questions.filter(q => Number.isInteger(draft.ratings[id]?.[q.id])).length, 0);
  const total = assignment.length * trial.questions.length;
  const valid = canAnswer(assignment, trial.questions, draft.ratings);
  $('continue').disabled = (!valid && session.pending_trial !== trial.id) || saving;
  $('skip-audio').hidden = trial.kind !== 'audio';
  $('skip-audio').disabled = saving || session.pending_trial === trial.id;
  $('choice-help').textContent = `${answered} of ${total} ratings completed. ` + (valid ? 'Ready to save your ratings.' : 'Rate all three samples on all three criteria.');
  if (session.pending_trial === trial.id) $('choice-help').textContent = 'Your ratings are ready to save. Retry the save button if the connection was interrupted.';
}

function videoLoaded(asset, signal) {
  return new Promise((resolve, reject) => {
    const cleanup = () => { video.removeEventListener('loadeddata', loaded); video.removeEventListener('error', failed); signal.removeEventListener('abort', aborted); };
    const loaded = () => { cleanup(); resolve(); };
    const failed = () => { cleanup(); reject(new Error('Video could not load. Please retry, or use a browser with H.264 video support.')); };
    const aborted = () => { cleanup(); reject(new DOMException('Selection changed', 'AbortError')); };
    video.addEventListener('loadeddata', loaded); video.addEventListener('error', failed);
    signal.addEventListener('abort', aborted, {once: true});
    video.src = url(asset); video.load();
  });
}

async function activateOption(id, autoplay = false) {
  const token = ++generation;
  request?.abort(); request = new AbortController();
  const signal = request.signal;
  pause(); ready = false; error('');
  active = trial.candidates.find(c => c.id === id); draft.active = id;
  $('play').disabled = $('timeline').disabled = true;
  $('loading').hidden = false; $('loading').textContent = 'Preparing option…'; $('retry-media').hidden = true;
  $('active-label').textContent = 'OPTION ' + letters[session.option_order[trial.id].indexOf(id)];
  updateChoices(); persist();
  if (autoplay && audio.context) audio.context.resume().catch(e => error(e.message));
  try {
    let wavPromise = Promise.resolve(null);
    if (active.audio) {
      wavPromise = audioCache.has(id) ? Promise.resolve(audioCache.get(id)) : fetch(url(active.audio), {signal}).then(response => {
        if (!response.ok) throw new Error('Audio could not load. Please retry.');
        return response.arrayBuffer();
      }).then(parseFOAWav);
    }
    const [, wav] = await Promise.all([videoLoaded(active.video, signal), wavPromise]);
    if (token !== generation) return;
    if (wav) {
      await audio.initialize();
      if (token !== generation) return;
      audioCache.set(id, wav); audio.setBuffer(wav);
    }
    applyGain(); updatePose();
    ready = true; $('loading').hidden = true; $('play').disabled = $('timeline').disabled = false;
    $('timeline').max = trial.duration; $('timeline').value = 0;
    $('playback-status').textContent = trial.kind === 'audio' ? 'Ready · use headphones and explore' : 'Ready · same view, same two-second window';
    if (autoplay) await play();
  } catch (e) {
    if (token === generation && e.name !== 'AbortError') { $('loading').textContent = e.message; $('retry-media').hidden = false; }
  }
}

function enterTrial() {
  pause(); ready = false;
  trial = study.trials.find(t => t.id === session.trial_order[session.index]);
  if (!trial) return;
  audioCache.clear();
  draft = session.drafts[trial.id] ||= {ratings: {}, reviewed_seconds: Object.fromEntries(trial.candidates.map(c => [c.id, 0])),
    pose: {yaw: 0, pitch: 0, fov: 110}, started_at: Date.now()};
  ({yaw, pitch, fov} = draft.pose);
  active = null;
  $('trial-count').textContent = `COMPARISON ${session.index + 1} OF ${study.trials.length}`;
  $('section-name').textContent = trial.kind === 'audio' ? 'SPATIAL AUDIO' : 'VIDEO QUALITY';
  $('scene-title').textContent = trial.title;
  $('choices-title').textContent = 'Play & rate each sample';
  $('question').textContent = trial.kind === 'audio' ? 'Rate each soundtrack' : 'Rate each video';
  $('criteria').textContent = 'Choose a sample, then rate Q1, Q2 and Q3 beside the player. Your scores stay saved when you switch.';
  const objects = Object.fromEntries(trial.foreground_objects.map(o => [o.id, o.description]));
  $('global-prompt').replaceChildren(...trial.prompt_segments.map(segment => {
    if (!segment.object_id) return document.createTextNode(segment.text);
    const mark = document.createElement('mark'); mark.textContent = segment.text;
    mark.title = objects[segment.object_id]; return mark;
  }));
  $('trial-meta').textContent = trial.kind === 'audio' ? '6-second clips · Headphones' : '2-second clips · Silent';
  $('sound-label').textContent = trial.kind === 'audio' ? 'HEADPHONE AUDIO' : 'SILENT VIDEO';
  $('volume-control').hidden = trial.kind !== 'audio';
  $('progress').replaceChildren(...session.trial_order.map((_, i) => {
    const step = document.createElement('span'); step.className = i < session.index ? 'done' : i === session.index ? 'current' : ''; return step;
  }));
  $('continue').textContent = session.index === study.trials.length - 1 ? 'Submit my answers ✓' : 'Save ratings & continue →';
  $('participant-label').textContent = 'Participant ' + session.participant_id.slice(0, 8);
  $('choices').replaceChildren();
  for (const [index, id] of session.option_order[trial.id].entries()) {
    const row = document.createElement('div'); row.className = 'option'; row.id = 'choice-' + id;
    row.innerHTML = `<button type="button" class="option-preview" aria-label="Play option ${letters[index]}"><span class="letter">${letters[index]}</span><span class="option-text"><strong>Option ${letters[index]}</strong><small>Not played</small></span></button>`;
    row.querySelector('button').onclick = () => activateOption(id, true);
    $('choices').append(row);
  }
  $('questions').replaceChildren();
  for (const [index, id] of session.option_order[trial.id].entries()) {
    const card = document.createElement('section'); card.className = 'sample-ratings'; card.dataset.candidate = id;
    const heading = document.createElement('div'); heading.className = 'section-top';
    const title = document.createElement('h2'); title.textContent = `Option ${letters[index]}`;
    heading.append(title); card.append(heading);
    const criteria = document.createElement('div'); criteria.className = 'sample-criteria';
    for (const [number, question] of trial.questions.entries()) {
      const field = document.createElement('fieldset'); field.className = 'criterion';
      const legend = document.createElement('legend');
      const numberLabel = document.createElement('strong'); numberLabel.textContent = `Q${number + 1}`;
      const questionLabel = document.createElement('span'); questionLabel.textContent = question.label;
      legend.append(numberLabel, questionLabel); field.title = question.description;
      const options = document.createElement('div'); options.className = 'criterion-options';
      for (const [value, anchor] of Object.entries(study.rating_scale)) {
        const label = document.createElement('label'); label.className = 'criterion-option';
        const input = document.createElement('input'); input.type = 'radio'; input.name = `${id}-${question.id}`; input.value = value;
        input.dataset.candidate = id; input.dataset.criterion = question.id;
        input.setAttribute('aria-label', `Option ${letters[index]}, ${question.label}: ${value} ${anchor}`);
        input.onchange = () => { (draft.ratings[id] ||= {})[question.id] = Number(value); updateChoices(); persist(); };
        const text = document.createElement('span'); text.textContent = `${value} · ${anchor}`;
        label.append(input, text); options.append(label);
      }
      field.append(legend, options); criteria.append(field);
    }
    card.append(criteria); $('questions').append(card);
  }
  $('loop').checked = false; show('trial-screen'); updateChoices(); updatePose();
  activateOption(draft.active || session.option_order[trial.id][0]);
}

async function saveChoice(skipAudio = false) {
  if (saving || (skipAudio && trial.kind !== 'audio') || (session.pending_trial !== trial.id && !skipAudio && !canAnswer(session.option_order[trial.id], trial.questions, draft.ratings))) return;
  pause(); saving = true; error(''); updateChoices();
  // Freeze the payload until acknowledgment: a retry after a lost response must be identical.
  if (session.pending_trial !== trial.id) {
    if (skipAudio) skipRemainingAudio(session, study);
    else {
      session.answers[trial.id] = {ratings: structuredClone(draft.ratings), reviewed_seconds: {...draft.reviewed_seconds}, pose: {...draft.pose},
        elapsed_seconds: Math.min(86400 * 30, (Date.now() - draft.started_at) / 1000), volume_db: session.volume_db};
      session.complete = session.index === study.trials.length - 1;
    }
    session.pending_trial = trial.id;
  }
  persist(); updateChoices();
  $('save-status').textContent = 'Saving to the study server…';
  try {
    const response = await fetch('/api/responses', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(submission(session)), signal: AbortSignal.timeout(15000)});
    const result = await response.json();
    if (!response.ok || !result.saved) throw new Error(result.error || 'Saving failed.');
    delete session.pending_trial;
    session.receipt = result;
    if (session.complete) { session.submitted = true; session.index = study.trials.length; persist(); showComplete(); }
    else { session.index++; persist(); $('save-status').textContent = 'Previous ratings saved to the study server.'; enterTrial(); }
  } catch (e) {
    $('save-status').textContent = 'Not yet saved to the study server. Your browser backup is retained.';
    error('We could not confirm that your ratings were saved. Keep this page open and press the save button again. ' + e.message);
  } finally { saving = false; updateChoices(); }
}

function showComplete() {
  pause(); ready = false; show('complete-screen');
  $('receipt').replaceChildren();
  const questionCount = Object.values(session.answers).reduce((sum, answer) => sum + Object.values(answer.ratings).reduce((n, scores) => n + Object.keys(scores).length, 0), 0);
  const skipped = Object.values(session.answers).filter(answer => answer.skipped).length;
  for (const text of [`${questionCount} ratings saved · ${skipped} audio scenes skipped or left unfinished`, 'Participant: ' + session.participant_id, 'Saved: ' + new Date(session.receipt.saved_at).toLocaleString()]) {
    const line = document.createElement('div'); line.textContent = text; $('receipt').append(line);
  }
}
function download(type) {
  const payload = submission(session);
  const rows = session.trial_order.flatMap((id, i) => {
    const answer = session.answers[id], t = study.trials.find(t => t.id === id);
    return session.option_order[id].flatMap((candidate, index) => t.questions.map(q => ({participant_id: session.participant_id, version: session.version, trial_number: i + 1, trial_id: id,
      kind: t.kind, scene: t.title, scene_skipped: answer.skipped || false, criterion_id: q.id, criterion: q.label,
      option: letters[index], candidate_id: candidate, score: answer.ratings[candidate]?.[q.id] ?? '', elapsed_seconds: answer.elapsed_seconds})));
  });
  const quote = text => '"' + String(text).replaceAll('"', '""') + '"';
  const content = type === 'json' ? JSON.stringify({...payload, receipt: session.receipt}, null, 2) :
    [Object.keys(rows[0]), ...rows.map(Object.values)].map(row => row.map(quote).join(',')).join('\r\n');
  const link = document.createElement('a'), objectURL = URL.createObjectURL(new Blob([content], {type: type === 'json' ? 'application/json' : 'text/csv;charset=utf-8'}));
  link.href = objectURL; link.download = `study-${session.participant_id}.${type}`; link.click(); setTimeout(() => URL.revokeObjectURL(objectURL), 1000);
}

$('headphones').onchange = () => { $('start').disabled = !study || !$('headphones').checked; };
$('start').onclick = () => {
  $('start').disabled = true; error('');
  try {
    persist(); enterTrial();
  } catch (e) { error('Could not start the study: ' + e.message); $('start').disabled = false; }
};
$('continue').onclick = () => saveChoice();
$('skip-audio').onclick = () => saveChoice(true);
$('play').onclick = () => video.paused ? play() : pause();
$('retry-media').onclick = () => activateOption(active.id);
$('reset-view').onclick = () => { stopKeyboardRotation(); yaw = pitch = 0; fov = 110; updatePose(); persist(); };
$('volume').oninput = () => { session.volume_db = Number($('volume').value); applyGain(); persist(); };
$('timeline').oninput = () => {
  if (!scrubbing) { resumeAfterScrub = !video.paused; scrubbing = true; pause(); }
  video.currentTime = Number($('timeline').value);
};
$('timeline').onchange = () => { scrubbing = false; if (resumeAfterScrub) play(); };
$('download-json').onclick = () => download('json'); $('download-csv').onclick = () => download('csv');
$('new-participant').onclick = async () => {
  try { study = await fetchStudy(); } catch (e) { error(e.message); return; }
  session = newSession(study); trial = draft = active = null; persist();
  $('headphones').checked = false; $('start').textContent = 'Begin study →'; $('start').disabled = true;
  $('resume-note').textContent = ''; error(''); show('welcome');
};
let drag;
$('perspective').onpointerdown = e => {
  if (e.button !== 0) return;
  stopKeyboardRotation();
  drag = {x: e.clientX, y: e.clientY, yaw, pitch}; $('perspective').setPointerCapture(e.pointerId);
};
$('perspective').onpointermove = e => {
  if (!drag) return;
  const scale = fov / $('perspective').clientWidth;
  yaw = drag.yaw + (e.clientX - drag.x) * scale; pitch = drag.pitch + (e.clientY - drag.y) * scale; updatePose();
};
$('perspective').onpointerup = $('perspective').onpointercancel = () => { drag = null; if (session) persist(); };
$('perspective').addEventListener('wheel', e => { e.preventDefault(); fov += e.deltaY * 0.04; updatePose(); }, {passive: false});
$('overview').onclick = e => {
  const rect = $('overview').getBoundingClientRect(); yaw = 180 - 360 * (e.clientX - rect.left) / rect.width;
  pitch = 90 - 180 * (e.clientY - rect.top) / rect.height; updatePose(); persist();
};
function stopKeyboardRotation() {
  const moving = heldRotationKeys.size > 0;
  heldRotationKeys.clear();
  if (moving && session) persist();
}
function updateKeyboardRotation(delta) {
  const horizontal = Number(heldRotationKeys.has('a')) - Number(heldRotationKeys.has('d'));
  const vertical = Number(heldRotationKeys.has('w')) - Number(heldRotationKeys.has('s'));
  if (!horizontal && !vertical) return;
  const step = 45 * delta / Math.max(1, Math.hypot(horizontal, vertical));
  yaw += horizontal * step; pitch += vertical * step;
  updatePose();
}
document.addEventListener('keydown', e => {
  if ($('trial-screen').hidden || e.ctrlKey || e.metaKey || e.altKey || e.target.isContentEditable || ['INPUT','TEXTAREA','SELECT'].includes(e.target.tagName)) {
    stopKeyboardRotation(); return;
  }
  const key = e.key.toLowerCase();
  if (['w', 'a', 's', 'd'].includes(key)) {
    e.preventDefault(); heldRotationKeys.add(key);
  } else if (key.startsWith('arrow') && !['BUTTON','A'].includes(e.target.tagName)) {
    e.preventDefault();
    yaw += key === 'arrowleft' ? 5 : key === 'arrowright' ? -5 : 0;
    pitch += key === 'arrowup' ? 5 : key === 'arrowdown' ? -5 : 0;
    updatePose(); persist();
  } else if (e.code === 'Space' && !['BUTTON','A'].includes(e.target.tagName)) {
    e.preventDefault(); video.paused ? play() : pause();
  }
});
document.addEventListener('keyup', e => {
  if (heldRotationKeys.delete(e.key.toLowerCase()) && session) persist();
});
document.addEventListener('focusin', e => {
  if (e.target.isContentEditable || ['INPUT','TEXTAREA','SELECT'].includes(e.target.tagName)) stopKeyboardRotation();
});
window.addEventListener('blur', stopKeyboardRotation);
video.muted = true;
video.addEventListener('playing', syncAudio);
video.addEventListener('waiting', () => { audio.stop(); lastMediaTime = null; $('playback-status').textContent = 'Buffering…'; });
video.addEventListener('pause', () => { audio.stop(); });
video.addEventListener('seeking', () => { audio.stop(); lastMediaTime = null; });
video.addEventListener('seeked', syncAudio);
video.addEventListener('ended', () => { if (ready) finishClip(); });
document.addEventListener('visibilitychange', () => { if (document.hidden) { stopKeyboardRotation(); pause(); if (session) persist(); } });
window.addEventListener('pagehide', () => { stopKeyboardRotation(); pause(); if (session) persist(); });

function animate(now) {
  const delta = lastFrameTime === null ? 0 : Math.min((now - lastFrameTime) / 1000, 0.05);
  lastFrameTime = now;
  if (ready && !$('trial-screen').hidden) {
    updateKeyboardRotation(delta);
    panorama.draw(yaw, pitch, fov);
    if (!scrubbing) $('timeline').value = Math.min(video.currentTime, trial.duration);
    $('time').textContent = `${Math.min(video.currentTime,trial.duration).toFixed(1)} / ${trial.duration.toFixed(1)} s`;
    if (!video.paused && !video.seeking && video.readyState >= 3) {
      const time = Math.min(video.currentTime, trial.duration);
      if (lastMediaTime !== null) {
        const delta = time - lastMediaTime;
        if (delta > 0 && delta < 0.3) {
          draft.reviewed_seconds[active.id] = Math.min(trial.duration, (draft.reviewed_seconds[active.id] || 0) + delta);
          updateChoices();
        }
      }
      lastMediaTime = time;
      if (now - lastSync > 250 && trial.kind === 'audio' && audio.position !== null) {
        if (Math.abs(audio.position - video.currentTime) > 0.08) syncAudio();
        lastSync = now;
      }
      if (video.currentTime >= trial.duration) finishClip();
    }
    if (now - lastPersist > 1000) { persist(); lastPersist = now; }
  }
  requestAnimationFrame(animate);
}

async function fetchStudy(participantId) {
  const response = await fetch('/api/study' + (participantId ? '?participant_id=' + encodeURIComponent(participantId) : ''));
  if (!response.ok) throw new Error('The study could not load. Please refresh and try again.');
  return response.json();
}

async function main() {
  if (location.protocol === 'file:') throw new Error('Open launch.command in this folder to start the study website and enable response saving.');
  try { session = JSON.parse(localStorage.getItem(storageKey)); } catch { session = null; }
  const savedId = /^[0-9a-f-]{36}$/i.test(session?.participant_id || '') ? session.participant_id : null;
  study = await fetchStudy(savedId);
  if (!validSession(session, study)) {
    if (session?.version && session.version !== study.version) {
      localStorage.setItem(`${storageKey}-archive-${session.version}-${session.participant_id}`, JSON.stringify(session));
    }
    if (savedId) study = await fetchStudy();
    session = newSession(study);
  }
  persist();
  $('total-trials').textContent = study.trials.length;
  $('video-trials').textContent = study.trials.filter(t => t.kind === 'video').length;
  $('audio-trials').textContent = study.trials.filter(t => t.kind === 'audio').length;
  panorama = new Panorama($('perspective'), $('overview'), video);
  requestAnimationFrame(animate);
  if (session.submitted) { showComplete(); return; }
  const resuming = session.index > 0 || Object.keys(session.drafts).length > 0;
  $('start').textContent = resuming ? 'Resume study →' : 'Begin study →';
  $('resume-note').textContent = resuming ? `Your progress is saved. Continue at comparison ${session.index + 1} of ${study.trials.length}.` : 'Video comparisons come first. Spatial audio is optional; use headphones if you choose to rate it.';
  $('start').disabled = !$('headphones').checked;
}
main().catch(e => error(e.message));