// --- TRASH & ITEM DATA ---
const trashData = [
  { name: "Daun Kering", type: "organik", icon: "🍂" },
  { name: "Sisa Apel", type: "organik", icon: "🍎" },
  { name: "Sisa Nasi", type: "organik", icon: "🍚" },
  { name: "Botol Plastik", type: "anorganik", icon: "🍾" },
  { name: "Gelas Plastik", type: "anorganik", icon: "🥤" },
  { name: "Kardus", type: "kertas", icon: "📦" },
  { name: "Koran Bekas", type: "kertas", icon: "📰" },
  { name: "Baterai Bekas", type: "b3", icon: "🔋" },
  { name: "Obat Exp", type: "b3", icon: "💊" }
];

const powerUpData = [
  { name: "JAM PASIR", type: "hourglass", icon: "⏳" },
  { name: "MAGNET", type: "magnet", icon: "🧲" },
  { name: "NYAWA EKSTRA", type: "heart", icon: "💖" }
];

const bossAmmoData = [
  { name: "Air Bersih", type: "water", icon: "💧" },
  { name: "Bibit Pohon", type: "seed", icon: "🌱" }
];

const quizQuestions = [
  { q: "Plastik bisa hancur dalam 1 tahun?", a: false },
  { q: "Kertas dibuat dari pohon hutan?", a: true },
  { q: "Baterai boleh dibuang ke tanah?", a: false },
  { q: "Sisa nasi bisa diolah jadi kompos?", a: true },
  { q: "Mendaur ulang menghemat energi?", a: true }
];

const triviaData = [
  "Tahukah kamu? Botol plastik butuh waktu 450 tahun untuk hancur di alam liar!",
  "Tahukah kamu? Mendaur ulang 1 ton kertas dapat menyelamatkan 17 pohon dewasa.",
  "Tahukah kamu? Baterai bekas mengandung logam berat beracun, buanglah di tempat khusus!",
  "Tahukah kamu? Sampah organik seperti sisa apel bisa dijadikan kompos untuk menyuburkan tanaman.",
  "Tahukah kamu? Mematikan lampu saat tidak digunakan dapat mengurangi polusi udara dari pembangkit listrik."
];

// --- AUDIO SETUP ---
let audioCtx = null;
function playTone(type) {
  if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  if (audioCtx.state === 'suspended') audioCtx.resume();
  const osc = audioCtx.createOscillator();
  const gain = audioCtx.createGain();
  const setupNode = (f1, f2, ft, tOsc, gs, gt) => {
    osc.frequency.setValueAtTime(f1, audioCtx.currentTime);
    osc.frequency.exponentialRampToValueAtTime(f2, audioCtx.currentTime + ft);
    osc.type = tOsc;
    gain.gain.setValueAtTime(gs, audioCtx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + gt);
    osc.connect(gain);
    gain.connect(audioCtx.destination);
    osc.start(); osc.stop(audioCtx.currentTime + gt);
  };
  if (type === 'good') setupNode(600, 1200, 0.1, 'sine', 0.1, 0.2);
  else if (type === 'bad') setupNode(250, 100, 0.3, 'sawtooth', 0.1, 0.3);
  else if (type === 'bomb') setupNode(100, 40, 0.5, 'square', 0.2, 0.5);
  else if (type === 'star') setupNode(800, 1600, 0.2, 'triangle', 0.1, 0.4);
  else if (type === 'powerup') setupNode(400, 800, 0.3, 'sine', 0.15, 0.5);
  else if (type === 'bossHit') setupNode(150, 50, 0.2, 'square', 0.3, 0.3);
  else if (type === 'victory') setupNode(523.25, 1046.50, 0.6, 'sine', 0.2, 1.0);
}

