İçeriğe geç
680 satır · 23,3 KBHamİndir
// Olay -> aksiyon: yorum, beğeni, hediye, takip, paylaşım geldiğinde sahnede ne olacağına karar verir.
import * as THREE from 'three';
import { Avatar, danceMode, GROUP_MODES } from '../scene/avatar.js';
import { formationTargets } from './formation.js';
import { DOOR, routeBetween, groundAt, STAGE_SPOT } from '../scene/tables.js';
import { Viewers, Scores, findCommand, genderCommand, isFarewell, normalizeText } from './state.js';

// Dans moduna göre sahneye çıkan müzisyenler
const BANDS = {
  halay: [{ kind: 'davul', name: '🥁 Davulcu', g: 'm' }, { kind: 'zurna', name: '🎺 Zurnacı', g: 'm' }],
  horon: [{ kind: 'kemence', name: '🎻 Kemençeci', g: 'm' }, { kind: 'tulum', name: '🎶 Tulumcu', g: 'm' }],
  oyun: [{ kind: 'darbuka', name: '🪘 Darbukacı', g: 'f' }, { kind: 'klarnet', name: '🎷 Klarnetçi', g: 'm' }],
};
const BAND_SPOTS = [{ x: -1.25, z: -15.85, enter: -3.6 }, { x: 2.05, z: -15.75, enter: 3.6 }];
const BAND_BANNER = {
  halay: '🥁 Davul zurna sahnede! Halay başlasın!',
  horon: '🎻 Kemençe ve tulum sahnede! Horon başlasın!',
  oyun: '🪘 Darbuka ve klarnet sahnede!',
};

const ZONE_LABEL = { normal: '', diva: 'diva', loca: 'loca', dans: 'dans', sahne: 'sahne' };

export class Game {
  constructor({ scene, layout, rules, audio, hud, venue, confetti }) {
    this.scene = scene;
    this.layout = layout;
    this.rules = rules;
    this.audio = audio;
    this.hud = hud;
    this.venue = venue;
    this.confetti = confetti;
    this.viewers = new Viewers();
    this.scores = new Scores();
    this.likeTotal = 0;
    this.likeGoal = rules.likes?.goal ?? 300;
    this.likeBase = 0;
    this.lastSongSkip = -Infinity;
    this.genders = new Map(); // id -> 'f' | 'm' (izleyicinin seçtiği cinsiyet)
    this.singer = null; // sahnedeki izleyici
    this.singerSince = 0;
    this.stageQueue = []; // sahne sırası (id)
    this.stageHold = false; // panelden: süre durdu, şarkıcı sen indirene kadar kalır
    this.viewerCount = null; // TikTok'taki anlık izleyici sayısı
    this.band = []; // sahnedeki müzisyenler [{ avatar, leaving }]
    this.bandMode = 'normal';
    this.tickTimer = 0;
    this.hud.setLikes(this.likeTotal, this.likeGoal, this.likeBase);
  }

  get freeMode() {
    return this.rules.freeMode !== false;
  }

  // ---------- Yer (koltuk / dans noktası) yönetimi ----------
  spotsOf(zone) {
    if (zone === 'sahne') return [STAGE_SPOT];
    if (zone === 'dans') return this.layout.danceSpots.slice(0, this.rules.capacity?.dans ?? 20);
    const list = this.layout.seats[zone];
    const cap = this.rules.capacity?.[zone];
    return cap ? list.slice(0, cap) : list;
  }

  acquire(zone, requester) {
    const spots = this.spotsOf(zone);
    let free = spots.filter((s) => !s.occupant);
    if (!free.length) {
      const occupants = spots.map((s) => s.occupant).filter((v) => v && v !== requester);
      if (!occupants.length) return null;
      if (zone === 'normal') {
        // en uzun süredir sessiz olan mekandan ayrılır
        const idle = occupants.sort((a, b) => a.lastActive - b.lastActive)[0];
        this.leave(idle);
      } else {
        // bölgeye en erken gelen normal masaya döner
        const oldest = occupants.sort((a, b) => a.zoneSince - b.zoneSince)[0];
        oldest.avatar.say('Yerimi kaptırdım 😢', 3);
        this.sendTo(oldest, 'normal');
      }
      free = spots.filter((s) => !s.occupant);
    }
    if (!free.length) return null;
    return free[Math.floor(Math.random() * free.length)];
  }

