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
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
import * as THREE from "three";
import {
  UPGRADE_MAX_LEVEL,
  UPGRADE_START_COST,
  UPGRADE_COST_SCALE,
  UPGRADE_RANGE_SCALE,
  UPGRADE_RATE_SCALE,
  UPGRADE_DAMAGE_SCALE,
  SELL_REFUND_RATE,
} from "../../config/gameConfig.js";
import { KINDS } from "./kinds/index.js";

export class Tower {
  constructor(pos, baseConfig, scene) {
    this.position = pos.clone();
    this.fireCooldown = 0;
    this.scene = scene;

    this.type = baseConfig.type || "basic";
    this.projectileEffect = baseConfig.projectileEffect || null;

    this.slowMultByLevel = baseConfig.slowMultByLevel || [0.75, 0.7, 0.65];
    this.slowDuration = baseConfig.slowDuration || 1.5;

    this.isElectric = this.type === "electric";
    if (this.isElectric) {
      this.maxTargets = baseConfig.maxTargets ?? 4;
      this.damagePerSecond = baseConfig.damagePerSecond ?? 1;
      this.visualRefreshRate = baseConfig.visualRefreshRate ?? 60;
      this.visualRefreshInterval = 1 / Math.max(1, this.visualRefreshRate);
      this.arcFadeDuration = baseConfig.arcFadeDuration ?? 0.2;
      this.arcDurationMs = Math.max(
        1,
        baseConfig.arcDurationMs ?? this.arcFadeDuration * 1000
      );

      this.arcStyle = {
        color: baseConfig.arc?.color ?? 0x9ad6ff,
        coreColor: baseConfig.arc?.coreColor ?? 0xe6fbff,
        thickness: baseConfig.arc?.thickness ?? 2,
        jitter: baseConfig.arc?.jitter ?? 0.25,
        segments: baseConfig.arc?.segments ?? 10,
      };

      this.targetPriority =
        baseConfig.targetPriorityMode ||
        baseConfig.targetPriority ||
        "closestToExit";
    }

    this.level = 1;
    this.baseRange = baseConfig.range;
    this.baseRate = baseConfig.fireRate;
    this.baseDamage = baseConfig.damage;
    this.range = this.baseRange;
    this.rate = this.baseRate;
    this.damage = this.baseDamage;

    if (this.type === "slow") {
      const idx = Math.max(
        0,
        Math.min(this.slowMultByLevel.length - 1, this.level - 1)
      );
      const effect = this.projectileEffect || {};
      this.projectileEffect = {
        ...effect,
        type: "slow",
        mult: this.slowMultByLevel[idx],
        duration: this.slowDuration,
      };
    }
    this.nextUpgradeCost = UPGRADE_START_COST;
    this.totalSpent = baseConfig.cost;

    this.isSniper = this.type === "sniper";
    this.aimTime = baseConfig.aimTime ?? 0;
    this.sniperProjectileSpeed = baseConfig.projectileSpeed ?? null;
    this.cancelThreshold = baseConfig.cancelThreshold ?? this.range;
    this.pierceChance = baseConfig.pierceChance ?? 0;
    this.targetPriority = baseConfig.targetPriority || (this.isSniper ? "closestToExit" : "nearest");
    this.aiming = false;
    this.aimingTimer = 0;
    this.aimedTarget = null;
    this.laserLine = null;

    const baseGeo = new THREE.CylinderGeometry(0.9, 1.2, 1, 12);
    const baseMat = new THREE.MeshStandardMaterial({
      color:
        this.type === "slow" ? 0xff69b4 : this.isSniper ? 0x6d6f73 : 0x3a97ff,
      metalness: this.isSniper ? 0.5 : 0.2,
      roughness: this.isSniper ? 0.35 : 0.6,
    });
    const base = new THREE.Mesh(baseGeo, baseMat);
    base.castShadow = true;
    base.receiveShadow = true;
    base.position.copy(this.position);

    this.mesh = base;
    this.baseMesh = base;

    this.kind = KINDS[this.type] || KINDS.basic;
    this.kind.buildHead(this, scene);

    const ringGeo = new THREE.RingGeometry(this.range - 0.05, this.range, 48);
    const ringMat = new THREE.MeshBasicMaterial({
      color:
        this.type === "slow" ? 0xff69b4 : this.isSniper ? 0x00ffff : 0x3a97ff,
      transparent: true,
      opacity: this.isSniper ? 0.32 : 0.2,
      side: THREE.DoubleSide,
      depthWrite: false,
      depthTest: true,
    });
    const ring = new THREE.Mesh(ringGeo, ringMat);
    ring.rotation.x = -Math.PI / 2;
    ring.position.y = 0.03;
    base.add(ring);
    ring.visible = true;

    const outlineGeo = new THREE.TorusGeometry(1.05, 0.04, 8, 32);
    const outlineMat = new THREE.MeshBasicMaterial({
      color: 0xffff66,
      transparent: true,
      opacity: 0.85,
      depthWrite: false,
    });
    const outline = new THREE.Mesh(outlineGeo, outlineMat);
    outline.rotation.x = Math.PI / 2;
    outline.position.y = 0.52;
    outline.visible = false;
    outline.name = "tower_hover_outline";
    base.add(outline);

    this.ring = ring;
    this.hoverOutline = outline;
    this.levelRing = null;
    this.levelRings = [];

    if (this.isElectric) {
      this.applyVisualLevel();
    }

    scene.add(base);
  }