// --- APP CONTROLLER (SPA) ---
const app = {
  currentMode: null,
  activeItems: [],
  bossAttacks: [],
  loopId: null,
  avatar: '👦',
  isPaused: false,
  currentQuizAnswer: false,

  // States per mode
  santai: { score: 0, maxItems: 3 },
  ekstrem: { score: 0, hearts: 3, combo: 0, speed: 100, spawnRate: 2000, lastSpawn: 0, isFrozen: false },
  boss: { hits: 0, hearts: 3, bossHp: 100, speed: 200, spawnRate: 1500, lastSpawn: 0, bossX: 50, bossDir: 1, attackRate: 2000, lastAttack: 0 },

  init() {
    this.updateLeaderboardUI();
    this.showScreen('menuScreen');
  },

  setAvatar(emoji) {
    this.avatar = emoji;
    document.querySelectorAll('.avatar-btn').forEach(btn => btn.classList.remove('active'));
    event.currentTarget.classList.add('active');
  },

  showScreen(screenId) {
    // Stop any loops
    if (this.loopId) cancelAnimationFrame(this.loopId);
    this.clearItems();

    // Hide all
    document.querySelectorAll('.screen').forEach(s => s.classList.remove('active'));
    document.getElementById('resultOverlay').classList.add('hidden-global');
    document.getElementById('freezeOverlay').classList.add('hidden-global');
    document.getElementById('ekstremScreen').classList.remove('wind-shake', 'night-mode');
    document.getElementById('weatherOverlay').className = 'weather-layer';

    // Show requested
    document.getElementById(screenId).classList.add('active');
  },

  startGame(mode) {
    if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    this.currentMode = mode;
    this.showScreen(`${mode}Screen`);

    if (mode === 'santai') {
      this.santai.score = 0;
      document.getElementById('santaiScore').textContent = 0;
      this.santaiLoop();
    } else if (mode === 'ekstrem') {
      this.ekstrem.score = 0; this.ekstrem.hearts = 3; this.ekstrem.combo = 0;
      this.ekstrem.speed = 120; this.ekstrem.spawnRate = 2000; this.ekstrem.isFrozen = false;
      this.updateEkstremHUD();
      this.ekstrem.lastSpawn = performance.now();
      this.loopId = requestAnimationFrame(this.ekstremLoop.bind(this));
    } else if (mode === 'boss') {
      this.boss.hits = 0; this.boss.hearts = 3; this.boss.bossHp = 100;
      this.boss.speed = 250; this.boss.spawnRate = 1200;
      this.boss.bossX = 50; this.boss.bossDir = 1;
      document.getElementById('bossHpBar').style.width = '100%';
      document.getElementById('theBoss').classList.remove('hurt');
      this.updateBossHUD();
      this.bossAttacks.forEach(a => a.el.remove()); this.bossAttacks = [];
      this.boss.lastSpawn = performance.now();
      this.boss.lastAttack = performance.now() + 1000;
      this.loopId = requestAnimationFrame(this.bossLoop.bind(this));
    }
  },

  clearItems() {
    this.activeItems.forEach(item => { if (item.el) item.el.remove(); });
    this.activeItems = [];
    if (this.bossAttacks) { this.bossAttacks.forEach(a => { if (a.el) a.el.remove(); }); this.bossAttacks = []; }
  },

  endGame(won, score) {
    cancelAnimationFrame(this.loopId);
    playTone(won ? 'victory' : 'bad');
    document.getElementById('resultTitle').textContent = won ? "KEMENANGAN!" : "GAME OVER";
    document.getElementById('resultMessage').textContent = won ? "Luar biasa! Alam kembali lestari." : "Kamu kehabisan nyawa!";
    document.getElementById('resultScore').textContent = score;
    
    // Trivia
    const trivia = triviaData[Math.floor(Math.random() * triviaData.length)];
    document.getElementById('resultTrivia').innerHTML = `💡 ${trivia}`;
    
    // Stars
    let stars = 1;
    if (score >= 300) stars = 2;
    if (score >= 500) stars = 3;
    const starsHtml = Array(3).fill(0).map((_, i) => `<div class="star-icon ${i < stars ? 'active' : ''}" style="animation-delay: ${i*0.2}s">⭐</div>`).join('');
    document.getElementById('resultStars').innerHTML = starsHtml;
    
    // Leaderboard save
    if (won || this.currentMode === 'ekstrem' || this.currentMode === 'santai') {
      let scores = JSON.parse(localStorage.getItem('ecoScores') || '[]');
      scores.push(score);
      scores.sort((a,b) => b - a);
      scores = scores.slice(0, 3);
      localStorage.setItem('ecoScores', JSON.stringify(scores));
      this.updateLeaderboardUI();
    }
    
    document.getElementById('restartBtn').onclick = () => this.startGame(this.currentMode);
    document.getElementById('resultOverlay').classList.remove('hidden-global');
  },

  updateLeaderboardUI() {
    const list = document.getElementById('leaderboardList');
    if (!list) return;
    const scores = JSON.parse(localStorage.getItem('ecoScores') || '[]');
    if (scores.length === 0) {
      list.innerHTML = '<li>Belum ada rekor</li>';
    } else {
      list.innerHTML = scores.map(s => `<li>${s} Poin</li>`).join('');
    }
  },

  showFloatingText(text, x, y, color) {
    const ft = document.createElement('div');
    ft.className = 'floating-text'; ft.textContent = text;
    ft.style.left = x + 'px'; ft.style.top = y + 'px'; ft.style.color = color;
    document.body.appendChild(ft);
    setTimeout(() => ft.remove(), 1000);
  },

  // =====================================
  // SANTAI MODE LOGIC
  // =====================================
  santaiLoop() {
    if (this.currentMode !== 'santai') return;
    // Keep exact number of max items on screen
    if (this.activeItems.length < this.santai.maxItems) {
      const valid = trashData.filter(t => t.type === 'organik' || t.type === 'anorganik' || t.type === 'b3');
      const data = valid[Math.floor(Math.random() * valid.length)];

      const el = document.createElement('div');
      el.className = 'trash-item';
      el.innerHTML = `<span class="trash-icon">${data.icon}</span><small>${data.name}</small>`;

      // Random position in picnic area (using percentages)
      const xPercent = 10 + Math.random() * 80;
      const yPercent = 20 + Math.random() * 60;

      el.style.left = xPercent + '%'; el.style.top = yPercent + '%';
      document.getElementById('santaiItemsArea').appendChild(el);

      const item = { el, type: data.type, mode: 'santai' };
      this.activeItems.push(item);
      this.bindDrag(item);
    }
    // Check every second
    this.loopId = setTimeout(() => this.santaiLoop(), 1000);
  },

  // =====================================
  // EKSTREM MODE LOGIC
  // =====================================
  updateEkstremHUD() {
    document.getElementById('ekstremScore').textContent = this.ekstrem.score;
    document.getElementById('ekstremHearts').textContent = `${this.avatar} ` + '❤️'.repeat(this.ekstrem.hearts) + '🖤'.repeat(Math.max(0, 3 - this.ekstrem.hearts));
    document.getElementById('ekstremCombo').textContent = `[Items: ${this.activeItems.length}] ` + (this.ekstrem.combo >= 3 ? `🔥 Combo x${this.ekstrem.combo}!` : '');
    
    let title = "Pemula";
    if (this.ekstrem.score >= 500) title = "Master Daur Ulang";
    else if (this.ekstrem.score >= 200) title = "Pengumpul Sigap";
    document.getElementById('ekstremIndicator').textContent = title;
  },

  ekstremLoop(now) {
    if (this.currentMode !== 'ekstrem') return;
    if (this.isPaused) {
      this.lastFrame = now;
      this.loopId = requestAnimationFrame(this.ekstremLoop.bind(this));
      return;
    }
    const dt = (now - (this.lastFrame || now)) / 1000;
    this.lastFrame = now;

    // Dynamic difficulty
    if (!this.ekstrem.isFrozen) {
      this.ekstrem.speed += 1.5 * dt;
      this.ekstrem.spawnRate = Math.max(800, 2000 - this.ekstrem.score * 3);
    }

    // Weather & Night Mode
    const screen = document.getElementById('ekstremScreen');
    const weather = document.getElementById('weatherOverlay');
    if (this.ekstrem.score > 200 && !weather.classList.contains('rain')) weather.classList.add('rain');
    if (this.ekstrem.score > 300 && !screen.classList.contains('night-mode')) screen.classList.add('night-mode');
    if (this.ekstrem.score > 400 && !screen.classList.contains('wind-shake')) screen.classList.add('wind-shake');

    if (now - this.ekstrem.lastSpawn > this.ekstrem.spawnRate) {
      this.spawnEkstremItem();
      this.ekstrem.lastSpawn = now;
    }

    const ww = window.innerWidth;
    const speed = this.ekstrem.isFrozen ? 20 : this.ekstrem.speed;

    for (let i = this.activeItems.length - 1; i >= 0; i--) {
      let it = this.activeItems[i];
      if (!it.isDragging) {
        it.x += speed * dt;
        it.el.style.left = it.x + 'px';
        if (it.x > ww + 50) {
          if (it.type === 'bomb') {
            this.ekstrem.score += 5; this.showFloatingText('+5', ww - 50, it.el.getBoundingClientRect().top, 'var(--green)'); this.updateEkstremHUD();
          } else if (!['star', 'hourglass', 'magnet', 'heart', 'quiz'].includes(it.type)) {
            this.loseEkstremHeart(ww - 50, it.el.getBoundingClientRect().top);
          }
          it.el.remove();
          this.activeItems.splice(i, 1);
        }
      }
    }

    if (this.ekstrem.hearts <= 0) this.endGame(false, this.ekstrem.score);
    else this.loopId = requestAnimationFrame(this.ekstremLoop.bind(this));
  },

  spawnEkstremItem() {
    let data;
    const r = Math.random();
    if (r < 0.05) data = { type: 'quiz', name: "KUIS", icon: "❓" };
    else if (r < 0.15) data = { name: "BOM", type: "bomb", icon: "💣" };
    else if (r > 0.9) data = powerUpData[Math.floor(Math.random() * powerUpData.length)];
    else if (r > 0.85) data = { name: "BINTANG", type: "star", icon: "⭐" };
    else data = trashData[Math.floor(Math.random() * trashData.length)];

    const el = document.createElement('div'); el.className = 'trash-item';
    if (data.type === 'bomb') el.classList.add('bomb');
    if (['hourglass', 'magnet', 'heart'].includes(data.type)) el.classList.add('powerup');
    if (data.type === 'quiz') el.classList.add('quiz');
    
    el.innerHTML = `<span class="trash-icon">${data.icon}</span><small>${data.name}</small>`;
    el.style.left = '50px';
    document.getElementById('ekstremItemsArea').appendChild(el);
    
    const item = { el, type: data.type, x: 50, isDragging: false, mode: 'ekstrem' };
    
    if (data.type === 'quiz') {
      el.addEventListener('pointerdown', (e) => {
        e.stopPropagation();
        this.openQuiz(item);
      });
    } else {
      this.bindDrag(item);
    }
    
    this.activeItems.push(item);
    this.updateEkstremHUD();
  },

  loseEkstremHeart(x, y) {
    playTone('bad'); this.ekstrem.combo = 0; this.ekstrem.hearts--;
    this.updateEkstremHUD();
    document.getElementById('ekstremScreen').classList.add('shake');
    setTimeout(() => document.getElementById('ekstremScreen').classList.remove('shake'), 400);
    if (x && y) this.showFloatingText('❌', x, y, 'var(--danger)');
  },

  // =====================================
  // QUIZ LOGIC
  // =====================================
  openQuiz(item) {
    this.isPaused = true;
    playTone('powerup');
    item.el.remove(); this.activeItems = this.activeItems.filter(i => i !== item);
    
    const q = quizQuestions[Math.floor(Math.random() * quizQuestions.length)];
    this.currentQuizAnswer = q.a;
    document.getElementById('quizQuestion').textContent = q.q;
    document.getElementById('quizOverlay').classList.remove('hidden-global');
  },

  answerQuiz(isTrue) {
    document.getElementById('quizOverlay').classList.add('hidden-global');
    if (isTrue === this.currentQuizAnswer) {
      playTone('good'); this.ekstrem.score += 50; this.updateEkstremHUD();
      this.showFloatingText('+50 BENAR!', window.innerWidth/2, window.innerHeight/2, 'var(--green)');
    } else {
      playTone('bad');
      this.showFloatingText('SALAH!', window.innerWidth/2, window.innerHeight/2, 'var(--danger)');
    }
    this.isPaused = false;
  },

  // =====================================
  // BOSS MODE LOGIC
  // =====================================
  updateBossHUD() {
    document.getElementById('bossHits').textContent = this.boss.hits;
    document.getElementById('bossHearts').textContent = '❤️'.repeat(this.boss.hearts) + '🖤'.repeat(Math.max(0, 3 - this.boss.hearts));
  },

  bossLoop(now) {
    if (this.currentMode !== 'boss') return;
    const dt = (now - (this.lastFrame || now)) / 1000;
    this.lastFrame = now;

    // Move Boss Back and Forth
    const theBoss = document.getElementById('theBoss');
    this.boss.bossX += this.boss.bossDir * 20 * dt;
    if (this.boss.bossX > 80) this.boss.bossDir = -1;
    if (this.boss.bossX < 20) this.boss.bossDir = 1;
    theBoss.style.left = this.boss.bossX + '%';

    // Spawn Ammo
    if (now - this.boss.lastSpawn > this.boss.spawnRate) {
      const data = bossAmmoData[Math.floor(Math.random() * bossAmmoData.length)];
      const el = document.createElement('div'); el.className = 'trash-item';
      el.innerHTML = `<span class="trash-icon">${data.icon}</span><small>${data.name}</small>`;
      el.style.left = '-50px';
      document.getElementById('bossItemsArea').appendChild(el);

      const item = { el, type: data.type, x: -50, isDragging: false, mode: 'boss' };
      this.activeItems.push(item); this.bindDrag(item);
      this.boss.lastSpawn = now;
    }

    if (now - this.boss.lastAttack > this.boss.attackRate) {
      this.spawnBossAttack();
      this.boss.lastAttack = now;
      this.boss.attackRate = Math.max(800, 2000 - (100 - this.boss.bossHp)*10);
    }

    // Move Ammo right to left
    const ww = window.innerWidth;
    for (let i = this.activeItems.length - 1; i >= 0; i--) {
      let it = this.activeItems[i];
      if (!it.isDragging) {
        it.x += this.boss.speed * dt;
        it.el.style.left = (ww - it.x) + 'px'; // Move backwards!
        if (it.x > ww + 50) {
          it.el.remove();
          this.activeItems.splice(i, 1);
        }
      }
    }

    const wh = window.innerHeight;
    for (let i = this.bossAttacks.length - 1; i >= 0; i--) {
      let atk = this.bossAttacks[i];
      atk.y += 150 * dt; 
      atk.el.style.top = atk.y + 'px';
      if (atk.y > wh - 100) {
        playTone('bad'); this.boss.hearts--; this.updateBossHUD();
        this.showFloatingText('❌ Polusi!', atk.x, atk.y, 'var(--danger)');
        document.getElementById('bossScreen').classList.add('shake');
        setTimeout(() => document.getElementById('bossScreen').classList.remove('shake'), 400);
        atk.el.remove(); this.bossAttacks.splice(i, 1);
      }
    }

    if (this.boss.hearts <= 0) this.endGame(false, this.boss.hits);
    else if (this.boss.bossHp <= 0) this.endGame(true, this.boss.hits * 100);
    else this.loopId = requestAnimationFrame(this.bossLoop.bind(this));
  },

  spawnBossAttack() {
    const bossNode = document.getElementById('theBoss');
    bossNode.classList.add('attacking');
    setTimeout(() => bossNode.classList.remove('attacking'), 300);

    const isToxic = Math.random() < 0.3; // 30% chance for toxic barrel
    const el = document.createElement('div');
    el.className = isToxic ? 'pollution-cloud toxic-barrel' : 'pollution-cloud'; 
    el.textContent = isToxic ? '🛢️' : '☁️';
    
    const xPos = (this.boss.bossX / 100) * window.innerWidth;
    el.style.left = xPos + 'px'; el.style.top = '100px';
    
    document.getElementById('bossAttacksArea').appendChild(el);
    const atk = { el, y: 100, x: xPos, hp: isToxic ? 2 : 1 };
    
    el.addEventListener('pointerdown', (e) => {
      e.stopPropagation();
      atk.hp--;
      if (atk.hp > 0) {
        playTone('bad'); el.classList.add('hurt');
        setTimeout(() => el.classList.remove('hurt'), 200);
      } else {
        playTone('pop'); this.showFloatingText('💥', atk.x, atk.y, 'white');
        el.remove(); this.bossAttacks = this.bossAttacks.filter(a => a !== atk);
      }
    });
    
    this.bossAttacks.push(atk);
  },

  // =====================================
  // SHARED DRAG LOGIC
  // =====================================
  bindDrag(item) {
    const el = item.el;
    let ox = 0, oy = 0;

    const down = (e) => {
      if (item.type === 'bomb') {
        playTone('bomb'); this.showFloatingText('💥 BUM!', e.clientX, e.clientY, 'var(--danger)');
        this.loseEkstremHeart(); el.remove(); this.activeItems = this.activeItems.filter(i => i !== item);
        return;
      }
      e.preventDefault(); el.setPointerCapture(e.pointerId); item.isDragging = true;
      el.classList.add('dragging'); ox = el.offsetWidth / 2; oy = el.offsetHeight / 2;
      el.style.left = e.clientX + 'px'; el.style.top = e.clientY + 'px';
    };

    const move = (e) => {
      if (!item.isDragging) return;
      e.preventDefault(); el.style.left = e.clientX + 'px'; el.style.top = e.clientY + 'px';
      if (item.mode !== 'boss') {
        const bins = document.getElementById(item.mode + 'Screen').querySelectorAll('.trash-bin');
        bins.forEach(b => {
          const r = b.getBoundingClientRect();
          if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) b.classList.add('drag-over');
          else b.classList.remove('drag-over');
        });
      }
    };

    const up = (e) => {
      if (!item.isDragging) return;
      item.isDragging = false; el.classList.remove('dragging'); el.releasePointerCapture(e.pointerId);

      if (item.mode === 'santai') this.handleSantaiDrop(item, e.clientX, e.clientY);
      else if (item.mode === 'ekstrem') this.handleEkstremDrop(item, e.clientX, e.clientY);
      else if (item.mode === 'boss') this.handleBossDrop(item, e.clientX, e.clientY);
    };

    el.addEventListener('pointerdown', down); el.addEventListener('pointermove', move);
    el.addEventListener('pointerup', up); el.addEventListener('pointercancel', up);
  },

  handleSantaiDrop(item, cx, cy) {
    const bins = document.getElementById('santaiScreen').querySelectorAll('.trash-bin');
    bins.forEach(b => b.classList.remove('drag-over'));

    let droppedBin = Array.from(bins).find(b => {
      const r = b.getBoundingClientRect();
      return (cx >= r.left && cx <= r.right && cy >= r.top && cy <= r.bottom);
    });

    if (droppedBin) {
      if (droppedBin.dataset.type === item.type) {
        playTone('good'); this.santai.score += 10;
        document.getElementById('santaiScore').textContent = this.santai.score;
        this.showFloatingText('Benar! 🌿', cx, cy, 'var(--green)');
        droppedBin.style.transform = 'scale(1.2)'; setTimeout(() => droppedBin.style.transform = '', 150);
        item.el.remove(); this.activeItems = this.activeItems.filter(i => i !== item);
      } else {
        playTone('bad'); this.showFloatingText('Coba Lagi', cx, cy, 'var(--danger)');
        // Snap back to picnic
        item.el.style.top = ''; item.el.style.left = '';
        document.getElementById('santaiItemsArea').appendChild(item.el);
      }
    } else {
      item.el.style.top = ''; item.el.style.left = '';
      document.getElementById('santaiItemsArea').appendChild(item.el);
    }
  },

  handleEkstremDrop(item, cx, cy) {
    const bins = document.getElementById('ekstremScreen').querySelectorAll('.trash-bin');
    bins.forEach(b => b.classList.remove('drag-over'));

    if (['hourglass', 'magnet', 'heart'].includes(item.type)) {
      this.activatePowerUp(item.type, cx, cy);
      item.el.remove(); this.activeItems = this.activeItems.filter(i => i !== item); return;
    }

    let droppedBin = Array.from(bins).find(b => {
      const r = b.getBoundingClientRect();
      return (cx >= r.left && cx <= r.right && cy >= r.top && cy <= r.bottom);
    });

    if (droppedBin) {
      if (droppedBin.dataset.type === item.type || item.type === 'star') {
        playTone('good'); this.ekstrem.combo++;
        const pts = item.type === 'star' ? 50 : 10 + (this.ekstrem.combo > 2 ? 5 : 0);
        this.ekstrem.score += pts; this.updateEkstremHUD();
        this.showFloatingText(`+${pts}`, cx, cy, 'var(--green)');
        droppedBin.style.transform = 'scale(1.2)'; setTimeout(() => droppedBin.style.transform = '', 150);
      } else {
        this.loseEkstremHeart(cx, cy);
      }
      item.el.remove(); this.activeItems = this.activeItems.filter(i => i !== item);
    } else {
      item.el.style.top = ''; item.el.style.position = ''; item.el.style.left = item.x + 'px';
    }
  },

  activatePowerUp(type, cx, cy) {
    playTone('powerup'); this.showFloatingText('POWER UP!', cx, cy, 'var(--yellow)');
    if (type === 'hourglass') {
      this.ekstrem.isFrozen = true; document.getElementById('freezeOverlay').classList.remove('hidden-global');
      setTimeout(() => { this.ekstrem.isFrozen = false; document.getElementById('freezeOverlay').classList.add('hidden-global'); }, 5000);
    } else if (type === 'magnet') {
      for (let i = this.activeItems.length - 1; i >= 0; i--) {
        const it = this.activeItems[i];
        if (['organik', 'anorganik', 'kertas', 'b3'].includes(it.type)) {
          this.ekstrem.score += 10; this.showFloatingText('+10', it.x, it.el.getBoundingClientRect().top, 'var(--green)');
          it.el.remove(); this.activeItems.splice(i, 1);
        }
      }
      this.updateEkstremHUD();
    } else if (type === 'heart') {
      if (this.ekstrem.hearts < 5) { this.ekstrem.hearts++; this.showFloatingText('+1 ❤️', cx, cy - 30, 'var(--danger)'); this.updateEkstremHUD(); }
    }
  },

  handleBossDrop(item, cx, cy) {
    const bossNode = document.getElementById('theBoss');
    const r = bossNode.getBoundingClientRect();
    if (cx >= r.left && cx <= r.right && cy >= r.top && cy <= r.bottom) {
      playTone('bossHit'); this.boss.hits++; this.boss.bossHp -= 10;
      document.getElementById('bossHpBar').style.width = Math.max(0, this.boss.bossHp) + '%';
      this.showFloatingText('💥 -10', cx, cy, 'white');
      bossNode.classList.add('hurt'); setTimeout(() => bossNode.classList.remove('hurt'), 200);
      this.updateBossHUD();
      item.el.remove(); this.activeItems = this.activeItems.filter(i => i !== item);
    } else {
      item.el.style.top = ''; item.el.style.position = ''; item.el.style.left = (window.innerWidth - item.x) + 'px';
    }
  }
};

// Start SPA
window.onload = () => app.init();