  release(v) {
    if (v.spot && v.spot.occupant === v) v.spot.occupant = null;
    v.spot = null;
  }

  sendTo(v, zone) {
    if (v.zone === zone) return false;
    this.release(v);
    const spot = this.acquire(zone, v);
    if (!spot) {
      if (v.zone !== 'normal' && zone !== 'normal') return this.sendTo(v, 'normal');
      return false;
    }
    spot.occupant = v;
    v.spot = spot;
    v.zone = zone;
    v.zoneSince = performance.now();
    const av = v.avatar;
    av.setLabelClass(ZONE_LABEL[zone]);
    const from = { x: av.root.position.x, z: av.root.position.z };
    av.walkTo(routeBetween(from, spot), () => {
      if (v.spot !== spot) return;
      av.setPosition(spot.x, spot.z);
      if (zone === 'dans') av.dance();
      else if (zone === 'sahne') av.sing();
      else av.sit(spot.facing, spot.seatY);
    });
    return true;
  }

  /** Belirli bir noktaya (koltuk değil) yürüt: ikili dansta partnerin karşısı. */
  placeAt(v, spot, pos, arrive) {
    this.release(v);
    spot.occupant = v;
    v.spot = spot;
    v.zone = spot.zone;
    v.zoneSince = performance.now();
    const av = v.avatar;
    av.setLabelClass(ZONE_LABEL[spot.zone]);
    const from = { x: av.root.position.x, z: av.root.position.z };
    av.walkTo(routeBetween(from, { ...pos, zone: spot.zone }), () => {
      if (v.spot !== spot) return;
      av.setPosition(pos.x, pos.z);
      arrive();
    });
  }

  leave(v) {
    if (!v || v.zone === 'leaving') return;
    this.release(v);
    v.zone = 'leaving';
    const av = v.avatar;
    av.setLabelClass('');
    const from = { x: av.root.position.x, z: av.root.position.z };
    av.walkTo(routeBetween(from, { x: DOOR.x, z: DOOR.z }), () => {
      av.dispose();
      if (this.viewers.get(v.id) === v) this.viewers.remove(v.id);
    });
  }

  ensure(user) {
    let v = this.viewers.get(user.id);
    if (v && v.zone !== 'leaving') {
      v.lastActive = performance.now();
      return v;
    }
    if (v) {
      // çıkmak üzereyken geri döndü
      v.avatar.dispose();
      this.viewers.remove(user.id);
    }
    const max = this.rules.maxAvatars ?? 60;
    const active = this.viewers.all().filter((x) => x.zone !== 'leaving');
    if (active.length >= max) {
      const idle = active.sort((a, b) => a.lastActive - b.lastActive)[0];
      this.leave(idle);
    }
    v = this.viewers.add(user);
    v.avatar = new Avatar(user.name, this.genders.get(user.id));
    v.avatar.setPosition(DOOR.x + (Math.random() - 0.5) * 2, DOOR.z);
    this.scene.add(v.avatar.root);
    if (!this.sendTo(v, 'normal')) {
      // hiç yer yoksa (olmamalı) kapıda bekler
      v.zone = 'normal';
    }
    return v;
  }

  // ---------- Olaylar ----------
  handle(e) {
    if (e?.type === 'viewers') {
      this.viewerCount = Math.max(0, e.count | 0);
      return;
    }
    if (!e?.user?.id) return;
    switch (e.type) {
      case 'chat': return this.onChat(e);
      case 'like': return this.onLike(e);
      case 'gift': return this.onGift(e);
      case 'join': if (this.rules.spawnOnJoin !== false) this.ensure(e.user); return;
      case 'follow': {
        const v = this.ensure(e.user);
        v.avatar.pop('💖');
        this.hud.feed(`💖 ${e.user.name} takip etti`);
        return;
      }
      case 'kons':
        this.giveKons(e.user);
        return;
      case 'share': {
        const v = this.ensure(e.user);
        v.avatar.pop('🔁');
        this.hud.feed(`🔁 ${e.user.name} yayını paylaştı`);
        return;
      }
    }
  }

