File size: 28,908 Bytes
642f608
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
794
795
796
797
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');
const wordLists = require('./words');

const app = express();
const server = http.createServer(app);
const io = new Server(server, { cors: { origin: '*' } });
const PORT = process.env.PORT || 7860;

app.use(express.static(path.join(__dirname, 'public')));
// /game now served by index.html (single page app)
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html')));

// ─── In-memory game state ───────────────────────────────────────────────────
const rooms = {};

function genCode() {
  let code;
  do { code = Math.random().toString(36).substring(2, 8).toUpperCase(); } while (rooms[code]);
  return code;
}

function getWords(settings, count = 3) {
  let pool = [];
  if (settings.wordMode === 'custom' && settings.customWords.length >= count) {
    pool = [...settings.customWords];
  } else if (settings.wordMode === 'mixed') {
    const cats = settings.categories || Object.keys(wordLists);
    cats.forEach(c => { if (wordLists[c]) pool = pool.concat(wordLists[c]); });
    pool = pool.concat(settings.customWords || []);
  } else {
    const cats = settings.categories || Object.keys(wordLists);
    cats.forEach(c => { if (wordLists[c]) pool = pool.concat(wordLists[c]); });
  }
  pool = [...new Set(pool)];
  const choices = [];
  while (choices.length < count && pool.length > 0) {
    const i = Math.floor(Math.random() * pool.length);
    choices.push(pool.splice(i, 1)[0]);
  }
  return choices;
}

function hintMask(word, revealed) {
  return word.split('').map((c, i) => c === ' ' ? ' ' : revealed.includes(i) ? c : '_').join('');
}

function levenshtein(a, b) {
  const dp = Array.from({ length: a.length + 1 }, (_, i) =>
    Array.from({ length: b.length + 1 }, (_, j) => i === 0 ? j : j === 0 ? i : 0));
  for (let i = 1; i <= a.length; i++)
    for (let j = 1; j <= b.length; j++)
      dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] : 1 + Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]);
  return dp[a.length][b.length];
}

function createRoom(settings = {}) {
  const id = genCode();
  rooms[id] = {
    id,
    host: null,
    players: [],
    spectators: [],
    state: 'waiting',
    settings: {
      maxPlayers: 10,
      rounds: 3,
      drawTime: 80,
      wordChoices: 3,
      customWords: [],
      wordMode: 'normal',
      categories: Object.keys(wordLists),
      teamMode: false,
      suddenDeath: false,
      quickDraw: false,
      hintsEnabled: true,
      ...settings
    },
    currentRound: 0,
    drawerOrder: [],
    currentDrawerIndex: 0,
    currentWord: null,
    wordChoices: [],
    drawStrokes: [],
    timer: null,
    chooseTimer: null,
    hintTimer1: null,
    hintTimer2: null,
    timeLeft: 0,
    totalTime: 80,
    hintsRevealed: [],
    roundStartTime: null,
    roundScores: [],
    usedWords: [],
    teams: { red: [], blue: [] },
    scoreHistory: [], // [{round, scores:[{id,score}]}] for graph
  };
  return id;
}

function addPlayer(room, sid, name, avatar) {
  const player = {
    id: sid,
    name: (name || 'Player').substring(0, 20),
    score: 0,
    avatar: avatar || { color: `hsl(${Math.floor(Math.random()*360)},70%,60%)`, icon: 'πŸ˜€' },
    team: null,
    streak: 0,
    powerUps: { revealLetter: 1, timeWarp: 1, bomb: 1 },
    achievements: [],
    isDrawing: false,
    hasGuessed: false,
    guessTime: null,
    isSpectator: false,
    wordsDrawn: 0,
  };
  room.players.push(player);
  return player;
}

function getPlayer(room, sid) {
  return room.players.find(p => p.id === sid) || room.spectators.find(p => p.id === sid);
}

function clearAllTimers(room) {
  if (room.timer) { clearInterval(room.timer); room.timer = null; }
  if (room.chooseTimer) { clearTimeout(room.chooseTimer); room.chooseTimer = null; }
  if (room.hintTimer1) { clearTimeout(room.hintTimer1); room.hintTimer1 = null; }
  if (room.hintTimer2) { clearTimeout(room.hintTimer2); room.hintTimer2 = null; }
}

function shuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

