// Diccionario de Slots
const SlotNames = {
    0: "Arma Izq", 1: "Arma Der", 2: "Casco", 3: "Pecho", 
    4: "Pantalones", 5: "Guantes", 6: "Botas", 7: "Alas", 8: "Mascota"
};

function decodeItem(hex) {
    if (!hex || hex.toLowerCase() === 'ffffffffffffffffffff') return null;

    // Convertir hex a array de bytes (10 bytes por item)
    let bytes = [];
    for (let i = 0; i < hex.length; i += 2) {
        bytes.push(parseInt(hex.substr(i, 2), 16));
    }

    // LÓGICA DE MU ONLINE
    // Byte 1: Nivel, Luck, Skill, Option
    let byte1 = bytes[1];
    let level = (byte1 >> 3) & 15;
    let skill = (byte1 >> 7) & 1;
    let luck  = (byte1 >> 2) & 1;
    
    // Byte 7: Opciones Excelentes
    let excelentByte = bytes[7];
    let excelentCount = 0;
    for (let i = 0; i < 6; i++) {
        if ((excelentByte >> i) & 1) excelentCount++;
    }

    return {
        level: level,
        luck: luck,
        skill: skill,
        isExcelent: excelentCount > 0,
        exeCount: excelentCount
    };
}

function getDetailedEquipment(inventoryHex) {
    let html = '<div class="grid grid-cols-1 gap-1 mt-2">';
    let itemsFound = 0;

    // Analizamos los primeros 9 slots (Equipamiento principal)
    for (let slot = 0; slot < 9; slot++) {
        let itemHex = inventoryHex.substring(slot * 20, (slot * 20) + 20);
        let data = decodeItem(itemHex);

        if (data) {
            itemsFound++;
            let exeLabel = data.isExcelent ? `<span class="text-[7px] bg-green-500/20 text-green-400 px-1 rounded border border-green-500/30">EXE +${data.exeCount} Opts</span>` : '';
            let luckLabel = data.luck ? '<span class="text-blue-400"> +Luck</span>' : '';
            
            html += `
                <div class="flex flex-col bg-white/5 p-2 rounded-lg border border-white/5">
                    <div class="flex justify-between items-center mb-1">
                        <span class="text-[8px] text-gray-500 font-black uppercase tracking-widest">${SlotNames[slot]}</span>
                        ${exeLabel}
                    </div>
                    <div class="text-[10px] font-bold ${data.isExcelent ? 'text-green-400' : 'text-white'}">
                        Item +${data.level}${luckLabel}
                        ${data.skill ? ' <span class="text-gray-400">+Skill</span>' : ''}
                    </div>
                </div>`;
        }
    }

    html += '</div>';
    return itemsFound > 0 ? html : '<p class="text-[10px] text-gray-600 italic text-center py-4">Personaje sin equipo</p>';
}

function fetchMarketItems() {
    const grid = document.getElementById('market-grid');
    grid.innerHTML = '<div class="col-span-full text-center py-20 text-orange-500 font-black animate-pulse">EXTRAYENDO DATOS...</div>';
    
    fetch('api_get_market.php').then(r => r.json()).then(data => {
        grid.innerHTML = '';
        data.forEach(item => {
            const isMine = (item.seller === myAcc);
            const detailedGear = getDetailedEquipment(item.inventory);

            grid.innerHTML += `
                <div class="market-card p-6 rounded-[2.5rem] border border-white/10 bg-gradient-to-b from-white/5 to-transparent flex flex-col">
                    <div class="flex items-center gap-4 mb-6">
                        <div class="relative">
                            <img src="assets/classes/${item.icon}" class="w-14 h-14 rounded-2xl border-2 border-orange-500/50 object-cover shadow-lg shadow-orange-500/20">
                            <div class="absolute -bottom-2 -right-2 bg-orange-600 text-[8px] font-black px-2 py-1 rounded-md text-white border border-black">LVL ${item.level}</div>
                        </div>
                        <div>
                            <h4 class="text-white font-black uppercase text-base tracking-tighter">${item.name}</h4>
                            <p class="text-[10px] text-orange-500 font-bold uppercase tracking-widest">Resets: ${item.resets}</p>
                        </div>
                    </div>

                    <div class="flex-1 space-y-4">
                        <div class="bg-black/40 rounded-3xl p-4 border border-white/5">
                            <h5 class="text-[8px] text-gray-500 font-black uppercase mb-3 flex items-center gap-2">
                                <span class="w-1.5 h-1.5 rounded-full bg-orange-500 animate-pulse"></span> Inventario Equipado
                            </h5>
                            ${detailedGear}
                        </div>

                        <div class="grid grid-cols-4 gap-2">
                            <div class="text-center p-2 bg-white/5 rounded-xl border border-white/5">
                                <p class="text-[7px] text-gray-500 font-bold uppercase">STR</p>
                                <p class="text-[10px] text-white font-black">${item.str}</p>
                            </div>
                            <div class="text-center p-2 bg-white/5 rounded-xl border border-white/5">
                                <p class="text-[7px] text-gray-500 font-bold uppercase">AGI</p>
                                <p class="text-[10px] text-white font-black">${item.agi}</p>
                            </div>
                            <div class="text-center p-2 bg-white/5 rounded-xl border border-white/5">
                                <p class="text-[7px] text-gray-500 font-bold uppercase">VIT</p>
                                <p class="text-[10px] text-white font-black">${item.vit}</p>
                            </div>
                            <div class="text-center p-2 bg-white/5 rounded-xl border border-white/5">
                                <p class="text-[7px] text-gray-500 font-bold uppercase">ENE</p>
                                <p class="text-[10px] text-white font-black">${item.ene}</p>
                            </div>
                        </div>
                    </div>

                    <div class="mt-6 pt-6 border-t border-white/5 flex items-center justify-between">
                        <div>
                            <p class="text-[8px] text-gray-500 font-bold uppercase">Precio Total</p>
                            <span class="text-2xl font-black text-white tracking-tighter">${item.price.toLocaleString()}</span>
                        </div>
                        <span class="text-[10px] text-orange-500 font-black uppercase bg-orange-500/10 px-3 py-1 rounded-full border border-orange-500/20 italic">
                             <?php echo $coin_config['coin_name']; ?>
                        </span>
                    </div>

                    <div class="mt-4">
                        ${isMine 
                            ? '<button disabled class="w-full py-4 rounded-2xl bg-white/5 text-gray-600 text-[10px] font-black uppercase border border-white/10 opacity-50">Tu Personaje</button>' 
                            : `<button onclick="openBuyModal('${item.name}', '${item.price}', ${item.id})" class="w-full py-4 rounded-2xl bg-orange-600 hover:bg-orange-500 text-white text-[10px] font-black uppercase transition-all shadow-xl shadow-orange-600/30">Adquirir Guerrero</button>`
                        }
                    </div>
                </div>`;
        });
        if(typeof lucide !== 'undefined') lucide.createIcons();
    });
}