  get canUpgrade() {
    return this.level < UPGRADE_MAX_LEVEL;
  }

  getSellValue() {
    return Math.floor(this.totalSpent * SELL_REFUND_RATE);
  }

  upgrade() {
    if (!this.canUpgrade) return false;

    this.level += 1;
    this.range *= UPGRADE_RANGE_SCALE;
    this.rate *= UPGRADE_RATE_SCALE;
    this.damage *= UPGRADE_DAMAGE_SCALE;

    if (this.type === "slow") {
      const idx = Math.max(
        0,
        Math.min(this.slowMultByLevel.length - 1, this.level - 1)
      );
      const effect = this.projectileEffect || {};
      this.projectileEffect = {
        ...effect,
        type: "slow",
        mult: this.slowMultByLevel[idx],
        duration: this.slowDuration,
      };
    }

    if (this.isSniper) {
      const minAimTime = (this.aimTime ?? 0) * 0.4;
      this.aimTime = Math.max(minAimTime, (this.aimTime ?? 0) * 0.9);
      this.pierceChance = Math.min(0.15, (this.pierceChance ?? 0) + 0.03);
    }

    const newGeo = new THREE.RingGeometry(this.range - 0.05, this.range, 48);
    this.ring.geometry.dispose();
    this.ring.geometry = newGeo;

    this.totalSpent += this.nextUpgradeCost;
    this.nextUpgradeCost = Math.round(
      this.nextUpgradeCost * UPGRADE_COST_SCALE
    );

    this.applyVisualLevel();

    return true;
  }

  applyVisualLevel() {
    // Let the kind update its visuals first (head position, colors, base ring)
    this.kind.applyVisualLevel(this);

    // Clean up any legacy/orphan base rings left from earlier versions
    this._cleanupOrphanLevelRings();

    // Then ensure a consistent number of visible rings across all towers:
    // Level 1 => 0 rings; Level 2 => 1 ring; Level 3 => 2 rings, etc.
    // Most kinds add a single base ring for level >= 2. We add additional
    // rings above that so the total equals (level - 1).
    this._updateAdditionalLevelRings();
  }

  tryFire(dt, enemies, projectiles, projectileSpeed) {
    return this.kind.tryFire(this, dt, enemies, projectiles, projectileSpeed);
  }

  updateElectricArcs(now) {
    if (this.kind.updateElectricArcs) {
      this.kind.updateElectricArcs(this, now);
    }
  }

  playShootSound() {
    if (
      typeof window !== "undefined" &&
      window.UIManager &&
      window.UIManager.playTowerSound
    ) {
      try {
        window.UIManager.playTowerSound(this);
      } catch {}
    }
  }

  playAimingTone() {
    if (
      typeof window !== "undefined" &&
      window.UIManager &&
      window.UIManager.playAimingTone
    ) {
      try {
        window.UIManager.playAimingTone(this);
      } catch {}
    }
  }
  
  stopAimingTone() {
    if (
      typeof window !== "undefined" &&
      window.UIManager &&
      window.UIManager.stopAimingTone
    ) {
      try {
        window.UIManager.stopAimingTone(this);
      } catch {}
    }
  }

