function makeZine({ name, blurb, format, site, title }) {
  let zine = document.createElement("li");

  let h2 = document.createElement("h2");
  if (site) {
    let a = document.createElement("a");
    a.innerHTML = name;
    a.href = site;
    h2.append(a);
  } else {
    h2.innerHTML = name;
  }
  zine.append(h2);

  if (title) {
    if (typeof title == "string") {
      let p = document.createElement("p");
      p.innerHTML = " made a " + format + " zine called ";
      zine.append(p);

      let h3 = document.createElement("h3");
      h3.innerHTML = title;
      zine.append(h3);
    } else {
      let p = document.createElement("p");
      p.innerHTML = " made " + format + " zines called ";
      zine.append(p);
      
      for (let i = 0; i < title.length; i++) {
        let h3 = document.createElement("h3");
        h3.innerHTML = title[i];
        zine.append(h3);
      }
    }

    let p = document.createElement("p");
    p.innerHTML = "and the original blurb was";
    zine.append(p);
  } else {
    let p = document.createElement("p");
    p.innerHTML = " is making a " + format + " zine:";
    zine.append(p);
  }

  let bq = document.createElement("blockquote");
  let bqP = document.createElement("p");
  bqP.innerHTML = blurb;
  bq.append(bqP);
  zine.append(bq);

  return zine;
}

function makeZinePage(zines) {
  for (let i = 0; i < zines.length; i++) {
    zineContainer.append(makeZine(zines[i]));
  }

  let zineCounter = document.getElementById("zine-count");
  let total = zines.length;
  let physical = zines.filter(
    (zine) => zine.format == "physical" || zine.format == "physical/digital"
  ).length;
  let digital = zines.filter(
    (zine) => zine.format == "digital" || zine.format == "physical/digital"
  ).length;

  let p = document.createElement("p");
  p.innerHTML =
    total +
    " artists. " +
    physical +
    " physical zines. " +
    digital +
    " digital zines.";
  zineCounter.append(p);
}

let zineContainer = document.getElementById("zine-container");

let script = document.currentScript;
let zinefile = script.dataset.zinefile;

fetch(zinefile)
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error, status = ${response.status}`);
    }
    return response.json();
  })
  .then((zines) => makeZinePage(zines))
  .catch((error) => {
    console.log(`Error: ${error.message}`);
  });
