/* AFB_TriageSummary — single source of truth for triage HTML and preview */
(function (w) {
  /* -------------------- helpers: triage state -------------------- */
  function getTriageState() {
    try {
      if (
        w.afb_ajax &&
        w.afb_ajax.triage_state &&
        typeof w.afb_ajax.triage_state === "object"
      ) {
        return w.afb_ajax.triage_state;
      }
    } catch (e) {}
    return {};
  }

  function getAnswers() {
    const state = getTriageState();
    const triageAnswers =
      state && typeof state.answers === "object" ? state.answers : {};
    return triageAnswers;
  }

  function getSummarySlice() {
    const state = getTriageState();
    return state && typeof state.summary === "object" ? state.summary : {};
  }

  /* -------------------- helpers: cookies + triage ref -------------------- */
  function getCookie(name) {
    try {
      const n = String(name || "").trim();
      if (!n) return "";
      const parts = String(document.cookie || "").split(";");
      for (let i = 0; i < parts.length; i++) {
        const p = parts[i].trim();
        if (!p) continue;
        const eq = p.indexOf("=");
        const k = eq >= 0 ? p.slice(0, eq).trim() : p;
        if (k === n) {
          const v = eq >= 0 ? p.slice(eq + 1) : "";
          return decodeURIComponent(v || "");
        }
      }
    } catch {}
    return "";
  }

  function getTriageRef() {
    // Prefer state/meta if it ever gets added later; fallback to cookie.
    const state = getTriageState() || {};
    const answers = getAnswers() || {};
    const summary = getSummarySlice() || {};

    const candidates = [
      state.triage_ref,
      state.session_key,
      state.meta && state.meta.triage_ref,
      state.meta && state.meta.session_key,
      summary.triage_ref,
      answers.triage_ref,
      answers.session_key,
      getCookie("triage_gpt_session"),
    ];

    for (const v of candidates) {
      if (v != null && String(v).trim() !== "") return String(v).trim();
    }
    return "";
  }

  /* ---- tiny allowlist sanitizer (preview only) ---- */
  function sanitizeForPreview(html) {
    try {
      const allowedTags = new Set([
        "P",
        "BR",
        "B",
        "STRONG",
        "I",
        "EM",
        "UL",
        "OL",
        "LI",
        "A",
        "H1",
        "H2",
        "H3",
        "H4",
        "H5",
        "H6",
        "HR",
      ]);
      const allowedAttrs = { A: new Set(["href", "target", "rel"]) };
      const doc = new DOMParser().parseFromString(String(html || ""), "text/html");
      Array.from(doc.body.querySelectorAll("*")).forEach((el) => {
        if (!allowedTags.has(el.tagName)) {
          el.replaceWith(doc.createTextNode(el.textContent || ""));
          return;
        }
        Array.from(el.attributes).forEach((attr) => {
          if (
            !(
              allowedAttrs[el.tagName] &&
              allowedAttrs[el.tagName].has(attr.name)
            )
          ) {
            el.removeAttribute(attr.name);
          }
        });
      });
      return doc.body.innerHTML.trim();
    } catch {
      return "";
    }
  }

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

  /* ---- helpers: fetch values from triage answers with common fallbacks ---- */
  function val(...keys) {
    const answers = getAnswers();
    for (const k of keys) {
      if (Object.prototype.hasOwnProperty.call(answers, k)) {
        const v = answers[k];
        if (v != null && String(v).trim() !== "") {
          return v;
        }
      }
    }
    return "";
  }

  /* ---- NEW: find current subservice schema and JSON-driven summary fields ---- */
  function getCurrentSubserviceSchema() {
    const cfg = window.triageServiceConfig || window.triageSchema || {};
    const answers = getAnswers() || {};

    const svcName = String(answers.service || answers.service_name || "").toLowerCase();
    const subName = String(answers.subservice || answers.subservice_name || "").toLowerCase();

    const services = [];

    // cfg might be a single service { subservices: [...] } or a map of services
    if (cfg && Array.isArray(cfg.subservices)) {
      services.push(cfg);
    }
    Object.values(cfg || {}).forEach((svc) => {
      if (svc && Array.isArray(svc.subservices) && services.indexOf(svc) === -1) {
        services.push(svc);
      }
    });

    let best = null;

    services.forEach((svc) => {
      if (!svc || !Array.isArray(svc.subservices)) return;

      const svcLabel = String(svc.service || svc.name || "").toLowerCase();
      if (svcName && svcLabel && svcLabel !== svcName) return;

      svc.subservices.forEach((ss) => {
        if (!ss || !ss.name) return;
        const ssLabel = String(ss.name).toLowerCase();

        // Prefer exact subservice match, otherwise first usable one
        if (!subName || ssLabel === subName) {
          if (!best || ssLabel === subName) {
            best = ss;
          }
        }
      });
    });

    return best;
  }

  // ---- NEW: add every answered question (opt-out with "summary_hide": true) ----
  function buildDynamicSummaryFieldsFromSchema() {
    const ss = getCurrentSubserviceSchema();
    if (!ss || !Array.isArray(ss.questions)) return [];

    const answers = getAnswers() || {};
    const out = [];

    ss.questions.forEach((q) => {
      if (!q || !q.key) return;
      if (q.summary_hide === true) return; // opt-out flag

      const key = String(q.key);
      let valRaw = answers[key];

      // Multi-select ⇒ comma-separated list
      if (Array.isArray(valRaw)) valRaw = valRaw.join(", ");

      if (valRaw == null || String(valRaw).trim() === "") return;

      // Prefer explicit summary_label → fall back to condensed question text
      let label = q.summary_label || "";
      if (!label && q.text) label = String(q.text).replace(/\?[\s\S]*$/, "").trim();
      if (!label) label = key;

      out.push([label, valRaw]);
    });

    return out;
  }

  /* ---- build the bullet list block from known keys + JSON-driven extras ---- */
  function buildBulletListHTML() {
    const triageRef = getTriageRef();

    // Existing base fields (keep behaviour)
    const baseFields = [


      ["Service", val("service", "service_name")],
      ["Subservice", val("subservice", "subservice_name")],
      ["Requested Date", val("requested_date", "requestedDate", "date")],
      ["Approval", val("approval", "approver_status")],
      ["Audience", val("audience", "target_audience")],
      ["Broadcast Type", val("broadcast_type")],
      ["DDG", val("qh_update_ddg", "ddg_other")],
      ["Broadcast Title", val("broadcast_title", "title")],
      ["Triage Ref", triageRef],
    ];

    // Extra fields driven entirely by JSON (summary_preview = true)
    const dynamic = buildDynamicSummaryFieldsFromSchema();

    const seen = new Set();
    const fields = [];

    // 1) Push base fields first
    baseFields.forEach(([label, value]) => {
      if (String(value || "").trim() === "") return;
      const key = String(label || "").toLowerCase();
      seen.add(key);
      fields.push([label, value]);
    });

    // 2) Append JSON-driven fields, skipping duplicate labels
    dynamic.forEach(([label, value]) => {
      if (String(value || "").trim() === "") return;
      const key = String(label || "").toLowerCase();
      if (seen.has(key)) return;
      fields.push([label, value]);
    });

    if (!fields.length) return "";

    const items = fields.map(
      ([k, v]) => `<li>${escapeHtml(k)}: ${escapeHtml(v)}</li>`
    );

    return `<ul>\n${items.join("\n")}\n</ul>`;
  }

  /* ---- public: build full HTML fragment for Asana html_notes or plain-to-html ---- */
  function buildHTML() {
    const summary = getSummarySlice();
    const answers = getAnswers();

    // Prefer explicit HTML summary if stored in state
    let triageRaw =
      summary.triage_summary_html ||
      answers.triage_summary_html ||
      "";

    // Fallback: plain summary text
    let triagePlain =
      summary.triage_summary ||
      answers.triage_summary ||
      "";

    if (triagePlain) {
      triagePlain = String(triagePlain)
        .replace(/^\s*Thanks?,?\s+there!?\.?\s*/i, "")
        .trim();
    }

    const introPara = triageRaw
      ? String(triageRaw)
      : triagePlain
      ? `<p>${escapeHtml(triagePlain)}</p>`
      : "";

    const bullets = buildBulletListHTML();

    let out = "";
    if (introPara) out += introPara;
    if (bullets) out += `\n${bullets}`;

    return out.trim();
  }

  /* ---- public: render a preview card in the dynamic form ---- */
  function renderPreview($container) {
    if (!$container || !$container.append) return;

    const html = buildHTML();
    if (!html) return;

    const $box = jQuery(
      '<div class="p-4 border border-gray-200 rounded bg-gray-50">' +
        '<div class="triage-preview text-sm text-gray-700 leading-relaxed"></div>' +
      "</div>"
    );

    $box.find(".triage-preview")[0].innerHTML = sanitizeForPreview(html);
    $container.append($box);
  }

  /* expose */
  w.AFB_TriageSummary = {
    buildHTML,
    renderPreview,
    _sanitizeForPreview: sanitizeForPreview, // for debugging/tests
  };
})(window);