  playFireCrack() {
    if (
      typeof window !== "undefined" &&
      window.UIManager &&
      window.UIManager.playFireCrack
    ) {
      try {
        window.UIManager.playFireCrack(this);
      } catch {}
    }
  }

  setSelected(selected) {
    this.selected = !!selected;
    if (this.hoverOutline) {
      this.hoverOutline.visible = this.selected || !!this.hovered;
      this.hoverOutline.material.opacity = this.selected ? 0.95 : 0.85;
    }
  }

  setHovered(hovered) {
    this.hovered = !!hovered;
    if (this.hoverOutline) {
      this.hoverOutline.visible = this.selected || this.hovered;
    }
  }

  destroy() {
    if (this.kind.onDestroy) {
      this.kind.onDestroy(this);
    }

    if (this.levelRing) {
      this.scene.remove(this.levelRing);
      this.levelRing.geometry.dispose();
      if (this.levelRing.material?.dispose) this.levelRing.material.dispose();
      this.levelRing = null;
    }
    if (this.levelRings && this.levelRings.length) {
      for (const ring of this.levelRings) {
        this.scene.remove(ring);
        ring.geometry?.dispose?.();
        ring.material?.dispose?.();
      }
      this.levelRings.length = 0;
    }
    this.scene.remove(this.mesh);
  }

  _updateAdditionalLevelRings() {
    // Clean up any previously created extra rings
    if (this.levelRings && this.levelRings.length) {
      for (const ring of this.levelRings) {
        this.scene.remove(ring);
        ring.geometry?.dispose?.();
        ring.material?.dispose?.();
      }
      this.levelRings.length = 0;
    }

    // How many rings should be visible in total
    const totalRings = Math.max(0, (this.level || 1) - 1);
    if (totalRings <= 1) {
      // Kind likely already created the first ring if level >= 2; nothing else to do
      return;
    }

    // Additional rings we should add above the kind's base ring
    const extraRings = totalRings - 1;

    // Placement parameters
    const baseY = (this.headTopY ?? 0.8) + 0.02; // matches kind base ring offset
    const spacing = 0.1; // increased vertical spacing between rings

    // Choose a color consistent with the tower type
    let color = 0x3aa6ff; // default blue
    if (this.type === "slow") color = 0xff8fc2;
    else if (this.type === "sniper") color = 0x00ffff;
    // electric uses default blue

    for (let i = 0; i < extraRings; i++) {
      const geom = new THREE.TorusGeometry(0.45, 0.035, 8, 24);
      const mat = new THREE.MeshStandardMaterial({
        color,
        emissive: 0xe01a6b,
        emissiveIntensity: 0.55,
        metalness: 0.3,
        roughness: 0.45,
      });
      const ring = new THREE.Mesh(geom, mat);
      ring.castShadow = false;
      ring.receiveShadow = false;
      ring.rotation.x = Math.PI / 2;
      ring.name = "tower_level_ring_extra";

      // Stack above the base ring with clear vertical separation
      const y = baseY + (i + 1) * spacing;
      ring.position.set(this.mesh.position.x, y, this.mesh.position.z);

      this.scene.add(ring);
      this.levelRings.push(ring);
    }
  }

  _cleanupOrphanLevelRings() {
    const scene = this.scene;
    if (!scene || !scene.children) return;

    const px = this.mesh?.position?.x ?? this.position?.x ?? 0;
    const pz = this.mesh?.position?.z ?? this.position?.z ?? 0;
    const threshold = 0.1; // only remove rings very near this tower

    // Collect candidates first to avoid mutating while iterating
    const toRemove = [];
    for (const obj of scene.children) {
      if (!obj || obj === this.levelRing) continue;
      if (obj.name !== 'tower_level_ring') continue;
      const ox = obj.position?.x ?? 0;
      const oz = obj.position?.z ?? 0;
      const dx = ox - px;
      const dz = oz - pz;
      if (dx * dx + dz * dz <= threshold * threshold) {
        toRemove.push(obj);
      }
    }
    for (const obj of toRemove) {
      scene.remove(obj);
      obj.geometry?.dispose?.();
      obj.material?.dispose?.();
    }
  }
}