function getRoomData(room) {
  return {
    id: room.id,
    host: room.host,
    state: room.state,
    settings: room.settings,
    players: room.players,
    spectators: room.spectators,
    currentRound: room.currentRound,
    totalRounds: room.settings.rounds,
    teams: room.teams,
  };
}

function broadcastPlayers(room) {
  io.to(room.id).emit('playerUpdate', { players: room.players });
}

// ─── Game Flow ───────────────────────────────────────────────────────────────
function startGame(room) {
  if (room.players.length === 0) return;
  room.state = 'playing';
  room.currentRound = 1;
  room.scoreHistory = [];
  room.usedWords = [];
  room.players.forEach(p => {
    p.score = 0; p.streak = 0; p.achievements = [];
    p.powerUps = { revealLetter: 1, timeWarp: 1, bomb: 1 };
  });

  if (room.settings.teamMode) assignTeams(room);

  room.drawerOrder = shuffle(room.players.map(p => p.id));
  room.currentDrawerIndex = 0;
  startRound(room);
}

function assignTeams(room) {
  room.teams = { red: [], blue: [] };
  room.players.forEach((p, i) => {
    p.team = i % 2 === 0 ? 'red' : 'blue';
    room.teams[p.team].push(p.id);
  });
}

function startRound(room) {
  clearAllTimers(room);
  room.players.forEach(p => { p.hasGuessed = false; p.isDrawing = false; p.guessTime = null; });
  room.drawStrokes = [];
  room.hintsRevealed = [];
  room.roundScores = [];
  room.currentWord = null;

  // Find drawer, skip if missing
  let drawerFound = false;
  while (!drawerFound && room.currentDrawerIndex < room.drawerOrder.length) {
    const drawerId = room.drawerOrder[room.currentDrawerIndex];
    const drawer = room.players.find(p => p.id === drawerId);
    if (drawer) { drawer.isDrawing = true; drawerFound = true; }
    else room.currentDrawerIndex++;
  }

  if (!drawerFound) { nextTurn(room); return; }

  const drawer = room.players.find(p => p.isDrawing);
  const choices = getWords(room.settings, room.settings.wordChoices);
  room.wordChoices = choices;
  room.state = 'choosing';

  io.to(room.id).emit('roundStart', {
    round: room.currentRound,
    totalRounds: room.settings.rounds,
    drawer: { id: drawer.id, name: drawer.name, avatar: drawer.avatar },
    players: room.players,
  });

  io.to(drawer.id).emit('chooseWord', { choices });

  room.chooseTimer = setTimeout(() => {
    if (room.state === 'choosing') {
      wordChosen(room, choices[Math.floor(Math.random() * choices.length)]);
    }
  }, 15000);
}

function wordChosen(room, word) {
  clearAllTimers(room);
  room.currentWord = word;
  room.usedWords.push(word);
  room.state = 'drawing';

  const drawTime = room.settings.quickDraw ? 20 : room.settings.drawTime;
  room.timeLeft = drawTime;
  room.totalTime = drawTime;
  room.roundStartTime = Date.now();

  const drawer = room.players.find(p => p.isDrawing);
  const mask = hintMask(word, []);
  const lengths = word.split(' ').map(w => w.length);

  io.to(drawer.id).emit('wordChosen', { word, hint: mask, lengths, isDrawer: true });
  socket_to_room_except(room.id, drawer.id, 'wordChosen', { word: null, hint: mask, lengths, isDrawer: false });

  // Auto hints
  if (room.settings.hintsEnabled) {
    room.hintTimer1 = setTimeout(() => { if (room.state === 'drawing') revealHint(room); }, drawTime * 500);
    room.hintTimer2 = setTimeout(() => { if (room.state === 'drawing') revealHint(room); }, drawTime * 750);
  }

  // Countdown
  room.timer = setInterval(() => {
    room.timeLeft--;
    io.to(room.id).emit('timerUpdate', { timeLeft: room.timeLeft, totalTime: room.totalTime });
    if (room.timeLeft <= 0) endRound(room);
  }, 1000);
}

function socket_to_room_except(roomId, exceptId, event, data) {
  io.to(roomId).except(exceptId).emit(event, data);
}

