// The Medicine page — Big Pharma + their consumer brands.
//
// The same handful of pharmaceutical giants — Pfizer, J&J, Roche, Novartis,
// Merck, Sanofi, AstraZeneca, GSK, AbbVie, Bayer — own the drugs in the
// medicine cabinet, the consumer products in the bathroom, the chemicals
// on the lawn. The same logic as the Food and Media pyramids: the choice
// the supermarket aisle presents is an illusion built on common ownership.

(function () {
  const root = document.getElementById("pharma-pyramid");
  if (!root) return;
  const view = document.querySelector('.view[data-view="medicine"]');
  if (!view) return;

  const t = (k, fb) => (window.i18n && window.i18n.t) ? window.i18n.t(k, fb) : fb;

  const PARENTS = {
    pfz:  { name: "Pfizer",         color: "#0288d1" },
    jnj:  { name: "Johnson & Johnson", color: "#dc2626" },
    rch:  { name: "Roche",          color: "#7c3aed" },
    nov:  { name: "Novartis",       color: "#f59e0b" },
    mrk:  { name: "Merck",          color: "#10b981" },
    snf:  { name: "Sanofi",         color: "#a855f7" },
    azn:  { name: "AstraZeneca",    color: "#ef4444" },
    gsk:  { name: "GSK",            color: "#0d9488" },
    abv:  { name: "AbbVie",         color: "#6366f1" },
    bay:  { name: "Bayer / Monsanto", color: "#84cc16" }
  };

  const PRODUCTS = [
    // Pfizer
    { name: "Lipitor",       parent: "pfz" },
    { name: "Viagra",        parent: "pfz" },
    { name: "Celebrex",      parent: "pfz" },
    { name: "Lyrica",        parent: "pfz" },
    { name: "Eliquis",       parent: "pfz" },
    { name: "Comirnaty (COVID vax)", parent: "pfz" },
    { name: "Zithromax",     parent: "pfz" },
    // Johnson & Johnson (consumer brands are the killer reveal here)
    { name: "Tylenol",       parent: "jnj" },
    { name: "Motrin",        parent: "jnj" },
    { name: "Band-Aid",      parent: "jnj" },
    { name: "Listerine",     parent: "jnj" },
    { name: "Neutrogena",    parent: "jnj" },
    { name: "Aveeno",        parent: "jnj" },
    { name: "Johnson's Baby",parent: "jnj" },
    { name: "Splenda",       parent: "jnj" },
    { name: "Stelara",       parent: "jnj" },
    // Roche
    { name: "Avastin",       parent: "rch" },
    { name: "Herceptin",     parent: "rch" },
    { name: "Tamiflu",       parent: "rch" },
    { name: "Rituxan",       parent: "rch" },
    { name: "Accu-Chek",     parent: "rch" },
    // Novartis
    { name: "Diovan",        parent: "nov" },
    { name: "Gleevec",       parent: "nov" },
    { name: "Sandimmune",    parent: "nov" },
    { name: "Cosentyx",      parent: "nov" },
    { name: "Voltaren (OTC)",parent: "nov" },
    // Merck
    { name: "Keytruda",      parent: "mrk" },
    { name: "Gardasil (HPV)",parent: "mrk" },
    { name: "Singulair",     parent: "mrk" },
    { name: "Zocor",         parent: "mrk" },
    { name: "Coppertone",    parent: "mrk" },
    { name: "Claritin",      parent: "mrk" },
    // Sanofi
    { name: "Lantus",        parent: "snf" },
    { name: "Plavix",        parent: "snf" },
    { name: "Allegra",       parent: "snf" },
    { name: "Dupixent",      parent: "snf" },
    // AstraZeneca
    { name: "Crestor",       parent: "azn" },
    { name: "Nexium",        parent: "azn" },
    { name: "Symbicort",     parent: "azn" },
    { name: "Vaxzevria (COVID vax)", parent: "azn" },
    // GSK
    { name: "Advair",        parent: "gsk" },
    { name: "Augmentin",     parent: "gsk" },
    { name: "Tums",          parent: "gsk" },
    { name: "Sensodyne",     parent: "gsk" },
    { name: "Aquafresh",     parent: "gsk" },
    { name: "Nicorette",     parent: "gsk" },
    // AbbVie
    { name: "Humira",        parent: "abv" },
    { name: "Botox",         parent: "abv" },
    { name: "Juvederm",      parent: "abv" },
    { name: "Restasis",      parent: "abv" },
    // Bayer / Monsanto
    { name: "Aspirin",       parent: "bay" },
    { name: "Aleve",         parent: "bay" },
    { name: "Claritin (intl.)", parent: "bay" },
    { name: "Yaz",           parent: "bay" },
    { name: "Roundup (Monsanto)", parent: "bay" },
    { name: "Dekalb seeds",  parent: "bay" }
  ];

  const midEl     = root.querySelector(".rp-mid");
  const svgEl     = root.querySelector(".rp-svg");
  const linesEl   = root.querySelector(".rp-lines");
  const detailsEl = root.querySelector(".rp-details");
  const SVG_NS    = "http://www.w3.org/2000/svg";

  PRODUCTS.forEach((p, i) => {
    const card = document.createElement("button");
    card.type = "button";
    card.className = "rp-prod";
    card.dataset.idx = String(i);
    card.dataset.parent = p.parent;
    card.textContent = p.name;
    midEl.appendChild(card);
  });

  function drawLines() {
    while (linesEl.firstChild) linesEl.removeChild(linesEl.firstChild);
    const rr = root.getBoundingClientRect();
    if (rr.width === 0) return;
    svgEl.setAttribute("viewBox", "0 0 " + rr.width + " " + rr.height);
    const prods = root.querySelectorAll(".rp-prod");
    prods.forEach((card) => {
      const pid = card.dataset.parent;
      const p = root.querySelector('.rp-parent[data-parent="' + pid + '"]');
      if (!p) return;
      const pr = p.getBoundingClientRect();
      const cr = card.getBoundingClientRect();
      const x1 = (pr.left + pr.width / 2) - rr.left;
      const y1 = pr.bottom - rr.top;
      const x2 = (cr.left + cr.width / 2) - rr.left;
      const y2 = cr.top - rr.top;
      const line = document.createElementNS(SVG_NS, "line");
      line.setAttribute("x1", x1.toFixed(1));
      line.setAttribute("y1", y1.toFixed(1));
      line.setAttribute("x2", x2.toFixed(1));
      line.setAttribute("y2", y2.toFixed(1));
      line.setAttribute("stroke", PARENTS[pid].color);
      line.setAttribute("class", "rp-line");
      line.dataset.parent = pid;
      line.dataset.idx    = card.dataset.idx;
      linesEl.appendChild(line);
    });
  }

  let selected = null;
  function showProd(card) {
    const idx = +card.dataset.idx;
    const pr = PRODUCTS[idx];
    const p = PARENTS[pr.parent];
    const sib = PRODUCTS.filter((x, j) => x.parent === pr.parent && j !== idx);
    detailsEl.innerHTML =
      '<div class="rp-d-name">' + pr.name + '</div>' +
      '<div class="rp-d-row"><span>' + t("page.medicine.rp_owned_by", "Owned by") + '</span>' +
        '<span style="color:' + p.color + '">' + p.name + '</span></div>' +
      (sib.length
        ? '<div class="rp-d-sib"><span>' + t("page.medicine.rp_siblings", "Other products under the same owner") + ':</span> '
            + sib.map(s => s.name).join(", ") + '</div>'
        : '');
    detailsEl.classList.add("visible");
    root.querySelectorAll(".rp-line").forEach((l) => {
      l.classList.toggle("active", l.dataset.parent === pr.parent);
    });
    root.querySelectorAll(".rp-parent").forEach((pp) => {
      pp.classList.toggle("active", pp.dataset.parent === pr.parent);
    });
  }
  function clearSelection() {
    if (selected) selected.classList.remove("active");
    selected = null;
    detailsEl.classList.remove("visible");
    root.querySelectorAll(".rp-line").forEach((l) => l.classList.remove("active"));
    root.querySelectorAll(".rp-parent").forEach((p) => p.classList.remove("active"));
    root.querySelectorAll(".rp-prod").forEach((b) => b.classList.remove("highlight"));
  }

  midEl.addEventListener("click", (e) => {
    const card = e.target.closest(".rp-prod");
    if (!card) return;
    if (card === selected) { clearSelection(); return; }
    clearSelection();
    selected = card;
    card.classList.add("active");
    showProd(card);
  });

  root.querySelector(".rp-top").addEventListener("click", (e) => {
    const p = e.target.closest(".rp-parent");
    if (!p) return;
    const pid = p.dataset.parent;
    const allSel = root.querySelectorAll('.rp-parent.active');
    if (allSel.length === 1 && allSel[0] === p) { clearSelection(); return; }
    clearSelection();
    p.classList.add("active");
    root.querySelectorAll('.rp-line[data-parent="' + pid + '"]').forEach((l) => l.classList.add("active"));
    root.querySelectorAll('.rp-prod[data-parent="' + pid + '"]').forEach((b) => b.classList.add("highlight"));
    detailsEl.innerHTML =
      '<div class="rp-d-name" style="color:' + PARENTS[pid].color + '">' + PARENTS[pid].name + '</div>' +
      '<div class="rp-d-sib"><span>' + t("page.medicine.rp_owns", "Owns") + ':</span> '
        + PRODUCTS.filter(p => p.parent === pid).map(p => p.name).join(", ") + '</div>';
    detailsEl.classList.add("visible");
  });

  midEl.addEventListener("mouseover", (e) => {
    if (selected) return;
    const card = e.target.closest(".rp-prod");
    if (!card) return;
    root.querySelectorAll(".rp-line").forEach((l) => {
      l.classList.toggle("hover", l.dataset.idx === card.dataset.idx);
    });
  });
  midEl.addEventListener("mouseout", (e) => {
    if (selected) return;
    if (!e.target.closest(".rp-prod")) return;
    root.querySelectorAll(".rp-line").forEach((l) => l.classList.remove("hover"));
  });

  let revealed = false;
  function reveal() {
    if (revealed) return;
    revealed = true;
    root.classList.add("rp-ready");
    Object.keys(PARENTS).forEach((id, i) => {
      setTimeout(() => {
        root.querySelectorAll('.rp-line[data-parent="' + id + '"]').forEach((l) => l.classList.add("drawn"));
      }, 300 + i * 220);
    });
  }
  function refresh() {
    drawLines();
    if (revealed) {
      root.querySelectorAll(".rp-line").forEach((l) => l.classList.add("drawn"));
    }
  }

  function isActive() { return view.classList.contains("active"); }
  function start() { refresh(); setTimeout(reveal, 300); }
  function stop() {
    clearSelection();
    revealed = false;
    root.classList.remove("rp-ready");
    root.querySelectorAll(".rp-line").forEach((l) => l.classList.remove("drawn"));
  }

  window.addEventListener("resize", () => { if (isActive()) refresh(); });
  window.addEventListener("langchange", () => { if (selected) showProd(selected); });

  if ("MutationObserver" in window) {
    new MutationObserver(() => { isActive() ? start() : stop(); })
      .observe(view, { attributes: true, attributeFilter: ["class"] });
    if (isActive()) start();
  } else {
    start();
  }
})();
