aboutsummaryrefslogtreecommitdiff
path: root/public/app.js
blob: ed1c6d618c30b12a243bf71f1122a389d3c1049b (plain)
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
"use strict"

const $ = (s) => document.querySelector(s)
const stage = $("#stage")
const world = $("#world")
const importState = $("#import-state")
const importEl = $("#import")
const fileInput = $("#file")
const dropOverlay = $("#drop")
const toastEl = $("#toast")
const progressEl = $("#progress")
const progressFill = $("#progress-fill")
const progressText = $("#progress-text")

addEventListener("error", (e) => {
  toast(`error: ${e.message || "script failed"}`, true)
})

const GAP = 10
const FIT_TOLERANCE = 350
const MIN_ZOOM = 0.05
const MAX_ZOOM = 5
const EPS = 0.5

let U = 300
const tiles = new Map()
const rectOf = new Map()
const photoInfo = new Map()
const exitsCache = new Map()
const exitPending = new Map()
let cur = null
let panX = 0
let panY = 0
let scale = 1
let userZoomed = false
let drag = null
let hoveredSlot = null

const TOUCH = typeof window.matchMedia === "function" && window.matchMedia("(hover: none)").matches

function aspect(info) {
  return info.h > 0 ? info.w / info.h : 1
}

function tileW(info) {
  const a = aspect(info)
  return a >= 1 ? U * a : U
}

function tileH(info) {
  const a = aspect(info)
  return a >= 1 ? U : U / a
}

function worldScale() {
  const n = tiles.size
  if (n <= 1) return 1
  return Math.max(0.5, 1 - (n - 1) * 0.04)
}

function applyPan() {
  world.style.transform = `translate(${panX}px, ${panY}px) scale(${scale})`
}

function center() {
  if (!cur) return
  const r = cur.rect
  panX = window.innerWidth / 2 - scale * (r.x + r.w / 2)
  panY = window.innerHeight / 2 - scale * (r.y + r.h / 2)
  applyPan()
}

function zoomAt(mx, my, factor) {
  const ns = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, scale * factor))
  if (ns === scale) return
  const wx = (mx - panX) / scale
  const wy = (my - panY) / scale
  panX = mx - wx * ns
  panY = my - wy * ns
  scale = ns
  userZoomed = true
  applyPan()
}

function resetZoom() {
  userZoomed = false
  scale = worldScale()
  center()
}

function overlaps(a, b) {
  return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y
}

function collides(rect) {
  for (const t of tiles.values()) if (overlaps(rect, t.rect)) return true
  return false
}

function baseRect(w, h, from, dir) {
  if (dir === "N") return { x: from.x + (from.w - w) / 2, y: from.y - h - GAP, w, h }
  if (dir === "S") return { x: from.x + (from.w - w) / 2, y: from.y + from.h + GAP, w, h }
  if (dir === "E") return { x: from.x + from.w + GAP, y: from.y + (from.h - h) / 2, w, h }
  return { x: from.x - w - GAP, y: from.y + (from.h - h) / 2, w, h }
}

function sideGap(rect, dx, dy) {
  let g = Infinity
  for (const t of tiles.values()) {
    const r = t.rect
    if (dx !== 0) {
      if (r.y + r.h <= rect.y || r.y >= rect.y + rect.h) continue
      const gap = dx < 0 ? rect.x - (r.x + r.w) : r.x - (rect.x + rect.w)
      if (gap >= 0 && gap < g) g = gap
    } else {
      if (r.x + r.w <= rect.x || r.x >= rect.x + rect.w) continue
      const gap = dy < 0 ? rect.y - (r.y + r.h) : r.y - (rect.y + rect.h)
      if (gap >= 0 && gap < g) g = gap
    }
  }
  return g
}

