document.addEventListener("DOMContentLoaded", function(){
const targetContainer=document.getElementById("treasure-target-container");
if(!targetContainer) return;
const currentPostId=parseInt(TreasureData.post_id, 10);
function renderAndInitChest(){
targetContainer.innerHTML=TreasureData.chest_html;
const chestWrapper=document.getElementById("treasure-chest-wrapper");
const chestImg=document.getElementById("treasure-chest-img");
const modalOverlay=document.getElementById("treasure-modal-overlay");
const modalCloseBtn=document.getElementById("treasure-modal-close");
const modalCodeText=document.getElementById("treasure-modal-code");
const hintText=document.getElementById("treasure-chest-hint");
if(localStorage.getItem("treasure_opened")==="true"){
chestImg.src=TreasureData.chest_open_img;
hintText.innerText="Tento poklad ste už objavili.";
chestImg.style.cursor="default";
chestWrapper.classList.remove("treasure-chest-hidden");
return;
}else{
chestWrapper.classList.remove("treasure-chest-hidden");
}
chestImg.addEventListener("click", function(){
if(localStorage.getItem("treasure_opened")==="true") return;
chestImg.style.transform="scale(1.1)";
setTimeout(()=> { chestImg.style.transform="scale(1)"; }, 200);
modalOverlay.classList.remove("treasure-hidden");
let formData=new FormData();
formData.append('action', 'generate_treasure_reward');
fetch(TreasureData.ajax_url, {
method: 'POST',
body: formData
})
.then(response=> response.json())
.then(data=> {
if(data.success){
localStorage.setItem("treasure_opened", "true");
chestImg.src=TreasureData.chest_open_img;
modalCodeText.innerText="🎁 DARČEK PRIDANÝ";
hintText.innerText="Mystery darček bol úspešne odomknutý!";
chestImg.style.cursor="default";
}else{
modalCodeText.innerText="Nastala chyba.";
}})
.catch(error=> {
console.error('Chyba:', error);
modalCodeText.innerText="Prepojenie zlyhalo.";
});
});
modalCloseBtn.addEventListener("click", function(){
modalOverlay.classList.add("treasure-hidden");
});
}
const cacheKey='treasure_locations_data';
const cacheTimeKey='treasure_locations_time';
const now=new Date().getTime();
const cachedData=sessionStorage.getItem(cacheKey);
const cachedTime=sessionStorage.getItem(cacheTimeKey);
if(cachedData&&cachedTime&&(now - parseInt(cachedTime) < 7200000)){
const locations=JSON.parse(cachedData);
const products=locations.products.map(Number);
const posts=locations.posts.map(Number);
if(products.includes(currentPostId)||posts.includes(currentPostId)){
renderAndInitChest();
}}else{
fetch(TreasureData.ajax_url + '?action=get_treasure_locations', { cache: 'no-store' })
.then(response=> response.json())
.then(data=> {
if(data.success){
sessionStorage.setItem(cacheKey, JSON.stringify(data.data));
sessionStorage.setItem(cacheTimeKey, now.toString());
const products=data.data.products.map(Number);
const posts=data.data.posts.map(Number);
if(products.includes(currentPostId)||posts.includes(currentPostId)){
renderAndInitChest();
}}
});
}});