  onChat(e) {
    const v = this.ensure(e.user);
    v.comments++;
    this.scores.bump(e.user, { comments: 1 });
    const text = (e.text || '').trim();
    const singing = this.singer === v && v.zone === 'sahne';
    if (text) {
      if (singing) v.avatar.say('🎤 ' + text, (this.rules.bubbleSeconds ?? 5) + 2, 'sing');
      else v.avatar.say(text, this.rules.bubbleSeconds ?? 5);
    }
    if (isFarewell(text, this.rules.bye)) {
      v.avatar.pop('👋');
      this.hud.feed(`👋 ${v.name} mekandan ayrıldı`);
      this.leave(v);
      return;
    }
    const g = genderCommand(text, this.rules.gender);
    if (g) {
      this.changeGender(v, g === 'toggle' ? (v.avatar.fem ? 'm' : 'f') : g);
      return;
    }
    const cmd = findCommand(text, this.rules.commands);
    if (!cmd) return;
    // "@isim dans": o kişiyle karşılıklı dans
    const mention = cmd === 'dans' && text.match(/@([^\s@,!?.]+)/);
    if (mention && this.freeMode) {
      const want = normalizeText(mention[1]);
      const partner = this.viewers.all().find((x) => x !== v && x.zone !== 'leaving' && (normalizeText(x.id) === want || normalizeText(x.name) === want));
      if (partner) {
        this.pairDance(v, partner);
        return;
      }
      v.avatar.pop('❓');
      this.hud.feed(`❓ @${mention[1]} mekanda yok, ${v.name} tek dans ediyor`);
    }

    const name = e.user.name;
    switch (cmd) {
      case 'diva':
      case 'loca':
      case 'dans':
        if (!this.freeMode) {
          v.avatar.pop('🎁');
          return;
        }
        this.goZone(v, cmd);
        return;
      case 'masa':
        this.sendTo(v, 'normal');
        return;
      case 'sahne':
        this.wantStage(v);
        return;
      case 'sarki': {
        const now = performance.now();
        const cd = (this.rules.songSkipCooldownSeconds ?? 60) * 1000;
        if (this.audio.mode !== 'files' && this.audio.mode !== 'youtube') return;
        if (now - this.lastSongSkip < cd) {
          v.avatar.pop('⏳');
          return;
        }
        this.lastSongSkip = now;
        this.audio.next();
        this.hud.banner(`🎵 ${name} şarkıyı değiştirdi`, 'song');
      }
    }
  }

  // ---------- Sahne: sırayla mikrofona çıkma ----------
  wantStage(v) {
    if (this.singer === v) return;
    if (!this.singer) {
      this.startSinger(v);
      return;
    }
    if (!this.stageQueue.includes(v.id)) this.stageQueue.push(v.id);
    const n = this.stageQueue.indexOf(v.id) + 1;
    v.avatar.pop('⏳');
    this.hud.feed(`🎤 ${v.name} sahne sırasında (${n}.)`);
  }

  startSinger(v) {
    this.stageQueue = this.stageQueue.filter((id) => id !== v.id);
    if (STAGE_SPOT.occupant && STAGE_SPOT.occupant !== v) this.sendTo(STAGE_SPOT.occupant, 'normal');
    if (v.zone === 'sahne') this.release(v), (v.zone = null);
    if (!this.sendTo(v, 'sahne')) return;
    this.singer = v;
    this.singerSince = performance.now();
    v.avatar.pop('🎤');
    this.hud.banner(`🎤 SAHNEDE: ${v.name}! Yazdıkları şarkı olsun`, 'diva');
  }

  /** Şarkıcıyı alkışla sahneden indir. */
  endSinger() {
    const s = this.singer;
    if (!s) return;
    this.singer = null;
    s.avatar.pop('👏');
    this.hud.feed(`👏 ${s.name} için alkış!`);
    this.confetti.burst(new THREE.Vector3(STAGE_SPOT.x, 2.6, STAGE_SPOT.z), 90, 2.5);
    this.sendTo(s, 'normal');
  }