function packGap(rect, w, h) {
  const cap = Math.max(w, h) * 2
  const g = [
    sideGap(rect, 0, -1),
    sideGap(rect, 0, 1),
    sideGap(rect, -1, 0),
    sideGap(rect, 1, 0),
  ]
  let sum = 0
  for (const v of g) sum += v === Infinity ? cap : v
  return sum
}

function bestPlacement(w, h, from, dir) {
  const base = baseRect(w, h, from, dir)
  if (!collides(base)) return { rect: base, cost: 0 }

  const xs = new Set([base.x])
  const ys = new Set([base.y])
  for (const t of tiles.values()) {
    const r = t.rect
    xs.add(r.x - w - GAP)
    xs.add(r.x + r.w + GAP)
    xs.add(r.x + (r.w - w) / 2)
    ys.add(r.y - h - GAP)
    ys.add(r.y + r.h + GAP)
    ys.add(r.y + (r.h - h) / 2)
  }

  let best = null
  let bestCost = Infinity
  for (const x of xs) {
    for (const y of ys) {
      const rect = { x, y, w, h }
      if (collides(rect)) continue
      const dist = Math.abs(x - base.x) + Math.abs(y - base.y)
      const cost = dist + 0.2 * packGap(rect, w, h)
      if (cost < bestCost) {
        bestCost = cost
        best = rect
      }
    }
  }
  return best ? { rect: best, cost: bestCost } : null
}

function addTile(info, rect) {
  const el = document.createElement("div")
  el.className = "tile"
  el.dataset.id = info.id
  el.style.left = rect.x + "px"
  el.style.top = rect.y + "px"
  el.style.width = rect.w + "px"
  el.style.height = rect.h + "px"
  const img = document.createElement("img")
  img.src = info.thumb
  img.alt = info.title || "photo"
  img.loading = "lazy"
  el.appendChild(img)
  world.appendChild(el)
  requestAnimationFrame(() => el.classList.add("lock"))
  tiles.set(info.id, { el, info, rect })
  rectOf.set(info.id, rect)
  placementCache.clear()
  adjacencyCache.clear()
  renderNav(info.id)
  return el
}

function setCurrent(id, rect, recenter = true) {
  const prevId = cur && cur.id
  for (const t of tiles.values()) t.el.classList.remove("current")
  cur = { id, rect }
  tiles.get(id).el.classList.add("current")
  if (recenter) {
    if (!userZoomed) scale = worldScale()
    center()
    hoveredSlot = null
  }
  getExits(id)
  if (prevId && prevId !== id) renderNav(prevId)
  renderNav(id)
  refreshPreviews()
}

function renderNav(id) {
  const t = tiles.get(id)
  if (!t) return
  t.el.querySelectorAll(".nav").forEach((n) => n.remove())
  const exits = exitsCache.get(id)
  if (!exits) return
  if (cur && cur.id === id) return
  if (TOUCH) return
  const nav = document.createElement("div")
  nav.className = "nav"
  for (const ex of exits) {
    const zone = document.createElement("div")
    zone.className = `nav-zone nav-zone-${ex.dir}`
    zone.addEventListener("pointerdown", (e) => e.stopPropagation())
    zone.addEventListener("click", (e) => { e.stopPropagation(); traverseFrom(id, ex.dir) })
    nav.appendChild(zone)
  }
  t.el.appendChild(nav)
}

async function getExits(id) {
  if (exitsCache.has(id)) return exitsCache.get(id)
  if (exitPending.has(id)) return exitPending.get(id)
  const p = (async () => {
    try {
      const r = await fetch(`/api/exits/${id}`)
      if (!r.ok) return null
      const data = await r.json()
      for (const ph of Object.values(data.photos || {})) photoInfo.set(ph.id, ph)
      for (const ex of data.exits || []) if (ex.next) photoInfo.set(ex.next.id, ex.next)
      const exits = data.exits || []
      exitsCache.set(id, exits)
      renderNav(id)
      if (!drag) {
        const s = findSlotAt(lastCursor.wx, lastCursor.wy)
        if (s) { hoveredSlot = s; refreshPreviews() }
      }
      return exits
    } catch {
      return null
    }
  })()
  exitPending.set(id, p)
  p.finally(() => exitPending.delete(id))
  return p
}

