/**
 * AppsTab — native Zeq App Store inside the extension panel.
 *
 * Pulls the live catalogue from the API (/api/store/apps + /api/store/categories)
 * and renders it natively (no website, no iframe to browse). Search + category
 * filter; each card opens the app IN-PANEL via window.openAppInPanel.
 *
 * Depends on: window.ZeqConfig, window.openAppInPanel (panel.js), window.ZeqAuth (optional).
 *
 * @version 1.287.6
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
const AppsTab = (() => {
  "use strict";

  let _containerId = null;
  let _apps = [];
  let _cats = [];
  let _activeCat = "all";
  let _query = "";
  let _loaded = false;

  function esc(s) { return String(s == null ? "" : s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }
  async function _api() { return await ZeqConfig.api(); }
  async function _origin() { return await ZeqConfig.origin(); }
  function _headers() {
    const h = { "Content-Type": "application/json" };
    if (typeof ZeqAuth !== "undefined" && ZeqAuth.isAuthenticated()) Object.assign(h, ZeqAuth.getHeaders());
    return h;
  }
  function _openApp(path, name) {
    _origin().then((o) => {
      if (typeof window.openAppInPanel === "function") window.openAppInPanel(o + path, name);
      else try { chrome.tabs.create({ url: o + path }); } catch (_) {}
    });
  }

  async function _load() {
    const api = await _api();
    try {
      const [ar, cr] = await Promise.all([
        fetch(api + "/store/apps", { headers: _headers() }),
        fetch(api + "/store/categories", { headers: _headers() }),
      ]);
      const aj = await ar.json().catch(() => ({}));
      const cj = await cr.json().catch(() => ({}));
      _apps = aj.apps || [];
      _cats = cj.categories || [];
      _loaded = true;
      return true;
    } catch (_) { return false; }
  }

  function _filtered() {
    const q = _query.trim().toLowerCase();
    return _apps.filter((a) => {
      if (_activeCat !== "all" && a.category !== _activeCat) return false;
      if (!q) return true;
      return (a.name || "").toLowerCase().includes(q) || (a.description || "").toLowerCase().includes(q) || (a.slug || "").toLowerCase().includes(q);
    });
  }

  function _card(a) {
    const beta = a.status && a.status !== "live";
    return (
      '<button class="zapp-card" data-path="' + esc(a.path || ("/apps/" + a.slug + "/")) + '" data-name="' + esc(a.name) + '">' +
      '<div class="zapp-ico">' + esc(a.icon || "▦") + "</div>" +
      '<div class="zapp-body"><div class="zapp-name">' + esc(a.name) + (beta ? ' <span class="zapp-beta">beta</span>' : "") + "</div>" +
      '<div class="zapp-desc">' + esc(a.description || "") + "</div></div></button>"
    );
  }

  function _render() {
    const c = document.getElementById(_containerId);
    if (!c) return;
    if (!_loaded) { c.innerHTML = '<div class="tab-scroll" style="padding:14px"><p style="color:var(--text-muted);font-size:12px">Loading the App Store…</p></div>'; return; }

    const chips = [{ id: "all", name: "All", icon: "▦" }].concat(_cats)
      .map((cat) => '<button class="zapp-chip' + (cat.id === _activeCat ? " active" : "") + '" data-cat="' + esc(cat.id) + '">' +
        esc((cat.icon ? cat.icon + " " : "") + cat.name) + (cat.appCount != null ? ' <span style="opacity:.6">' + cat.appCount + "</span>" : "") + "</button>").join("");

    const list = _filtered();
    const featured = _activeCat === "all" && !_query ? _apps.filter((a) => a.featured) : [];
    const cards = list.map(_card).join("") || '<p style="color:var(--text-muted);font-size:12px;padding:8px">No apps match.</p>';

    c.innerHTML =
      '<style>' +
      ".zapp-wrap{padding:12px;overflow-y:auto;height:100%}" +
      ".zapp-search{width:100%;padding:9px 12px;background:rgba(0,0,0,.45);border:1px solid var(--border);border-radius:8px;color:var(--text-primary);font-size:13px;outline:none;box-sizing:border-box;margin-bottom:10px}" +
      ".zapp-search:focus{border-color:var(--accent-mint)}" +
      ".zapp-chips{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px}" +
      ".zapp-chip{font-size:10.5px;padding:5px 9px;border-radius:14px;border:1px solid var(--border);background:transparent;color:var(--text-secondary);cursor:pointer;white-space:nowrap}" +
      ".zapp-chip.active{border-color:var(--accent-mint);color:var(--accent-mint);background:rgba(0,255,136,.06)}" +
      ".zapp-h{font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:var(--text-muted);margin:6px 0}" +
      ".zapp-card{display:flex;gap:10px;width:100%;text-align:left;padding:10px;margin-bottom:8px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:10px;cursor:pointer;align-items:flex-start}" +
      ".zapp-card:hover{border-color:var(--accent-mint)}" +
      ".zapp-ico{font-size:20px;line-height:1;flex-shrink:0}" +
      ".zapp-name{font-weight:600;font-size:13px;color:var(--text-primary)}" +
      ".zapp-beta{font-size:9px;color:var(--text-muted);border:1px solid var(--border);border-radius:8px;padding:0 5px;margin-left:4px}" +
      ".zapp-desc{font-size:11px;color:var(--text-secondary);line-height:1.45;margin-top:2px}" +
      "</style>" +
      '<div class="zapp-wrap">' +
      '<input class="zapp-search" id="zapp-search" placeholder="Search apps…" value="' + esc(_query) + '">' +
      '<div class="zapp-chips">' + chips + "</div>" +
      (featured.length ? '<div class="zapp-h">Featured</div>' + featured.map(_card).join("") + '<div class="zapp-h">All apps</div>' : "") +
      cards +
      "</div>";

    const search = document.getElementById("zapp-search");
    if (search) {
      search.addEventListener("input", (e) => { _query = e.target.value; _render(); });
      // keep focus + caret after re-render
      const v = search.value; search.focus(); search.setSelectionRange(v.length, v.length);
    }
    c.querySelectorAll(".zapp-chip").forEach((b) => b.addEventListener("click", () => { _activeCat = b.getAttribute("data-cat"); _query = document.getElementById("zapp-search")?.value || ""; _render(); }));
    c.querySelectorAll(".zapp-card").forEach((b) => b.addEventListener("click", () => _openApp(b.getAttribute("data-path"), b.getAttribute("data-name"))));
  }

  async function init(containerId) {
    _containerId = containerId;
    _render(); // loading state
    if (!_loaded) await _load();
    _render();
  }

  return { init };
})();

if (typeof module !== "undefined" && module.exports) { module.exports = AppsTab; }