  // ---------- Panelden sahne ----------
  stageNext() {
    this.endSinger();
    this.updateStage();
  }

  setStageHold(on) {
    if (this.stageHold && !on) this.singerSince = performance.now(); // süre baştan başlasın
    this.stageHold = !!on;
  }

  stageUp(user) {
    const want = normalizeText(user.id);
    let v = this.viewers.all().find((x) => x.zone !== 'leaving' && (normalizeText(x.id) === want || normalizeText(x.name) === want));
    if (!v) v = this.ensure(user);
    v.lastActive = performance.now();
    if (this.singer === v) return;
    this.endSinger();
    this.startSinger(v);
  }

  /** Panelde gösterilecek sahne durumu. */
  stageInfo() {
    const s = this.singer;
    const secs = this.rules.stage?.seconds ?? 45;
    return {
      singer: s ? s.name : null,
      left: s && !this.stageHold ? Math.max(0, Math.ceil(secs - (performance.now() - this.singerSince) / 1000)) : null,
      queue: this.stageQueue.map((id) => this.viewers.get(id)?.name).filter(Boolean),
    };
  }

  updateStage() {
    const s = this.singer;
    if (s) {
      const secs = this.rules.stage?.seconds ?? 45;
      if (s.zone !== 'sahne' || this.viewers.get(s.id) !== s) {
        this.singer = null;
      } else if (!this.stageHold && performance.now() - this.singerSince > secs * 1000) {
        this.endSinger();
      }
    }
    while (!this.singer && this.stageQueue.length) {
      const v = this.viewers.get(this.stageQueue.shift());
      if (v && v.zone !== 'leaving') this.startSinger(v);
    }
  }

  // ---------- İkili dans ----------
  pairDance(a, b) {
    this.unpair(a);
    this.unpair(b);
    this.release(a);
    this.release(b);
    const spots = this.spotsOf('dans');
    // aynı sırada yan yana iki boş nokta ara (pist 4 sütun)
    let sa = null;
    let sb = null;
    for (let i = 0; i < spots.length - 1 && !sa; i++) {
      if (i % 4 !== 3 && !spots[i].occupant && !spots[i + 1].occupant) [sa, sb] = [spots[i], spots[i + 1]];
    }
    if (!sa) {
      sa = this.acquire('dans', a);
      if (sa) sa.occupant = a;
      sb = this.acquire('dans', b);
      if (sa) sa.occupant = null;
    }
    if (!sa || !sb) {
      this.goZone(a, 'dans');
      return;
    }
    // yan yanaysa ortada karşılıklı dursunlar
    const near = Math.hypot(sa.x - sb.x, sa.z - sb.z) < 2.6;
    const mx = (sa.x + sb.x) / 2;
    const mz = (sa.z + sb.z) / 2;
    const pa = near ? { x: mx - 0.29, z: mz } : { x: sa.x, z: sa.z };
    const pb = near ? { x: mx + 0.29, z: mz } : { x: sb.x, z: sb.z };
    if (near) a.pair = b.pair = { a, b, cx: mx, cz: mz, r: 0.29, angle: Math.PI / 2 };
    const fa = Math.atan2(pb.x - pa.x, pb.z - pa.z);
    const fb = Math.atan2(pa.x - pb.x, pa.z - pb.z);
    a.partner = b;
    b.partner = a;
    this.placeAt(a, sa, pa, () => { a.avatar.dance(); if (a.partner === b) a.avatar.pairWith(fa); });
    this.placeAt(b, sb, pb, () => { b.avatar.dance(); if (b.partner === a) b.avatar.pairWith(fb); });
    a.avatar.pop('💞');
    b.avatar.pop('💞');
    this.hud.feed(`💞 ${a.name} ile ${b.name} dans ediyor`);
  }