const placementCache = new Map()
const adjacencyCache = new Map()

function choosePlacement(id, dir) {
  const key = id + ":" + dir
  if (placementCache.has(key)) return placementCache.get(key)
  const exits = exitsCache.get(id)
  const ex = exits && exits.find((e) => e.dir === dir)
  if (!ex) return null
  const from = tiles.get(id).rect
  const seen = new Set()
  const claimed = new Set()
  if (exits) for (const e of exits) if (e.dir !== dir && e.next) claimed.add(e.next.id)
  const candIds = []
  const addCand = (cid) => {
    if (cid && !claimed.has(cid) && !seen.has(cid) && !rectOf.has(cid)) {
      seen.add(cid)
      candIds.push(cid)
    }
  }
  addCand(ex.next && ex.next.id)
  for (const wid of ex.walk) {
    if (candIds.length >= 4) break
    addCand(wid)
  }
  const scored = []
  for (const cid of candIds) {
    const info = photoInfo.get(cid) || (tiles.get(cid) && tiles.get(cid).info)
    if (!info) continue
    const p = bestPlacement(tileW(info), tileH(info), from, dir)
    if (p) scored.push({ id: cid, info, rect: p.rect, cost: p.cost })
  }
  if (!scored.length) {
    for (const [cid, info] of photoInfo) {
      if (rectOf.has(cid) || cid === id) continue
      const p = bestPlacement(tileW(info), tileH(info), from, dir)
      if (p) scored.push({ id: cid, info, rect: p.rect, cost: p.cost + (claimed.has(cid) ? 1e12 : 0) })
    }
  }
  if (!scored.length) return null
  scored.sort((a, b) => a.cost - b.cost)
  const best = scored[0]
  const next = ex.next && !rectOf.has(ex.next.id) ? scored.find((s) => s.id === ex.next.id) : null
  const chosen = next && next.cost - best.cost <= FIT_TOLERANCE ? next : best
  const out = { id: chosen.id, info: chosen.info, rect: chosen.rect }
  placementCache.set(key, out)
  return out
}

function adjacentTile(id, dir) {
  const key = id + ":" + dir
  if (adjacencyCache.has(key)) return adjacencyCache.get(key)
  const r = tiles.get(id).rect
  let best = null
  let bestDist = Infinity
  for (const t of tiles.values()) {
    if (t.info.id === id) continue
    const q = t.rect
    let adj = false
    if (dir === "N") adj = Math.abs(q.y + q.h + GAP - r.y) <= EPS && q.x < r.x + r.w && q.x + q.w > r.x
    else if (dir === "S") adj = Math.abs(q.y - (r.y + r.h + GAP)) <= EPS && q.x < r.x + r.w && q.x + q.w > r.x
    else if (dir === "E") adj = Math.abs(q.x - (r.x + r.w + GAP)) <= EPS && q.y < r.y + r.h && q.y + q.h > r.y
    else adj = Math.abs(q.x + q.w + GAP - r.x) <= EPS && q.y < r.y + r.h && q.y + q.h > r.y
    if (!adj) continue
    const d = dir === "N" || dir === "S"
      ? Math.abs(q.x + q.w / 2 - (r.x + r.w / 2))
      : Math.abs(q.y + q.h / 2 - (r.y + r.h / 2))
    if (d < bestDist) { bestDist = d; best = t }
  }
  const out = best ? best.info.id : null
  adjacencyCache.set(key, out)
  return out
}

function traverseFrom(id, dir) {
  followEnabled = false
  const back = adjacentTile(id, dir)
  if (back) {
    setCurrent(back, tiles.get(back).rect)
    return
  }
  const chosen = choosePlacement(id, dir)
  if (!chosen) return
  addTile(chosen.info, chosen.rect)
  setCurrent(chosen.id, chosen.rect)
}