function revealHint(room) {
  const word = room.currentWord;
  if (!word) return;
  const unrevealed = [];
  word.split('').forEach((c, i) => { if (c !== ' ' && !room.hintsRevealed.includes(i)) unrevealed.push(i); });
  if (unrevealed.length === 0) return;
  const n = Math.max(1, Math.floor(unrevealed.length * 0.3));
  const picks = shuffle([...unrevealed]).slice(0, n);
  room.hintsRevealed.push(...picks);
  const drawer = room.players.find(p => p.isDrawing);
  const hint = hintMask(word, room.hintsRevealed);
  socket_to_room_except(room.id, drawer?.id || '', 'hintUpdate', { hint, revealed: room.hintsRevealed });
}

function checkGuess(room, sid, text) {
  if (!room.currentWord || room.state !== 'drawing') return 'ignore';
  const player = room.players.find(p => p.id === sid);
  if (!player || player.hasGuessed || player.isDrawing) return 'ignore';

  const guess = text.trim().toLowerCase();
  const answer = room.currentWord.toLowerCase();

  if (guess === answer) {
    const elapsed = (Date.now() - room.roundStartTime) / 1000;
    const timeRatio = Math.max(0, 1 - elapsed / room.totalTime);
    const baseScore = 200;
    const timeBonus = Math.round(timeRatio * 300);
    const firstBonus = room.roundScores.length === 0 ? 50 : 0;
    const streakBonus = player.streak * 25;
    const total = baseScore + timeBonus + firstBonus + streakBonus;

    player.hasGuessed = true;
    player.guessTime = elapsed;
    player.score += total;
    player.streak++;
    player.wordsDrawn;

    const drawer = room.players.find(p => p.isDrawing);
    if (drawer) {
      const drawerGain = Math.round(50 + (room.roundScores.length === 0 ? 0 : 10));
      drawer.score += drawerGain;
    }

    room.roundScores.push({ id: sid, score: total, time: elapsed });
    checkAchievements(room, player);

    const nonDrawers = room.players.filter(p => !p.isDrawing && !p.isSpectator);
    if (nonDrawers.every(p => p.hasGuessed)) setTimeout(() => endRound(room), 1500);

    return { correct: true, score: total, streak: player.streak, firstBonus };
  }

  const dist = levenshtein(guess, answer);
  if (dist <= 2 && guess.length > 2) return 'close';

  if (room.settings.suddenDeath) {
    player.score = Math.max(0, player.score - 15);
    broadcastPlayers(room);
  }
  return 'wrong';
}

function checkAchievements(room, player) {
  const unlocked = [];
  const add = (id, name, desc) => {
    if (!player.achievements.includes(id)) {
      player.achievements.push(id);
      unlocked.push({ id, name, desc });
    }
  };
  if (player.guessTime < 8) add('speed_demon', '⚑ Speed Demon', 'Guessed in under 8 seconds!');
  if (player.streak >= 3) add('on_fire', 'πŸ”₯ On Fire', '3 correct guesses in a row!');
  if (player.streak >= 5) add('unstoppable', 'πŸ’Ž Unstoppable', '5 in a row!');
  if (room.roundScores.length === 1) add('first_blood', '🩸 First Blood', 'First to guess the word!');
  if (room.hintsRevealed.length === 0 && player.guessTime < room.totalTime * 0.5)
    add('no_hints', 'πŸ•΅οΈ Sherlock', 'Guessed with zero hints revealed!');
  if (unlocked.length > 0) io.to(player.id).emit('achievementUnlocked', unlocked);
}

function endRound(room) {
  clearAllTimers(room);
  if (room.state === 'intermission' || room.state === 'ended') return;
  room.state = 'intermission';

  const drawer = room.players.find(p => p.isDrawing);

  // Picasso achievement
  const nonDrawers = room.players.filter(p => !p.isDrawing && !p.isSpectator);
  if (drawer && nonDrawers.length > 0 && nonDrawers.every(p => p.hasGuessed)) {
    if (!drawer.achievements.includes('picasso')) {
      drawer.achievements.push('picasso');
      io.to(drawer.id).emit('achievementUnlocked', [{ id: 'picasso', name: '🎨 Picasso', desc: 'Everyone guessed your drawing!' }]);
    }
    drawer.score += 100; // bonus
  }

  // Record score history
  room.scoreHistory.push({
    round: room.currentRound,
    drawerTurn: room.currentDrawerIndex,
    scores: room.players.map(p => ({ id: p.id, name: p.name, score: p.score }))
  });

  io.to(room.id).emit('roundEnd', {
    word: room.currentWord,
    scores: room.players.map(p => ({
      id: p.id, name: p.name, score: p.score, avatar: p.avatar,
      roundGain: room.roundScores.find(r => r.id === p.id)?.score || 0,
      guessTime: p.guessTime,
    })),
    drawStrokes: room.drawStrokes,
    drawer: drawer ? { id: drawer.id, name: drawer.name } : null,
    scoreHistory: room.scoreHistory,
  });

  room.timer = setTimeout(() => {
    if (!rooms[room.id]) return;
    nextTurn(room);
  }, 7000);
}

