/**
 * SkillsTab — native Zeq Skills directory inside the extension panel.
 *
 * Browse the industry skill templates (GET /api/skills), open one to see its
 * domains/inputs/examples (GET /api/skills/:id), then generate a concrete skill
 * definition (POST /api/skills/generate) — shown in-panel with copy + .md download.
 *
 * Depends on: window.ZeqConfig, window.ZeqAuth (optional).
 *
 * @version 1.287.6
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
const SkillsTab = (() => {
  "use strict";

  let _containerId = null;
  let _skills = [];
  let _loaded = false;
  let _view = "list"; // list | detail
  let _current = null;

  function esc(s) { return String(s == null ? "" : s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }
  async function _api() { return await ZeqConfig.api(); }
  function _headers() {
    const h = { "Content-Type": "application/json" };
    if (typeof ZeqAuth !== "undefined" && ZeqAuth.isAuthenticated()) Object.assign(h, ZeqAuth.getHeaders());
    return h;
  }

  async function _load() {
    try {
      const api = await _api();
      const r = await fetch(api + "/skills", { headers: _headers() });
      const j = await r.json().catch(() => ({}));
      _skills = j.skills || [];
      _loaded = true;
      return true;
    } catch (_) { return false; }
  }

  const STYLE = "<style>" +
    ".zsk-wrap{padding:12px;overflow-y:auto;height:100%}" +
    ".zsk-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}" +
    ".zsk-card:hover{border-color:var(--accent-mint)}" +
    ".zsk-ico{font-size:20px;flex-shrink:0}" +
    ".zsk-name{font-weight:600;font-size:13px;color:var(--text-primary)}" +
    ".zsk-dom{font-size:11px;color:var(--text-secondary);margin-top:2px}" +
    ".zsk-back{background:transparent;border:1px solid var(--border);border-radius:6px;color:var(--text-primary);font-size:12px;padding:5px 9px;cursor:pointer;margin-bottom:10px}" +
    ".zsk-h{font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:var(--text-muted);margin:12px 0 4px}" +
    ".zsk-input{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}" +
    ".zsk-input:focus{border-color:var(--accent-mint)}" +
    ".zsk-btn{width:100%;margin-top:10px;padding:11px;border-radius:8px;border:1px solid var(--accent-mint);background:var(--accent-mint);color:#02120a;font-weight:700;font-size:13px;cursor:pointer}" +
    ".zsk-btn:disabled{opacity:.5}" +
    ".zsk-chiprow{display:flex;flex-wrap:wrap;gap:5px}" +
    ".zsk-chip{font-size:10.5px;padding:3px 8px;border-radius:12px;border:1px solid var(--border);color:var(--text-secondary)}" +
    ".zsk-out{margin-top:12px}" +
    ".zsk-out pre{white-space:pre-wrap;word-break:break-word;font-size:11px;background:rgba(0,0,0,.5);border:1px solid var(--border);border-radius:8px;padding:10px;max-height:240px;overflow:auto}" +
    ".zsk-err{color:var(--accent-red);font-size:11.5px;margin-top:8px}" +
    "</style>";

  function _renderList() {
    const cards = _skills.map((s) =>
      '<button class="zsk-card" data-id="' + esc(s.id) + '"><div class="zsk-ico">' + esc(s.icon || "✨") + "</div>" +
      '<div><div class="zsk-name">' + esc(s.label) + "</div>" +
      '<div class="zsk-dom">' + esc((s.domains || []).join(" · ")) + "</div></div></button>"
    ).join("");
    return STYLE + '<div class="zsk-wrap">' +
      '<p style="font-size:11px;color:var(--text-secondary);margin:0 0 10px">Pick an industry template, describe your use case, and generate a grounded skill definition — free, in-panel.</p>' +
      (cards || '<p style="color:var(--text-muted);font-size:12px">No skills available.</p>') + "</div>";
  }

  function _renderDetail(s) {
    const inputs = Object.entries(s.inputs || {}).map(([k, u]) => '<span class="zsk-chip">' + esc(k) + " [" + esc(u) + "]</span>").join("");
    const examples = (s.examples || []).map((e) => "<li>" + esc(e) + "</li>").join("");
    return STYLE + '<div class="zsk-wrap">' +
      '<button class="zsk-back" id="zsk-back">‹ All skills</button>' +
      '<div class="zsk-name" style="font-size:16px">' + esc(s.icon || "✨") + " " + esc(s.label) + "</div>" +
      '<div class="zsk-h">Domains</div><div class="zsk-dom">' + esc((s.domains || []).join(" · ")) + "</div>" +
      '<div class="zsk-h">Suggested inputs</div><div class="zsk-chiprow">' + inputs + "</div>" +
      (examples ? '<div class="zsk-h">Example applications</div><ul style="font-size:11.5px;color:var(--text-secondary);line-height:1.5;padding-left:18px;margin:0">' + examples + "</ul>" : "") +
      '<div class="zsk-h">Generate a skill</div>' +
      '<input class="zsk-input" id="zsk-usecase" placeholder="Describe your use case (min 5 chars)…">' +
      '<button class="zsk-btn" id="zsk-gen">Generate skill definition</button>' +
      '<div class="zsk-err" id="zsk-err" style="display:none"></div>' +
      '<div class="zsk-out" id="zsk-out"></div>' +
      "</div>";
  }

  function _render() {
    const c = document.getElementById(_containerId);
    if (!c) return;
    if (!_loaded) { c.innerHTML = '<div class="zsk-wrap" style="padding:14px"><p style="color:var(--text-muted);font-size:12px">Loading skills…</p></div>'; return; }
    if (_view === "detail" && _current) { c.innerHTML = _renderDetail(_current); _bindDetail(c); return; }
    c.innerHTML = _renderList();
    c.querySelectorAll(".zsk-card").forEach((b) => b.addEventListener("click", () => {
      _current = _skills.find((x) => x.id === b.getAttribute("data-id"));
      _view = "detail"; _render();
    }));
  }

  function _bindDetail(c) {
    c.querySelector("#zsk-back")?.addEventListener("click", () => { _view = "list"; _current = null; _render(); });
    c.querySelector("#zsk-gen")?.addEventListener("click", async (e) => {
      const uc = (document.getElementById("zsk-usecase")?.value || "").trim();
      const err = document.getElementById("zsk-err");
      const out = document.getElementById("zsk-out");
      if (uc.length < 5) { if (err) { err.textContent = "Describe your use case (at least 5 characters)."; err.style.display = "block"; } return; }
      const btn = e.currentTarget; btn.disabled = true; btn.textContent = "Running 7-step wizard…"; if (err) err.style.display = "none";
      try {
        const api = await _api();
        const r = await fetch(api + "/skills/generate", { method: "POST", headers: _headers(), body: JSON.stringify({ industry: _current.id, useCase: uc }) });
        const j = await r.json().catch(() => ({}));
        if (!r.ok || !j.skill) throw new Error(j.error || ("Generate failed (" + r.status + ")"));
        const md = j.skill.markdown || "";
        out.innerHTML =
          '<div class="zsk-name">' + esc(j.skill.name) + "</div>" +
          '<div class="zsk-dom" style="margin:4px 0">Domain: ' + esc(j.skill.domain) + " · operators: " + esc((j.skill.operators || []).join(", ")) + "</div>" +
          '<div style="display:flex;gap:6px;margin:6px 0"><button class="zsk-back" id="zsk-copy">Copy .md</button><button class="zsk-back" id="zsk-dl">Download .md</button></div>' +
          "<pre>" + esc(md.slice(0, 4000)) + (md.length > 4000 ? "\n…" : "") + "</pre>";
        document.getElementById("zsk-copy")?.addEventListener("click", (ev) => { navigator.clipboard.writeText(md).then(() => { ev.currentTarget.textContent = "Copied!"; }).catch(() => {}); });
        document.getElementById("zsk-dl")?.addEventListener("click", () => {
          const blob = new Blob([md], { type: "text/markdown" });
          const url = URL.createObjectURL(blob);
          const a = document.createElement("a"); a.href = url; a.download = (j.skill.skillId || "zeq-skill") + ".md";
          document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url);
        });
      } catch (ex) {
        if (err) { err.textContent = ex.message || "Generate failed"; err.style.display = "block"; }
      } finally { btn.disabled = false; btn.textContent = "Generate skill definition"; }
    });
  }

  async function init(containerId) {
    _containerId = containerId;
    _view = "list"; _current = null;
    _render();
    if (!_loaded) await _load();
    _render();
  }

  return { init };
})();

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