const slotUI = { preview: null, previewImg: null, dropzone: null, key: null, loadTimer: 0 }
const lastCursor = { wx: 0, wy: 0 }

function hideSlot() {
  if (slotUI.preview && slotUI.preview.parentNode) world.removeChild(slotUI.preview)
  if (slotUI.dropzone && slotUI.dropzone.parentNode) world.removeChild(slotUI.dropzone)
  slotUI.key = null
}

function showSlot(slot) {
  if (!tiles.has(slot.id) || !exitsCache.has(slot.id) || !choosePlacement(slot.id, slot.dir)) {
    hideSlot()
    return
  }
  const p = choosePlacement(slot.id, slot.dir)
  const key = slot.id + ":" + slot.dir
  if (slotUI.key === key) return
  hideSlot()
  slotUI.key = key
  if (!slotUI.preview) {
    slotUI.preview = document.createElement("div")
    slotUI.preview.className = "preview"
    slotUI.previewImg = document.createElement("img")
    slotUI.previewImg.alt = ""
    slotUI.preview.appendChild(slotUI.previewImg)
    const spinner = document.createElement("div")
    spinner.className = "spinner"
    slotUI.preview.appendChild(spinner)
    slotUI.dropzone = document.createElement("div")
    slotUI.dropzone.className = "dropzone"
    slotUI.dropzone.addEventListener("pointerdown", (e) => e.stopPropagation())
  }
  const doneLoading = () => {
    clearTimeout(slotUI.loadTimer)
    slotUI.preview.classList.remove("loading", "slow")
  }
  slotUI.previewImg.onload = doneLoading
  slotUI.previewImg.onerror = doneLoading
  slotUI.preview.style.left = p.rect.x + "px"
  slotUI.preview.style.top = p.rect.y + "px"
  slotUI.preview.style.width = p.rect.w + "px"
  slotUI.preview.style.height = p.rect.h + "px"
  slotUI.dropzone.style.left = p.rect.x + "px"
  slotUI.dropzone.style.top = p.rect.y + "px"
  slotUI.dropzone.style.width = p.rect.w + "px"
  slotUI.dropzone.style.height = p.rect.h + "px"
  slotUI.dropzone.onclick = () => traverseFrom(slot.id, slot.dir)
  const next = new URL(p.info.thumb, location.href).href
  if (slotUI.previewImg.src === next && slotUI.previewImg.complete) {
    doneLoading()
  } else {
    clearTimeout(slotUI.loadTimer)
    slotUI.preview.classList.add("loading")
    slotUI.preview.classList.remove("slow")
    slotUI.previewImg.src = next
    slotUI.loadTimer = setTimeout(() => {
      if (slotUI.preview.classList.contains("loading")) slotUI.preview.classList.add("slow")
    }, 1000)
  }
  world.appendChild(slotUI.dropzone)
  world.appendChild(slotUI.preview)
}

function refreshPreviews() {
  if (hoveredSlot) showSlot(hoveredSlot)
  else hideSlot()
}

function findSlotAt(wx, wy) {
  let best = null
  let bestD = Infinity
  for (const t of tiles.values()) {
    if (!exitsCache.has(t.info.id)) continue
    const r = t.rect
    const m = Math.max(r.w, r.h) * 2 + GAP
    if (wx < r.x - m || wx > r.x + r.w + m || wy < r.y - m || wy > r.y + r.h + m) continue
    for (const dir of ["N", "E", "S", "W"]) {
      if (adjacentTile(t.info.id, dir)) continue
      const p = choosePlacement(t.info.id, dir)
      if (!p) continue
      const q = p.rect
      if (wx < q.x || wx > q.x + q.w || wy < q.y || wy > q.y + q.h) continue
      const d = Math.hypot(wx - (q.x + q.w / 2), wy - (q.y + q.h / 2))
      if (d < bestD) { bestD = d; best = { id: t.info.id, dir, rect: q } }
    }
  }
  return best
}