  unpair(v) {
    const p = v.partner;
    if (!p) return;
    v.partner = null;
    v.pair = null;
    v.avatar.pairFacing = null;
    if (p.partner === v) {
      p.partner = null;
      p.pair = null;
      p.avatar.pairFacing = null;
    }
  }

  // ---------- Müzisyenler ----------
  setBand(mode) {
    this.bandMode = mode;
    // eskiler perdenin arkasına yürüyüp gider
    for (const b of this.band) {
      if (b.leaving) continue;
      b.leaving = true;
      const av = b.avatar;
      av.state = 'idle';
      av.walkTo([{ x: b.spot.enter, z: -16.3 }], () => {
        av.dispose();
        this.band = this.band.filter((x) => x !== b);
      });
    }
    const list = BANDS[mode];
    if (!list) return;
    list.forEach((m, i) => {
      const spot = BAND_SPOTS[i];
      const av = new Avatar(m.name, m.g);
      av.setLabelClass('band');
      av.isBand = true;
      av.bandCostume = mode === 'halay' || mode === 'horon' ? mode : null;
      av.setPosition(spot.enter, -16.3);
      this.scene.add(av.root);
      const b = { avatar: av, spot, leaving: false };
      av.walkTo([{ x: spot.x, z: spot.z }], () => {
        if (!b.leaving) av.play(m.kind);
      });
      this.band.push(b);
    });
    this.hud.banner(BAND_BANNER[mode], 'party');
  }

  /** İkili (samimi) dans: çift ortadaki nokta etrafında ağır ağır döner. */
  updatePairs(dt) {
    const seen = new Set();
    for (const v of this.viewers.map.values()) {
      const p = v.pair;
      if (!p || seen.has(p) || !v.partner) continue;
      seen.add(p);
      const a = p.a.avatar;
      const b = p.b.avatar;
      if (a.state !== 'dance' || b.state !== 'dance' || a.formation || b.formation) continue;
      p.angle += dt * 0.32;
      const sx = Math.sin(p.angle) * p.r;
      const sz = Math.cos(p.angle) * p.r;
      a.spotX = p.cx - sx; a.spotZ = p.cz - sz;
      b.spotX = p.cx + sx; b.spotZ = p.cz + sz;
      const fa = Math.atan2(sx, sz);
      a.pairFacing = a.targetFacing = fa;
      b.pairFacing = b.targetFacing = fa + Math.PI;
      p.heart = (p.heart || 0) + dt;
      if (p.heart > 7) {
        p.heart = 0;
        a.pop('💕');
      }
    }
  }

  changeGender(v, g) {
    this.genders.set(v.id, g);
    if (!v.avatar.setGender(g)) return;
    v.avatar.pop(g === 'f' ? '💃' : '🕺');
    this.hud.feed(`🔄 ${v.name} ${g === 'f' ? 'kadın' : 'erkek'} oldu`);
  }

  goZone(v, zone) {
    const moved = this.sendTo(v, zone);
    if (!moved) return;
    const name = v.name;
    if (zone === 'diva') {
      this.hud.banner(`👑 ${name} DİVALAR MASASINA oturdu`, 'diva');
      v.avatar.pop('👑');
    } else if (zone === 'loca') {
      this.hud.banner(`🥂 ${name} ÖZEL LOCA'ya geçti`, 'loca');
      v.avatar.pop('🥂');
    } else if (zone === 'dans') {
      this.hud.feed(`💃 ${name} piste çıktı`);
      v.avatar.pop('💃');
    }
  }

  onLike(e) {
    const v = this.ensure(e.user);
    const n = Math.max(1, e.count | 0);
    v.likes += n;
    this.scores.bump(e.user, { likes: n });
    const now = performance.now();
    if (!v.lastHeart || now - v.lastHeart > 3000) {
      v.lastHeart = now;
      v.avatar.pop('❤️');
    }
    this.likeTotal += n;
    if (this.likeTotal >= this.likeGoal) {
      this.venue.party(10);
      this.confetti.burst(new THREE.Vector3(0, 6, -6), 350, 9);
      this.hud.banner('🎉 PARTİ ZAMANI! 🎉', 'party');
      this.likeBase = this.likeGoal;
      const step = this.rules.likes?.goalStep ?? 300;
      while (this.likeGoal <= this.likeTotal) this.likeGoal += step;
    }
    this.hud.setLikes(this.likeTotal, this.likeGoal, this.likeBase);
  }