function nextTurn(room) {
  clearAllTimers(room);
  room.currentDrawerIndex++;

  if (room.currentDrawerIndex >= room.drawerOrder.length) {
    room.currentRound++;
    if (room.currentRound > room.settings.rounds) { endGame(room); return; }
    room.drawerOrder = shuffle(room.players.map(p => p.id));
    room.currentDrawerIndex = 0;
  }

  if (room.players.length < 1) {
    room.state = 'waiting';
    io.to(room.id).emit('gameAborted', { reason: 'Not enough players' });
    return;
  }
  startRound(room);
}

function endGame(room) {
  clearAllTimers(room);
  room.state = 'ended';

  const sorted = [...room.players].sort((a, b) => b.score - a.score);

  // Victory achievement
  if (sorted[0]) {
    const winner = sorted[0];
    if (!winner.achievements.includes('champion')) {
      winner.achievements.push('champion');
      io.to(winner.id).emit('achievementUnlocked', [{ id: 'champion', name: 'πŸ‘‘ Champion', desc: 'You won the game!' }]);
    }
  }

  io.to(room.id).emit('gameEnd', {
    players: sorted.map((p, i) => ({
      id: p.id, name: p.name, score: p.score,
      rank: i + 1, achievements: p.achievements, avatar: p.avatar, streak: p.streak
    })),
    scoreHistory: room.scoreHistory,
  });

  setTimeout(() => { if (rooms[room.id]) delete rooms[room.id]; }, 60000);
}