let lastFollow = 0
let followEnabled = true
function followCurrent() {
  if (!tiles.size || !cur) return
  const cx = (window.innerWidth / 2 - panX) / scale
  const cy = (window.innerHeight / 2 - panY) / scale
  const view = {
    x: cx - window.innerWidth / 2 / scale,
    y: cy - window.innerHeight / 2 / scale,
    w: window.innerWidth / scale,
    h: window.innerHeight / scale,
  }
  let best = null
  let bestD = Infinity
  for (const t of tiles.values()) {
    const r = t.rect
    if (!overlaps(view, r)) continue
    const px = Math.max(r.x, Math.min(cx, r.x + r.w))
    const py = Math.max(r.y, Math.min(cy, r.y + r.h))
    const d = Math.hypot(cx - px, cy - py)
    if (d < bestD) { bestD = d; best = t }
  }
  if (!best || best.info.id === cur.id) return
  setCurrent(best.info.id, best.rect, false)
}

function maybeFollow() {
  const now = performance.now()
  if (now - lastFollow < 200) return
  lastFollow = now
  const before = cur && cur.id
  if (followEnabled) followCurrent()
  if (cur && cur.id === before) refreshPreviews()
}

stage.addEventListener("pointerover", (e) => {
  const tileEl = e.target.closest(".tile")
  if (tileEl) getExits(Number(tileEl.dataset.id))
})

const pointers = new Map()
let pinchDist = 0

stage.addEventListener("pointerdown", (e) => {
  if (e.target.closest(".nav-zone")) return
  if (e.target.closest("#import-state")) return
  pointers.set(e.pointerId, { x: e.clientX, y: e.clientY })
  try { stage.setPointerCapture(e.pointerId) } catch { /* ignore */ }
  hoveredSlot = null
  hideSlot()
  world.style.transition = "none"
  if (pointers.size === 2) {
    followEnabled = true
    drag = null
    const [a, b] = [...pointers.values()]
    pinchDist = Math.hypot(b.x - a.x, b.y - a.y)
    return
  }
  followEnabled = false
  drag = { x: e.clientX, y: e.clientY, px: panX, py: panY, moved: false, tile: e.target.closest(".tile") }
})

stage.addEventListener("pointermove", (e) => {
  lastCursor.wx = (e.clientX - panX) / scale
  lastCursor.wy = (e.clientY - panY) / scale
  if (pointers.has(e.pointerId)) {
    pointers.set(e.pointerId, { x: e.clientX, y: e.clientY })
    if (pointers.size === 2 && pinchDist > 0) {
      const [a, b] = [...pointers.values()]
      const d = Math.hypot(b.x - a.x, b.y - a.y)
      if (d > 0) {
        zoomAt((a.x + b.x) / 2, (a.y + b.y) / 2, d / pinchDist)
        pinchDist = d
      }
      return
    }
  }
  if (drag) {
    const dx = e.clientX - drag.x
    const dy = e.clientY - drag.y
    if (!drag.moved && Math.hypot(dx, dy) > 5) drag.moved = true
    if (drag.moved) {
      panX = drag.px + dx
      panY = drag.py + dy
      applyPan()
      maybeFollow()
    }
    return
  }
  const slot = findSlotAt(lastCursor.wx, lastCursor.wy)
  const key = slot ? slot.id + ":" + slot.dir : null
  const curKey = hoveredSlot && hoveredSlot.id + ":" + hoveredSlot.dir
  if (key !== curKey) {
    hoveredSlot = slot
    refreshPreviews()
  }
})