  /** Kons: içki ısmarlandı -> kişinin elinde kadeh, isminde 🥂 sayısı, duyuru */
  giveKons(user) {
    const v = this.ensure(user);
    v.kons = (v.kons || 0) + 1;
    v.avatar.setKons(v.kons);
    v.avatar.pop('🥂');
    const p = v.avatar.root.position;
    this.confetti.burst(new THREE.Vector3(p.x, 2.2, p.z), 50, 1.5);
    this.hud.banner(`🥂 ${v.name} için KONS geldi!${v.kons > 1 ? ` (${v.kons}. kons)` : ''}`, 'loca');
  }

  /** Hediye: sadece teşekkür. Ödül / jeton yazısı yok (TikTok hediye karşılığı otomatik ödülü kısıtlıyor). */
  onGift(e) {
    const v = this.ensure(e.user);
    v.avatar.pop('💖');
    this.hud.feed(`💖 ${e.user.name} teşekkürler!`);
  }

  // ---------- Döngü ----------
  update(dt, beat) {
    this.time = (this.time || 0) + dt;
    if (danceMode.value !== this.bandMode) this.setBand(danceMode.value);
    for (const b of this.band) {
      b.avatar.update(dt, beat);
      b.avatar.root.position.y = groundAt(b.avatar.root.position.x, b.avatar.root.position.z);
    }
    this.updatePairs(dt);
    this.updateFormation(beat);
    for (const v of this.viewers.map.values()) {
      const av = v.avatar;
      av.update(dt, beat);
      av.root.position.y = groundAt(av.root.position.x, av.root.position.z);
    }
    this.tickTimer += dt;
    if (this.tickTimer >= 1) {
      this.tickTimer = 0;
      this.tick();
    }
  }

  /** Halay / horon: pistte dans edenleri sıraya diz. */
  updateFormation(beat) {
    const mode = danceMode.value;
    const group = GROUP_MODES.has(mode);
    const dancers = [];
    for (const v of this.viewers.map.values()) {
      const av = v.avatar;
      if (group && v.zone === 'dans' && av.state === 'dance') dancers.push(v);
      else if (av.formation) av.formation = null;
    }
    if (!group) return;
    dancers.sort((a, b) => a.zoneSince - b.zoneSince);
    const targets = formationTargets(mode, dancers.length, this.time, beat.phase);
    dancers.forEach((v, i) => { v.avatar.formation = { ...targets[i], leader: i === 0 }; });
  }

  // ---------- Kayıt: sayfa yenilenince mekan aynen geri gelsin ----------
  snapshot() {
    const now = performance.now();
    const spotIndex = (v) => {
      if (!v.spot) return -1;
      const list = v.zone === 'dans' ? this.layout.danceSpots : this.layout.seats[v.zone] || [];
      return list.indexOf(v.spot);
    };
    return {
      savedAt: Date.now(),
      likeTotal: this.likeTotal,
      likeGoal: this.likeGoal,
      likeBase: this.likeBase,
      scores: [...this.scores.map.entries()],
      genders: [...this.genders.entries()],
      viewers: this.viewers.all()
        .filter((v) => v.zone && v.zone !== 'leaving')
        .map((v) => ({
          id: v.id, name: v.name, zone: v.zone === 'sahne' ? 'normal' : v.zone, spot: v.zone === 'sahne' ? -1 : spotIndex(v),
          idleMs: now - v.lastActive, sinceMs: now - v.zoneSince,
          comments: v.comments, likes: v.likes, coins: v.coins, kons: v.kons || 0,
        })),
    };
  }

