(function () {
  "use strict";

  var API_URL = "https://ems.myadspaceinc.com/api/media-realtime";

  function datetimeLocalToApi(s) {
    if (!s || typeof s !== "string") return "";
    var normalized = s.replace("T", " ");
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(normalized)) {
      return normalized + ":00";
    }
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(normalized)) {
      return normalized.slice(0, 19);
    }
    return normalized;
  }

  function cellValue(v) {
    if (v === null || v === undefined) return "";
    if (typeof v === "object") return JSON.stringify(v);
    return String(v);
  }

  function rowsFromJson(data) {
    if (data == null) {
      return { columns: [], rows: [] };
    }
    if (Array.isArray(data)) {
      if (data.length === 0) {
        return { columns: [], rows: [] };
      }
      var first = data[0];
      if (typeof first === "object" && first !== null && !Array.isArray(first)) {
        var keys = Object.keys(first);
        return {
          columns: keys,
          rows: data.map(function (row) {
            return keys.map(function (k) {
              return cellValue(row[k]);
            });
          }),
        };
      }
      return {
        columns: ["#", "value"],
        rows: data.map(function (v, i) {
          return [String(i + 1), cellValue(v)];
        }),
      };
    }
    if (typeof data === "object") {
      var nested = data.data || data.results || data.items || data.records;
      if (Array.isArray(nested)) {
        return rowsFromJson(nested);
      }
      return {
        columns: ["key", "value"],
        rows: Object.keys(data).map(function (k) {
          return [k, cellValue(data[k])];
        }),
      };
    }
    return { columns: ["value"], rows: [[cellValue(data)]] };
  }

  function renderTable(tbody, thead, data) {
    var parsed = rowsFromJson(data);
    thead.innerHTML = "";
    tbody.innerHTML = "";

    if (!parsed.columns.length && !parsed.rows.length) {
      tbody.innerHTML =
        '<tr><td class="track-table__empty" colspan="1">No data returned.</td></tr>';
      return;
    }

    var trHead = document.createElement("tr");
    parsed.columns.forEach(function (col) {
      var th = document.createElement("th");
      th.scope = "col";
      th.textContent = col;
      trHead.appendChild(th);
    });
    thead.appendChild(trHead);

    parsed.rows.forEach(function (row) {
      var tr = document.createElement("tr");
      row.forEach(function (cell) {
        var td = document.createElement("td");
        td.textContent = cell;
        tr.appendChild(td);
      });
      tbody.appendChild(tr);
    });
  }

  document.addEventListener("DOMContentLoaded", function () {
    var form = document.getElementById("track-campaign-form");
    var statusEl = document.getElementById("track-campaign-status");
    var tbody = document.querySelector("#track-campaign-table tbody");
    var thead = document.querySelector("#track-campaign-table thead");
    if (!form || !statusEl || !tbody || !thead) return;

    form.addEventListener("submit", function (e) {
      e.preventDefault();

      var material = (form.elements.namedItem("material") && form.elements.namedItem("material").value) || "";
      var media = (form.elements.namedItem("media") && form.elements.namedItem("media").value) || "";
      var startInput = form.elements.namedItem("startdate");
      var endInput = form.elements.namedItem("enddate");
      var startdate = datetimeLocalToApi(startInput && startInput.value);
      var enddate = datetimeLocalToApi(endInput && endInput.value);

      if (!material.trim() || !media.trim() || !startdate || !enddate) {
        statusEl.textContent = "Please fill material, media, start date, and end date.";
        statusEl.className = "track-campaign-status track-campaign-status--error";
        return;
      }

      var params = new URLSearchParams();
      params.set("material", material.trim());
      params.set("media", media.trim());
      params.set("startdate", startdate);
      params.set("enddate", enddate);

      var url = API_URL + "?" + params.toString();
      statusEl.textContent = "Loading…";
      statusEl.className = "track-campaign-status track-campaign-status--loading";
      tbody.innerHTML = "";
      thead.innerHTML = "";

      fetch(url, { method: "GET", credentials: "omit" })
        .then(function (res) {
          if (!res.ok) {
            return res.text().then(function (t) {
              throw new Error(res.status + " " + res.statusText + (t ? ": " + t.slice(0, 200) : ""));
            });
          }
          var ct = res.headers.get("content-type") || "";
          if (ct.indexOf("application/json") !== -1) {
            return res.json();
          }
          return res.text().then(function (t) {
            try {
              return JSON.parse(t);
            } catch (err) {
              throw new Error("Response was not JSON.");
            }
          });
        })
        .then(function (json) {
          renderTable(tbody, thead, json);
          statusEl.textContent = "Showing API result (" + url.split("?")[0] + ").";
          statusEl.className = "track-campaign-status track-campaign-status--ok";
        })
        .catch(function (err) {
          thead.innerHTML = "";
          tbody.innerHTML =
            '<tr><td class="track-table__empty" colspan="99">' +
            "Request failed: " +
            (err && err.message ? err.message : String(err)) +
            "</td></tr>";
          statusEl.textContent =
            "Could not load data. If the API runs on another origin, ensure CORS allows this site.";
          statusEl.className = "track-campaign-status track-campaign-status--error";
        });
    });
  });
})();