stage.addEventListener("pointerup", (e) => {
  const wasPinch = pointers.size >= 2
  pointers.delete(e.pointerId)
  if (wasPinch && pointers.size === 1) {
    const p = [...pointers.values()][0]
    drag = { x: p.x, y: p.y, px: panX, py: panY, moved: true, tile: null }
  }
  pinchDist = 0
  if (!drag) return
  const wasDrag = drag.moved
  const tile = drag.tile
  drag = null
  world.style.transition = ""
  if (wasDrag || !tile) {
    if (wasDrag && followEnabled) followCurrent()
    if (!wasDrag && !tile && e.pointerType === "touch") bgTap()
    return
  }
  const id = Number(tile.dataset.id)
  followEnabled = false
  if (cur && cur.id === id) return
  setCurrent(id, tiles.get(id).rect)
})

stage.addEventListener("pointercancel", (e) => {
  pointers.delete(e.pointerId)
  pinchDist = 0
  drag = null
  world.style.transition = ""
})

let lastBgTap = -Infinity
function bgTap() {
  const now = performance.now()
  if (now - lastBgTap < 350) {
    lastBgTap = 0
    resetZoom()
    return
  }
  lastBgTap = now
}

let zoomTimer = 0
stage.addEventListener("wheel", (e) => {
  e.preventDefault()
  followEnabled = true
  let dx = e.deltaX
  let dy = e.deltaY
  if (e.deltaMode === 1) { dx *= 16; dy *= 16 }
  else if (e.deltaMode === 2) { dx *= window.innerWidth; dy *= window.innerHeight }
  world.style.transition = "none"
  if (e.ctrlKey) {
    hoveredSlot = null
    hideSlot()
    const rect = stage.getBoundingClientRect()
    zoomAt(e.clientX - rect.left, e.clientY - rect.top, Math.exp(-dy * 0.01))
  } else {
    hoveredSlot = null
    hideSlot()
    panX -= dx
    panY -= dy
    applyPan()
    maybeFollow()
  }
  clearTimeout(zoomTimer)
  zoomTimer = setTimeout(() => { world.style.transition = "" }, 120)
}, { passive: false })

stage.addEventListener("dblclick", (e) => {
  if (e.target.closest(".tile")) return
  resetZoom()
})

addEventListener("keydown", (e) => {
  const map = { ArrowUp: "N", ArrowRight: "E", ArrowDown: "S", ArrowLeft: "W" }
  const dir = map[e.key]
  if (dir) {
    e.preventDefault()
    if (cur) traverseFrom(cur.id, dir)
  } else if (e.key === "0" || e.key === "f" || e.key === "F") {
    e.preventDefault()
    resetZoom()
  }
})

addEventListener("resize", center)

let started = false

function showImportState() {
  importState.hidden = false
  stage.classList.add("blocked")
}

function hideImportState() {
  importState.hidden = true
  stage.classList.remove("blocked")
}

async function initDirectHint() {
  try {
    const r = await fetch("/api/health")
    const data = await r.json()
    const d = data.direct || {}
    const urls = [d.magic, d.lan, d.tailscale].filter(Boolean)
    if (!urls.length) return
    if (urls.some((u) => { try { return new URL(u).host === location.host } catch { return false } })) return
    const link = $("#direct-link")
    link.textContent = d.magic
    link.href = d.magic
    $("#direct-hint").hidden = false
  } catch { /* ignore */ }
}

async function beginWalk() {
  if (started) return
  started = true
  try {
    const r = await fetch("/api/random")
    const data = await r.json()
    if (!data.photo) {
      showImportState()
      return
    }
    hideImportState()
    const photo = data.photo
    photoInfo.set(photo.id, photo)
    const a = aspect(photo)
    const wf = a >= 1 ? a : 1
    const hf = a >= 1 ? 1 : 1 / a
    const uW = (window.innerWidth * 0.92) / wf
    const uH = (window.innerHeight * 0.92) / hf
    U = Math.max(100, Math.min(640, Math.round(Math.min(uW, uH))))
    const rect = { x: 0, y: 0, w: tileW(photo), h: tileH(photo) }
    addTile(photo, rect)
    setCurrent(photo.id, rect)
  } catch { /* ignore */ }
}

