/* =========================
   PCMOD Plus Explore — explore.js (Final Stable)

   ✅ Loads unified data.json (categories + items)
   ✅ Uses PNG thumbnails (fast + no flicker)
   ✅ Fallback when thumb missing (noThumb class)
   ✅ Deep-link to reels: ./reels.html?r=slug
   ✅ Chips + search + URL sync
   ✅ Sidebar collapse + logo swap
   ✅ Default OPEN on every visit (even if saved was collapsed)
   ========================= */

const DATA_JSON_URL = "./data.json";
const THUMBS_BASE   = "https://media.pcmod.ir/thumbs";

/* -------------------------
   Safe helpers (NO crash)
------------------------- */
function safe(fn){
  try { return fn(); } catch(e){ console.error(e); return undefined; }
}

function escapeHtml(str){
  return String(str || "")
    .replace(/&/g,"&amp;")
    .replace(/</g,"&lt;")
    .replace(/>/g,"&gt;")
    .replace(/"/g,"&quot;")
    .replace(/'/g,"&#039;");
}

function getQueryCat(){
  const u = new URL(location.href);
  return u.searchParams.get("cat");
}

function updateURLCat(cat){
  const u = new URL(location.href);
  if (!cat || cat === "all") u.searchParams.delete("cat");
  else u.searchParams.set("cat", cat);
  history.replaceState({}, "", u.toString());
}

/* -------------------------
   Sidebar (Desktop)
   - Default OPEN always
   - Toggle works
   - Logo swaps
------------------------- */
function initSidebar(){
  const side = document.getElementById("sideNav");
  const tog  = document.getElementById("sideToggle");
  const img  = document.querySelector(".sideLogoImg");
  if (!side || !tog || !img) return;

  const STORE_KEY = "pcmod_side_collapsed";

  const full = img.getAttribute("data-full") || img.src;
  const mini = img.getAttribute("data-mini") || img.src;

  const apply = (collapsed) => {
    side.classList.toggle("collapsed", !!collapsed);
    img.src = collapsed ? mini : full;

    const ico = tog.querySelector("i");
    if (ico) {
      ico.classList.toggle("fa-bars", !collapsed);
      ico.classList.toggle("fa-xmark", collapsed);
    }

    // ذخیره وضعیت (اختیاری)
    safe(() => localStorage.setItem(STORE_KEY, collapsed ? "1" : "0"));
  };

  // ✅ مهم: همیشه شروع باز
  // حتی اگر قبلش ذخیره شده "بسته"، ما override می‌کنیم که باز باشه.
  safe(() => localStorage.setItem(STORE_KEY, "0"));
  apply(false);

  // ✅ کلیک: باز <-> بسته
  tog.addEventListener("click", (e) => {
    e.preventDefault();
    e.stopPropagation();
    apply(!side.classList.contains("collapsed"));
  });
}

/* -------------------------
   DOM refs
------------------------- */
const grid  = document.getElementById("grid");
const search = document.getElementById("search");
const chips  = document.getElementById("chips");
const statVideos = document.getElementById("statVideos");

let CATEGORIES = []; // [{id,title}]
let ITEMS = [];      // [{slug,title,desc,cat,thumb}]
let activeCat = getQueryCat() || "all";
let q = "";

/* -------------------------
   Load unified data.json
------------------------- */
async function loadExploreData(){
  const res = await fetch(`${DATA_JSON_URL}?ts=${Date.now()}`, { cache: "no-store" });
  if(!res.ok) throw new Error(`data.json load failed: ${res.status}`);

  const json = await res.json();

  CATEGORIES = (json.categories || [])
    .filter(c => c && c.id)
    .map(c => ({ id: String(c.id), title: String(c.title || c.id) }));

  ITEMS = (json.items || [])
    .filter(it => it && it.slug)
    .map(it => ({
      slug: String(it.slug),
      title: String(it.title || it.slug),
      desc: String(it.desc || ""),
      cat: String(it.cat || "pcmod"),
      thumb: `${THUMBS_BASE}/${encodeURIComponent(String(it.slug))}.png`
    }));
}

function catToLabel(cat){
  const found = CATEGORIES.find(c => c.id === cat);
  return found ? found.title : "PCMOD";
}

/* -------------------------
   Render
------------------------- */
function matchFilter(it){
  const catOk = (activeCat === "all") ? true : it.cat === activeCat;
  if (!catOk) return false;

  if (!q) return true;

  const text = `${it.title||""} ${it.slug||""} ${it.desc||""}`.toLowerCase();
  return text.includes(q);
}

function itemToCardHTML(it){
  const reelsUrl = `./reels.html?r=${encodeURIComponent(it.slug)}`;

  return `
    <article class="card" tabindex="0" data-slug="${escapeHtml(it.slug)}">
      <a class="cardLink" href="${reelsUrl}" aria-label="مشاهده ویدئو: ${escapeHtml(it.title)}"></a>

      <div class="thumb">
        <img class="thumbImg" src="${escapeHtml(it.thumb)}" alt="${escapeHtml(it.title)}" loading="lazy" decoding="async" />
        <div class="badge">${escapeHtml(catToLabel(it.cat))}</div>
      </div>

      <div class="metaRow">
        <div class="h">${escapeHtml(it.title)}</div>
        <div class="p">${escapeHtml(it.desc || "")}</div>
      </div>
    </article>
  `;
}

function bindThumbFallbackOnce(){
  if (!grid) return;

  grid.querySelectorAll(".thumbImg").forEach(img => {
    if (img.dataset.bound === "1") return;
    img.dataset.bound = "1";

    img.addEventListener("error", () => {
      img.style.display = "none";
      img.parentElement?.classList.add("noThumb");
    }, { once:true });
  });
}

function render(){
  if (!grid) return;

  const items = ITEMS.filter(matchFilter);
  grid.innerHTML = items.map(itemToCardHTML).join("");

  grid.querySelectorAll(".card").forEach((card) => {
    card.addEventListener("keydown", (ev) => {
      if (ev.key === "Enter" || ev.key === " ") {
        ev.preventDefault();
        card.querySelector(".cardLink")?.click();
      }
    });
  });

  bindThumbFallbackOnce();
}

/* -------------------------
   Chips UI + search
------------------------- */
function syncChipsUI(){
  if (!chips) return;
  chips.querySelectorAll(".chip, .pcmodPill").forEach((b) => {
    b.classList.toggle("active", (b.dataset.cat || "all") === activeCat);
  });
}

function bootUI(){
  if (statVideos) statVideos.textContent = String(ITEMS.length);

  syncChipsUI();
  render();

  if (search) {
    search.addEventListener("input", () => {
      q = (search.value || "").trim().toLowerCase();
      render();
    });
  }

  if (chips) {
    chips.addEventListener("click", (e) => {
      const btn = e.target.closest(".chip, .pcmodPill");
      if (!btn) return;

      activeCat = btn.dataset.cat || "all";
      updateURLCat(activeCat);
      syncChipsUI();
      render();
    });
  }
}

/* -------------------------
   User popover
------------------------- */
function initUserPopover(){
  const btn = document.getElementById("userBtn");
  const pop = document.getElementById("userPop");
  if (!btn || !pop) return;

  const close = () => {
    pop.classList.remove("open");
    btn.setAttribute("aria-expanded", "false");
  };

  btn.addEventListener("click", (e) => {
    e.stopPropagation();
    const isOpen = pop.classList.toggle("open");
    btn.setAttribute("aria-expanded", isOpen ? "true" : "false");
  });

  document.addEventListener("click", close);
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") close();
  });
}

/* -------------------------
   Boot
------------------------- */
(function start(){
  // تضمین DOM
  const run = async () => {
    safe(() => initSidebar());
    safe(() => initUserPopover());

    try{
      await loadExploreData();
    }catch(e){
      console.error(e);
      CATEGORIES = [];
      ITEMS = [];
    }

    safe(() => bootUI());
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", run);
  } else {
    run();
  }
})();