// ─── Socket.IO ───────────────────────────────────────────────────────────────
io.on('connection', (socket) => {

  socket.on('createRoom', ({ name, avatar, settings }) => {
    const id = createRoom(settings || {});
    const room = rooms[id];
    room.host = socket.id;
    const player = addPlayer(room, socket.id, name, avatar);
    socket.join(id);
    socket.roomId = id;
    socket.emit('roomCreated', { roomId: id, player, room: getRoomData(room) });
  });

  socket.on('joinRoom', ({ roomId, name, avatar, asSpectator }) => {
    const code = (roomId || '').toUpperCase().trim();
    const room = rooms[code];
    if (!room) { socket.emit('joinError', { message: 'Room not found. Check the code!' }); return; }
    if (room.players.length >= room.settings.maxPlayers) {
      socket.emit('joinError', { message: 'Room is full! (max ' + room.settings.maxPlayers + ')' }); return;
    }

    socket.join(code);
    socket.roomId = code;

    let player;
    if (asSpectator) {
      player = addPlayer(room, socket.id, name, avatar);
      player.isSpectator = true;
      room.players = room.players.filter(p => p.id !== socket.id);
      room.spectators.push(player);
    } else {
      player = addPlayer(room, socket.id, name, avatar);
      // If joining mid-game, mark as late joiner (they wait for next round to draw)
      if (room.state !== 'waiting') {
        player.lateJoin = true;
      }
    }

    socket.emit('roomJoined', { player, room: getRoomData(room) });
    socket.to(code).emit('playerJoined', { player, players: room.players, spectators: room.spectators });
  });

  socket.on('joinRandom', ({ name, avatar }) => {
    // Find a waiting matchmaking room (including ones in grace period with 0 players)
    let room = Object.values(rooms).find(r =>
      r.state === 'waiting' &&
      r.isMatchmaking === true &&
      r.players.length < r.settings.maxPlayers
    );

    const isNewRoom = !room;
    if (!room) {
      const id = createRoom();
      room = rooms[id];
      room.isMatchmaking = true;
      room.host = socket.id;
      room.mmStartTime = Date.now(); // track when matchmaking started
    }

    // Cancel grace-period deletion timer if rejoining
    if (room._graceTimer) {
      clearTimeout(room._graceTimer);
      delete room._graceTimer;
    }

    const player = addPlayer(room, socket.id, name, avatar);
    socket.join(room.id);
    socket.roomId = room.id;
    if (room.players.length === 1) room.host = socket.id;

    socket.emit('roomJoined', { player, room: getRoomData(room) });
    socket.to(room.id).emit('playerJoined', { player, players: room.players });

    if (room.players.length >= 2) {
      // ── 2+ players: cancel solo timer, start 10s multiplayer countdown ──
      if (room.matchmakingTimer)   { clearTimeout(room.matchmakingTimer);   room.matchmakingTimer = null; }
      if (room.matchmakingCountdown) { clearInterval(room.matchmakingCountdown); room.matchmakingCountdown = null; }

      let secs = 10;
      io.to(room.id).emit('matchmakingUpdate', { players: room.players.length, needed: 2, countdown: secs, waiting: false });

      room.matchmakingCountdown = setInterval(() => {
        secs--;
        io.to(room.id).emit('matchmakingUpdate', { players: room.players.length, needed: 2, countdown: secs, waiting: false });
        if (secs <= 0) { clearInterval(room.matchmakingCountdown); room.matchmakingCountdown = null; }
      }, 1000);

      room.matchmakingTimer = setTimeout(() => {
        if (!rooms[room.id] || room.state !== 'waiting') return;
        room.isMatchmaking = false;
        startGame(room);
      }, 10000);

    } else {
      // ── 1 player: only start timers if NOT already running (prevents reset on reconnect) ──
      if (!room.matchmakingTimer) {
        room.mmStartTime = Date.now();
        const SOLO_WAIT = 30000;

        // Send initial countdown
        io.to(room.id).emit('matchmakingUpdate', { players: 1, needed: 2, countdown: 30, waiting: true });

        room.matchmakingCountdown = setInterval(() => {
          if (!rooms[room.id]) { clearInterval(room.matchmakingCountdown); return; }
          const elapsed = Date.now() - room.mmStartTime;
          const remaining = Math.max(0, Math.ceil((SOLO_WAIT - elapsed) / 1000));
          io.to(room.id).emit('matchmakingUpdate', {
            players: room.players.length,
            needed: 2,
            countdown: remaining,
            waiting: room.players.length < 2
          });
          if (remaining <= 0) { clearInterval(room.matchmakingCountdown); room.matchmakingCountdown = null; }
        }, 1000);

        room.matchmakingTimer = setTimeout(() => {
          if (!rooms[room.id] || room.state !== 'waiting') return;
          if (room.players.length === 0) { delete rooms[room.id]; return; } // nobody reconnected
          room.isMatchmaking = false;
          room.settings.rounds = 3;
          startGame(room);
        }, SOLO_WAIT);

      } else {
        // Timer already running β€” just send current remaining time to this (re)joining socket
        const elapsed = Date.now() - (room.mmStartTime || Date.now());
        const remaining = Math.max(0, Math.ceil((30000 - elapsed) / 1000));
        socket.emit('matchmakingUpdate', { players: room.players.length, needed: 2, countdown: remaining, waiting: true });
      }
    }
  });

  // CRITICAL: When page reloads after game starts, new socket must rejoin room
  socket.on('rejoinGame', ({ roomId, name, avatar }) => {
    const code = (roomId || '').toUpperCase().trim();
    const room = rooms[code];
    if (!room) { socket.emit('rejoinError', { message: 'Room expired or not found' }); return; }

    socket.join(code);
    socket.roomId = code;

    // Check if player with same name already exists (reconnect)
    let player = room.players.find(p => p.name === name);
    if (player) {
      // Update their socket id to the new one
      const oldId = player.id;
      player.id = socket.id;
      // Update host if needed
      if (room.host === oldId) room.host = socket.id;
      // Update drawerOrder
      const di = room.drawerOrder.indexOf(oldId);
      if (di !== -1) room.drawerOrder[di] = socket.id;
    } else {
      // New player joining mid-game
      if (room.players.length >= room.settings.maxPlayers) {
        socket.emit('rejoinError', { message: 'Room is full!' }); return;
      }
      player = addPlayer(room, socket.id, name, avatar);
      player.lateJoin = true;
    }

    // Send current game state so they can sync up
    const drawer = room.players.find(p => p.isDrawing);
    socket.emit('gameRejoined', {
      player,
      room: getRoomData(room),
      state: room.state,
      round: room.currentRound,
      totalRounds: room.settings.rounds,
      drawer: drawer ? { id: drawer.id, name: drawer.name, avatar: drawer.avatar } : null,
      players: room.players,
      hint: room.currentWord ? hintMask(room.currentWord, room.hintsRevealed) : null,
      timeLeft: room.timeLeft,
      totalTime: room.totalTime,
      drawStrokes: room.drawStrokes,
      isDrawer: drawer?.id === socket.id,
      word: drawer?.id === socket.id ? room.currentWord : null,
    });

    // Tell others this player is back
    socket.to(code).emit('playerJoined', { player, players: room.players });
  });

  socket.on('startGame', () => {
    const room = rooms[socket.roomId];
    if (!room) return;
    if (room.host !== socket.id) { socket.emit('gameError', { message: 'Only the host can start' }); return; }
    if (room.players.length < 2) { socket.emit('gameError', { message: 'Need at least 2 players' }); return; }
    startGame(room);
  });

  socket.on('chooseWord', ({ word }) => {
    const room = rooms[socket.roomId];
    if (!room || room.state !== 'choosing') return;
    const player = room.players.find(p => p.id === socket.id);
    if (!player?.isDrawing || !room.wordChoices.includes(word)) return;
    wordChosen(room, word);
  });

  socket.on('draw', (data) => {
    const room = rooms[socket.roomId];
    if (!room || room.state !== 'drawing') return;
    const player = room.players.find(p => p.id === socket.id);
    if (!player?.isDrawing) return;
    const stamped = { ...data, t: Date.now() - (room.roundStartTime || Date.now()) };
    room.drawStrokes.push(stamped);
    socket.to(socket.roomId).emit('draw', data);
  });

  socket.on('clearCanvas', () => {
    const room = rooms[socket.roomId];
    if (!room || room.state !== 'drawing') return;
    const player = room.players.find(p => p.id === socket.id);
    if (!player?.isDrawing) return;
    room.drawStrokes = [{ type: 'clear', t: 0 }];
    io.to(socket.roomId).emit('clearCanvas');
  });

  socket.on('guess', ({ text }) => {
    const room = rooms[socket.roomId];
    if (!room || !text) return;
    const player = getPlayer(room, socket.id);
    if (!player) return;

    // Block drawer from revealing word in chat
    if (player.isDrawing) {
      socket.emit('chatMessage', { system: true, text: '🀫 You cannot chat while drawing!', type: 'warn' });
      return;
    }

    const result = checkGuess(room, socket.id, text);

    if (result === 'ignore') return;

    if (result?.correct) {
      socket.emit('correctGuess', { score: result.score, streak: result.streak, firstBonus: result.firstBonus });
      io.to(socket.roomId).emit('chatMessage', {
        system: true,
        text: `πŸŽ‰ ${player.name} guessed it! (+${result.score}pts${result.streak > 1 ? ` πŸ”₯x${result.streak}` : ''})`,
        type: 'correct'
      });
      broadcastPlayers(room);
    } else if (result === 'close') {
      socket.emit('chatMessage', { system: true, text: `🌑️ So close! Keep trying...`, type: 'close' });
      io.to(socket.roomId).emit('chatMessage', { sender: player.name, text: '...', playerId: socket.id, type: 'guess' });
    } else {
      io.to(socket.roomId).emit('chatMessage', { sender: player.name, text, playerId: socket.id, type: 'guess' });
    }
  });

  socket.on('chatMessage', ({ text }) => {
    const room = rooms[socket.roomId];
    if (!room || !text) return;
    const player = getPlayer(room, socket.id);
    if (!player) return;
    // Only allow chat in non-drawing state or for spectators
    if (room.state === 'drawing' && !player.isSpectator) {
      // This goes through guess flow - ignore raw chat
      return;
    }
    io.to(socket.roomId).emit('chatMessage', { sender: player.name, text: text.substring(0, 120), playerId: socket.id, type: 'chat' });
  });

  socket.on('usePowerUp', ({ type }) => {
    const room = rooms[socket.roomId];
    if (!room || room.state !== 'drawing') return;
    const player = room.players.find(p => p.id === socket.id);
    if (!player || player.isDrawing || !player.powerUps[type] || player.powerUps[type] <= 0) return;

    player.powerUps[type]--;

    if (type === 'revealLetter') {
      revealHint(room);
      io.to(socket.roomId).emit('chatMessage', { system: true, text: `πŸ” ${player.name} revealed a letter!`, type: 'powerup' });
    } else if (type === 'timeWarp') {
      room.timeLeft = Math.min(room.timeLeft + 15, room.totalTime);
      io.to(socket.roomId).emit('timerUpdate', { timeLeft: room.timeLeft, totalTime: room.totalTime });
      io.to(socket.roomId).emit('chatMessage', { system: true, text: `⏰ ${player.name} warped time! +15s`, type: 'powerup' });
    } else if (type === 'bomb') {
      room.drawStrokes = [{ type: 'clear', t: Date.now() - room.roundStartTime }];
      io.to(socket.roomId).emit('clearCanvas');
      io.to(socket.roomId).emit('chatMessage', { system: true, text: `πŸ’£ ${player.name} dropped a BOMB! Canvas cleared!`, type: 'powerup' });
    }

    socket.emit('powerUpUsed', { type, remaining: player.powerUps });
  });

  socket.on('reaction', ({ emoji }) => {
    const room = rooms[socket.roomId];
    if (!room) return;
    const player = getPlayer(room, socket.id);
    io.to(socket.roomId).emit('reaction', { emoji, name: player?.name || 'Someone' });
  });

  socket.on('updateSettings', (settings) => {
    const room = rooms[socket.roomId];
    if (!room || room.host !== socket.id || room.state !== 'waiting') return;
    Object.assign(room.settings, settings);
    io.to(socket.roomId).emit('settingsUpdated', room.settings);
  });

  socket.on('kickPlayer', ({ playerId }) => {
    const room = rooms[socket.roomId];
    if (!room || room.host !== socket.id) return;
    const target = io.sockets.sockets.get(playerId);
    if (target) {
      target.emit('kicked', { reason: 'You were kicked by the host' });
      target.leave(socket.roomId);
    }
    room.players = room.players.filter(p => p.id !== playerId);
    io.to(socket.roomId).emit('playerLeft', { playerId, players: room.players });
  });

  socket.on('requestReplay', () => {
    // Allow replay of last round strokes - sent on roundEnd already
  });

  socket.on('disconnect', () => {
    const room = rooms[socket.roomId];
    if (!room) return;

    const wasDrawing = room.players.find(p => p.id === socket.id)?.isDrawing;
    room.players = room.players.filter(p => p.id !== socket.id);
    room.spectators = room.spectators.filter(p => p.id !== socket.id);

    if (room.players.length === 0 && room.spectators.length === 0) {
      if (room.isMatchmaking && room.matchmakingTimer) {
        // Keep room + matchmaking timers alive; give mobile 15s to reconnect
        room._graceTimer = setTimeout(() => {
          const r = rooms[socket.roomId];
          if (r && r.players.length === 0) {
            if (r.matchmakingTimer)   clearTimeout(r.matchmakingTimer);
            if (r.matchmakingCountdown) clearInterval(r.matchmakingCountdown);
            clearAllTimers(r);
            delete rooms[socket.roomId];
          }
        }, 15000);
      } else {
        clearAllTimers(room);
        if (room.matchmakingTimer)   clearTimeout(room.matchmakingTimer);
        if (room.matchmakingCountdown) clearInterval(room.matchmakingCountdown);
        delete rooms[socket.roomId];
      }
      return;
    }

    if (room.host === socket.id && room.players.length > 0) {
      room.host = room.players[0].id;
      io.to(room.host).emit('youAreHost');
    }

    io.to(socket.roomId).emit('playerLeft', { playerId: socket.id, players: room.players });

    if (wasDrawing && (room.state === 'drawing' || room.state === 'choosing')) {
      endRound(room);
    }

    if (room.players.length < 1 && room.state !== 'waiting' && room.state !== 'ended') {
      clearAllTimers(room);
      room.state = 'waiting';
      io.to(socket.roomId).emit('gameAborted', { reason: 'Not enough players to continue' });
    }
  });
});

server.listen(PORT, '0.0.0.0', () => {
  console.log(`🎨 Drawable running at http://localhost:${PORT}`);
});