  restore(s) {
    if (!s || this.viewers.size) return;
    const now = performance.now();
    const away = Math.max(0, Date.now() - (s.savedAt || Date.now()));
    this.likeTotal = s.likeTotal || 0;
    this.likeGoal = s.likeGoal || this.likeGoal;
    this.likeBase = s.likeBase || 0;
    this.hud.setLikes(this.likeTotal, this.likeGoal, this.likeBase);
    for (const [id, sc] of s.scores || []) this.scores.map.set(id, sc);
    for (const [id, g] of s.genders || []) this.genders.set(id, g);
    const leaveMs = (this.rules.idle?.leaveVenueSeconds ?? 900) * 1000;
    for (const sv of s.viewers || []) {
      if (sv.idleMs + away > leaveMs) continue;
      const v = this.viewers.add({ id: sv.id, name: sv.name });
      Object.assign(v, { comments: sv.comments, likes: sv.likes, coins: sv.coins });
      v.lastActive = now - sv.idleMs - away;
      v.zoneSince = now - sv.sinceMs - away;
      v.avatar = new Avatar(sv.name, this.genders.get(sv.id));
      v.kons = sv.kons || 0;
      if (v.kons) v.avatar.setKons(v.kons);
      this.scene.add(v.avatar.root);
      const list = sv.zone === 'dans' ? this.spotsOf('dans') : this.spotsOf(sv.zone);
      let spot = list[sv.spot];
      if (!spot || spot.occupant) spot = list.find((x) => !x.occupant);
      if (!spot) {
        spot = this.spotsOf('normal').find((x) => !x.occupant);
        if (!spot) { v.avatar.dispose(); this.viewers.remove(v.id); continue; }
      }
      spot.occupant = v;
      v.spot = spot;
      v.zone = spot.zone;
      v.avatar.setLabelClass(ZONE_LABEL[v.zone]);
      v.avatar.setPosition(spot.x, spot.z);
      if (v.zone === 'dans') v.avatar.dance();
      else v.avatar.sit(spot.facing, spot.seatY);
    }
    this.tick();
  }

  tick() {
    const now = performance.now();
    const idle = this.rules.idle || {};
    const danceMs = (idle.danceBackToTableSeconds ?? 120) * 1000;
    const leaveMs = (idle.leaveVenueSeconds ?? 900) * 1000;
    // sadece girip hiç yazmayan / beğenmeyen daha çabuk çıkar (TikTok çıkanı bildirmiyor)
    const lurkMs = (idle.lurkerLeaveSeconds ?? 180) * 1000;
    for (const v of this.viewers.all()) {
      if (v.zone === 'leaving') continue;
      const quiet = now - v.lastActive;
      const lurker = !v.comments && !v.likes && !v.kons;
      if (v.partner && (v.zone !== 'dans' || v.partner.zone !== 'dans')) this.unpair(v);
      if (quiet > leaveMs || (lurker && quiet > lurkMs)) this.leave(v);
      else if (v.zone === 'dans' && quiet > danceMs) this.sendTo(v, 'normal');
    }
    // mekandaki kişi TikTok'taki izleyiciden fazlaysa en uzun süredir sessiz olanlar çıkar
    if (this.viewerCount != null) {
      const active = this.viewers.all().filter((v) => v.zone !== 'leaving');
      const extra = active.length - this.viewerCount;
      if (extra > 0) {
        active
          .filter((v) => v !== this.singer && now - v.lastActive > 60000)
          .sort((a, b) => a.lastActive - b.lastActive)
          .slice(0, Math.min(extra, 3))
          .forEach((v) => this.leave(v));
      }
    }
    this.updateStage();
    this.hud.setLeaders(this.scores.top(3, this.freeMode), this.freeMode);
    this.hud.setCount(this.viewers.all().filter((v) => v.zone !== 'leaving').length);
  }

  reset() {
    for (const v of this.viewers.all()) {
      this.release(v);
      v.avatar.dispose();
    }
    this.viewers.map.clear();
    this.scores.clear();
    this.genders.clear();
    this.singer = null;
    this.stageQueue = [];
    this.likeTotal = 0;
    this.likeGoal = this.rules.likes?.goal ?? 300;
    this.likeBase = 0;
    this.hud.setLikes(0, this.likeGoal, 0);
    this.hud.setLeaders([], this.freeMode);
  }
}

Lisans bilgisi projenin LICENSE dosyasında.