const grid = document.getElementById("grid");
const q = document.getElementById("q");
const chips = document.getElementById("chips");
const statTotal = document.getElementById("statTotal");
const y = document.getElementById("y");
const btnRefresh = document.getElementById("btnRefresh");

const modal = document.getElementById("modal");
const modalClose = document.getElementById("modalClose");
const modalX = document.getElementById("modalX");
const modalCancel = document.getElementById("modalCancel");
const modalGo = document.getElementById("modalGo");
const modalPreview = document.getElementById("modalPreview");

y.textContent = new Date().getFullYear();

let DATA = [];
let activeFilter = "all";
let lastOpen = null;

function esc(s=""){
  return String(s).replace(/[&<>"']/g, m => ({
    "&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"
  }[m]));
}

function badge(status){
  status = String(status || "").toLowerCase();
  if(status === "live") return `<span class="badge live">Live</span>`;
  if(status === "soon") return `<span class="badge soon">Soon</span>`;
  return `<span class="badge end">Ended</span>`;
}

function typeLabel(type){
  type = String(type || "").toLowerCase();
  if(type === "monthly" || type === "bulanan") return "Bulanan";
  if(type === "harian") return "Harian";
  if(type === "seasonal") return "Seasonal";
  if(type === "vip") return "VIP";
  return "Event";
}

function render(){
  const term = (q.value || "").trim().toLowerCase();

  const filtered = DATA.filter(it => {
    const passType = (activeFilter === "all")
      ? true
      : (String(it.type || "").toLowerCase() === String(activeFilter).toLowerCase());

    const hay = `${it.title} ${it.desc} ${it.period} ${typeLabel(it.type)}`.toLowerCase();
    const passSearch = term ? hay.includes(term) : true;

    return passType && passSearch;
  });

  statTotal.textContent = filtered.length;

  if(filtered.length === 0){
    grid.innerHTML = `<div class="card"><h3 class="title">Tidak ada event</h3><p class="desc">Coba ubah filter atau kata kunci pencarian.</p></div>`;
    return;
  }

  grid.innerHTML = filtered.map(it => `
    <article class="card">
      <div class="badges">
        ${badge(it.status)}
        <span class="badge">${esc(typeLabel(it.type))}</span>
      </div>
      <h3 class="title">${esc(it.title)}</h3>
      <p class="desc">${esc(it.desc)}</p>
      <div class="meta">
        <span>Periode</span>
        <span>${esc(it.period || "-")}</span>
      </div>
      <div class="btnrow">
        <button class="btn" data-open="${esc(it.id)}" type="button">Daftar Pemenang</button>
        <button class="small" data-copy="${esc(it.id)}" type="button" title="Salin link">Copy Link</button>
      </div>
    </article>
  `).join("");
}

function openModal(item){
  lastOpen = item;

  modalPreview.innerHTML = `
    <div><b>${esc(item.title)}</b></div>
    <div class="muted" style="margin-top:6px">${esc(item.desc)}</div>
    <div class="muted" style="margin-top:10px">
      Tujuan: <span style="color:rgba(234,240,255,.92)">${esc(item.winnerLink)}</span>
    </div>
  `;

  // simpan URL target ke atribut, supaya click handler pasti ambil yang benar
  modalGo.href = item.winnerLink;
  modalGo.setAttribute("data-url", item.winnerLink);

  // tampilkan modal (INI sebelumnya missing di script Anda)
  modal.classList.add("show");
  modal.setAttribute("aria-hidden", "false");
}

function closeModal(){
  modal.classList.remove("show");
  modal.setAttribute("aria-hidden", "true");
  lastOpen = null;
}

async function load(){
  try{
    const url = "./assets/events.json?v=" + Date.now();
    const res = await fetch(url, { cache: "no-store" });

    if(!res.ok){
      throw new Error(`events.json gagal di-load (HTTP ${res.status}). Pastikan path: /event/assets/events.json`);
    }

    const json = await res.json();
    if(!Array.isArray(json)){
      throw new Error("Format events.json salah. Harus berupa ARRAY: [ {...}, {...} ]");
    }

    DATA = json.filter(it => it && it.id && it.title && it.winnerLink);
    render();

  }catch(err){
    console.error(err);
    DATA = [];
    statTotal.textContent = "0";

    grid.innerHTML = `
      <div class="card">
        <h3 class="title">Event tidak bisa dimuat</h3>
        <p class="desc">Cek file <b>/event/assets/events.json</b> (akses publik) dan pastikan JSON valid.</p>
        <p class="desc" style="opacity:.85;margin-top:10px">
          Detail: ${esc(err.message || String(err))}
        </p>
      </div>
    `;
  }
}

document.addEventListener("click", (e) => {
  const openBtn = e.target.closest("[data-open]");
  const copyBtn = e.target.closest("[data-copy]");
  const chipBtn = e.target.closest(".chip");

  if(openBtn){
    const id = openBtn.getAttribute("data-open");
    const item = DATA.find(x => x.id === id);
    if(item) openModal(item);
  }

  if(copyBtn){
    const id = copyBtn.getAttribute("data-copy");
    const item = DATA.find(x => x.id === id);
    if(item){
      navigator.clipboard?.writeText(item.winnerLink).then(() => {
        copyBtn.textContent = "Copied";
        setTimeout(() => copyBtn.textContent = "Copy Link", 900);
      }).catch(() => {
        alert("Gagal menyalin. Copy manual: " + item.winnerLink);
      });
    }
  }

  if(chipBtn){
    document.querySelectorAll(".chip").forEach(x => x.classList.remove("active"));
    chipBtn.classList.add("active");
    activeFilter = chipBtn.getAttribute("data-filter");
    render();
  }
});

q.addEventListener("input", () => render());
btnRefresh.addEventListener("click", () => load());

modalClose.addEventListener("click", closeModal);
modalX.addEventListener("click", closeModal);
modalCancel.addEventListener("click", closeModal);
document.addEventListener("keydown", (e) => { if(e.key === "Escape") closeModal(); });

/* ====== NEW TAB FIX (PASTI) ====== */
modalGo.addEventListener("click", (e) => {
  e.preventDefault();
  const url = modalGo.getAttribute("data-url") || modalGo.href;
  if(url){
    window.open(url, "_blank", "noopener,noreferrer");
  }
  closeModal();
});

load();