;(async () => {
  try {
    const r = await fetch("/api/paths")
    const data = await r.json()
    if (data.total) await beginWalk()
    else showImportState()
  } catch {
    showImportState()
  }
  initDirectHint()
})()

let toastTimer = 0

function toast(msg, isError = false) {
  toastEl.textContent = msg
  toastEl.classList.toggle("err", isError)
  toastEl.classList.add("show")
  clearTimeout(toastTimer)
  toastTimer = setTimeout(() => toastEl.classList.remove("show"), isError ? 7000 : 3500)
}

function plural(n) {
  return n === 1 ? "photo" : "photos"
}

function setProgress(mode, pct, text) {
  progressEl.hidden = false
  progressText.textContent = text
  if (mode === "indeterminate") {
    progressEl.classList.add("indeterminate")
  } else {
    progressEl.classList.remove("indeterminate")
    progressFill.style.width = pct + "%"
  }
}

function hideProgress() {
  progressEl.hidden = true
  progressEl.classList.remove("indeterminate")
  progressFill.style.width = "0%"
}

function uploadWithProgress(form, onPct, onUploaded) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open("POST", "/api/import")
    xhr.upload.addEventListener("progress", (e) => {
      if (e.lengthComputable) onPct(Math.min(100, Math.round((e.loaded / e.total) * 100)))
    })
    xhr.upload.addEventListener("load", () => onUploaded())
    xhr.addEventListener("load", () => {
      let data = {}
      try { data = JSON.parse(xhr.responseText) } catch { /* ignore */ }
      if (xhr.status >= 200 && xhr.status < 300) resolve(data)
      else reject(new Error(data.error || `import failed (${xhr.status})`))
    })
    xhr.addEventListener("error", () => reject(new Error("upload failed (network error)")))
    xhr.send(form)
  })
}

async function importFiles(list) {
  const files = Array.from(list || []).filter((f) => f.size > 0)
  if (!files.length) return
  const form = new FormData()
  for (const f of files) form.append("photos", f, f.name)
  importEl.classList.add("busy")
  setProgress("determinate", 0, `uploading ${files.length} ${plural(files.length)}… 0%`)
  try {
    const data = await uploadWithProgress(
      form,
      (pct) => setProgress("determinate", pct, `uploading ${files.length} ${plural(files.length)}… ${pct}%`),
      () => setProgress("indeterminate", 100, "indexing…")
    )
    if (!data.ok) throw new Error(data.error || "import failed")
    exitsCache.clear()
    exitPending.clear()
    hideProgress()
    hideImportState()
    await beginWalk()
    toast(`imported ${data.imported} ${plural(data.imported)} - keep walking to find them`)
  } catch (err) {
    hideProgress()
    toast(err.message || "import failed", true)
  } finally {
    importEl.classList.remove("busy")
    fileInput.value = ""
  }
}

function hasFiles(e) {
  return Array.from(e.dataTransfer?.types || []).includes("Files")
}


fileInput.addEventListener("change", () => importFiles(fileInput.files))

let dragDepth = 0

addEventListener("dragenter", (e) => {
  if (!hasFiles(e)) return
  e.preventDefault()
  dragDepth++
  dropOverlay.classList.add("show")
})

addEventListener("dragover", (e) => {
  if (!hasFiles(e)) return
  e.preventDefault()
  e.dataTransfer.dropEffect = "copy"
})

addEventListener("dragleave", () => {
  dragDepth = Math.max(0, dragDepth - 1)
  if (dragDepth === 0) dropOverlay.classList.remove("show")
})

addEventListener("drop", (e) => {
  if (!e.dataTransfer) return
  e.preventDefault()
  dragDepth = 0
  dropOverlay.classList.remove("show")
  importFiles(e.dataTransfer.files)
})