const POWERUP_TYPES = {
    cafe: {
        nombre: 'Café',
        color: '#7a4a20',
        accent: '#d8b890',
        effect: 'restorePaciencia',
        valor: 60,
        flash: '+60 paciencia ☕'
    },
    auriculares: {
        nombre: 'Auriculares',
        color: '#1a1a1a',
        accent: '#ddaa44',
        effect: 'reduceDetection',
        duracionMs: 18000,
        valor: 0.4,
        flash: 'Auriculares 18s 🎧'
    }
};

const powerupsCtx = {
    items: [],
    container: null,
    activeBuffs: {}
};

function _materialPowerup(hex) {
    return new THREE.MeshLambertMaterial({ color: new THREE.Color(hex) });
}

function _createPowerupMesh(type) {
    const t = POWERUP_TYPES[type];
    const group = new THREE.Group();

    const cube = new THREE.Mesh(
        new THREE.BoxGeometry(0.6, 0.6, 0.6),
        _materialPowerup(t.color)
    );
    group.add(cube);

    if (t.accent) {
        const cap = new THREE.Mesh(
            new THREE.BoxGeometry(0.7, 0.18, 0.7),
            _materialPowerup(t.accent)
        );
        cap.position.y = 0.06;
        group.add(cap);
    }

    const halo = new THREE.Mesh(
        new THREE.RingGeometry(0.7, 0.95, 16),
        new THREE.MeshBasicMaterial({ color: t.accent || t.color, transparent: true, opacity: 0.5, side: THREE.DoubleSide })
    );
    halo.rotation.x = -Math.PI / 2;
    halo.position.y = -0.5;
    group.add(halo);

    return group;
}

function spawnPowerups(nivel) {
    clearPowerups();
    powerupsCtx.activeBuffs = {};
    const container = new THREE.Group();
    sceneCtx.scene.add(container);
    powerupsCtx.container = container;

    for (const c of nivel.path) {
        if (c.type !== 'callejon' || !c.powerup) continue;
        const r = c.rect;
        const cx = (r.minX + r.maxX) / 2;
        const cz = (r.minZ + r.maxZ) / 2;
        const halfX = (r.maxX - r.minX) / 2 - 0.6;
        const halfZ = (r.maxZ - r.minZ) / 2 - 0.6;
        const placeX = cx + c.dir[0] * halfX * 0.7;
        const placeZ = cz + c.dir[1] * halfZ * 0.7;

        const mesh = _createPowerupMesh(c.powerup);
        mesh.position.set(placeX, 0.8, placeZ);
        container.add(mesh);

        powerupsCtx.items.push({
            mesh: mesh,
            type: c.powerup,
            pos: { x: placeX, y: 0.8, z: placeZ },
            picked: false,
            spawnTime: performance.now()
        });
    }
}

function updatePowerups(dt) {
    if (!powerupsCtx.container) return;
    const player = getPlayerPos();
    const t = performance.now();

    for (const item of powerupsCtx.items) {
        if (item.picked) continue;
        item.mesh.rotation.y = (t - item.spawnTime) / 700;
        item.mesh.position.y = 0.8 + Math.sin((t - item.spawnTime) / 400) * 0.12;

        const dx = player.x - item.pos.x;
        const dz = player.z - item.pos.z;
        if (dx * dx + dz * dz < 1.0) {
            _pickup(item);
        }
    }

    for (const k in powerupsCtx.activeBuffs) {
        if (t > powerupsCtx.activeBuffs[k]) {
            delete powerupsCtx.activeBuffs[k];
        }
    }
}

function _pickup(item) {
    item.picked = true;
    if (item.mesh.parent) item.mesh.parent.remove(item.mesh);
    item.mesh.traverse((obj) => {
        if (obj.geometry) obj.geometry.dispose();
        if (obj.material) {
            if (Array.isArray(obj.material)) obj.material.forEach((m) => m.dispose());
            else obj.material.dispose();
        }
    });

    const type = POWERUP_TYPES[item.type];
    if (type.effect === 'restorePaciencia') {
        if (typeof recuperarPaciencia === 'function') recuperarPaciencia(type.valor);
        else gameState.paciencia = Math.min(PACIENCIA_INICIAL, gameState.paciencia + type.valor);
    } else if (type.effect === 'reduceDetection') {
        powerupsCtx.activeBuffs.auriculares = performance.now() + type.duracionMs;
    }
    if (typeof playSfx === 'function') playSfx('powerup');
    flashPowerupMessage(type.flash);
}

function getDetectionRangeMultiplier() {
    if (powerupsCtx.activeBuffs.auriculares) return POWERUP_TYPES.auriculares.valor;
    return 1.0;
}

function getActiveBuffs() {
    const t = performance.now();
    const out = [];
    for (const k in powerupsCtx.activeBuffs) {
        const remaining = (powerupsCtx.activeBuffs[k] - t) / 1000;
        if (remaining > 0) out.push({ id: k, type: POWERUP_TYPES[k], remaining: remaining });
    }
    return out;
}

function clearPowerups() {
    if (powerupsCtx.container) {
        sceneCtx.scene.remove(powerupsCtx.container);
        powerupsCtx.container.traverse((obj) => {
            if (obj.geometry) obj.geometry.dispose();
            if (obj.material) {
                if (Array.isArray(obj.material)) obj.material.forEach((m) => m.dispose());
                else obj.material.dispose();
            }
        });
    }
    powerupsCtx.container = null;
    powerupsCtx.items = [];
}

function flashPowerupMessage(text) {
    let el = document.getElementById('powerup-flash');
    if (!el) {
        el = document.createElement('div');
        el.id = 'powerup-flash';
        document.body.appendChild(el);
    }
    el.textContent = text;
    el.classList.remove('show');
    void el.offsetWidth;
    el.classList.add('show');
}
