// The Six-Hands-on-Ninety-Percent Pyramid (Media page).
//
// Top: the handful of conglomerates that own ~90% of what the average
// American sees, reads, or hears. Middle: brands the reader recognizes —
// "competing" news networks, film studios, streaming services, magazines,
// papers. Click any outlet to see who owns it.
//
// Color-codes the SVG lines by conglomerate so the visual is readable
// when all the lines are drawn — each outlet has exactly one parent.

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

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

  // 6 parent conglomerates with their HQ-coded colors for the lines.
  const PARENTS = {
    cmcst: { name: "Comcast / NBCUniversal", color: "#7c3aed" },
    dis:   { name: "Disney",                 color: "#3b82f6" },
    wbd:   { name: "Warner Bros. Discovery", color: "#06b6d4" },
    para:  { name: "Paramount Global",       color: "#10b981" },
    fox:   { name: "Fox + News Corp",        color: "#f59e0b" },
    sony:  { name: "Sony Pictures",          color: "#ef4444" }
  };

  // ~90 outlets people think of as independent voices.
  const OUTLETS = [
    // Comcast / NBCUniversal (18)
    { name: "NBC News",                parent: "cmcst" },
    { name: "MSNBC",                   parent: "cmcst" },
    { name: "CNBC",                    parent: "cmcst" },
    { name: "USA Network",             parent: "cmcst" },
    { name: "Bravo",                   parent: "cmcst" },
    { name: "E!",                      parent: "cmcst" },
    { name: "Syfy",                    parent: "cmcst" },
    { name: "Oxygen",                  parent: "cmcst" },
    { name: "Golf Channel",            parent: "cmcst" },
    { name: "NBC Sports",              parent: "cmcst" },
    { name: "Telemundo",               parent: "cmcst" },
    { name: "Universal Pictures",      parent: "cmcst" },
    { name: "Focus Features",          parent: "cmcst" },
    { name: "DreamWorks Animation",    parent: "cmcst" },
    { name: "Peacock",                 parent: "cmcst" },
    { name: "Xfinity",                 parent: "cmcst" },
    { name: "Sky News (UK)",           parent: "cmcst" },
    { name: "Sky Sports (UK)",         parent: "cmcst" },
    // Disney (17)
    { name: "ABC",                     parent: "dis"   },
    { name: "ABC News",                parent: "dis"   },
    { name: "ESPN",                    parent: "dis"   },
    { name: "ESPN+",                   parent: "dis"   },
    { name: "Hulu",                    parent: "dis"   },
    { name: "Disney+",                 parent: "dis"   },
    { name: "Disney Channel",          parent: "dis"   },
    { name: "Disney Junior",           parent: "dis"   },
    { name: "Freeform",                parent: "dis"   },
    { name: "National Geographic",     parent: "dis"   },
    { name: "Marvel Studios",          parent: "dis"   },
    { name: "Pixar",                   parent: "dis"   },
    { name: "Lucasfilm",               parent: "dis"   },
    { name: "20th Century Studios",    parent: "dis"   },
    { name: "Searchlight Pictures",    parent: "dis"   },
    { name: "FX",                      parent: "dis"   },
    { name: "A&E (50%)",               parent: "dis"   },
    // Warner Bros. Discovery (19)
    { name: "CNN",                     parent: "wbd"   },
    { name: "HBO / Max",               parent: "wbd"   },
    { name: "Discovery Channel",       parent: "wbd"   },
    { name: "Investigation Discovery", parent: "wbd"   },
    { name: "Travel Channel",          parent: "wbd"   },
    { name: "Animal Planet",           parent: "wbd"   },
    { name: "Science Channel",         parent: "wbd"   },
    { name: "Magnolia Network",        parent: "wbd"   },
    { name: "Food Network",            parent: "wbd"   },
    { name: "HGTV",                    parent: "wbd"   },
    { name: "Warner Bros. Pictures",   parent: "wbd"   },
    { name: "New Line Cinema",         parent: "wbd"   },
    { name: "Castle Rock",             parent: "wbd"   },
    { name: "Cartoon Network",         parent: "wbd"   },
    { name: "Adult Swim",              parent: "wbd"   },
    { name: "TNT",                     parent: "wbd"   },
    { name: "TBS",                     parent: "wbd"   },
    { name: "DC Comics",               parent: "wbd"   },
    { name: "OWN",                     parent: "wbd"   },
    // Paramount (16)
    { name: "CBS",                     parent: "para"  },
    { name: "CBS News",                parent: "para"  },
    { name: "CBS Sports",              parent: "para"  },
    { name: "MTV",                     parent: "para"  },
    { name: "Nickelodeon",             parent: "para"  },
    { name: "Comedy Central",          parent: "para"  },
    { name: "Showtime",                parent: "para"  },
    { name: "BET",                     parent: "para"  },
    { name: "VH1",                     parent: "para"  },
    { name: "CMT",                     parent: "para"  },
    { name: "TV Land",                 parent: "para"  },
    { name: "Logo",                    parent: "para"  },
    { name: "Smithsonian Channel",     parent: "para"  },
    { name: "Paramount Pictures",      parent: "para"  },
    { name: "Paramount+",              parent: "para"  },
    { name: "Pluto TV",                parent: "para"  },
    { name: "Channel 5 (UK)",          parent: "para"  },
    // Fox + News Corp (15)
    { name: "Fox News",                parent: "fox"   },
    { name: "Fox Broadcasting",        parent: "fox"   },
    { name: "Fox Business",            parent: "fox"   },
    { name: "Fox Sports (FS1)",        parent: "fox"   },
    { name: "Tubi",                    parent: "fox"   },
    { name: "Wall Street Journal",     parent: "fox"   },
    { name: "Barron's",                parent: "fox"   },
    { name: "MarketWatch",             parent: "fox"   },
    { name: "NY Post",                 parent: "fox"   },
    { name: "The Times (UK)",          parent: "fox"   },
    { name: "The Sun (UK)",            parent: "fox"   },
    { name: "The Australian",          parent: "fox"   },
    { name: "Daily Telegraph (AU)",    parent: "fox"   },
    { name: "Foxtel (AU)",             parent: "fox"   },
    { name: "HarperCollins",           parent: "fox"   },
    // Sony Pictures (10)
    { name: "Sony Pictures",           parent: "sony"  },
    { name: "Columbia Pictures",       parent: "sony"  },
    { name: "TriStar Pictures",        parent: "sony"  },
    { name: "Screen Gems",             parent: "sony"  },
    { name: "Sony Pictures Classics",  parent: "sony"  },
    { name: "Sony Pictures Animation", parent: "sony"  },
    { name: "Sony Pictures Television",parent: "sony"  },
    { name: "AXN",                     parent: "sony"  },
    { name: "Crunchyroll",             parent: "sony"  },
    { name: "Funimation",              parent: "sony"  }
  ];

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

  OUTLETS.forEach((o, i) => {
    const card = document.createElement("button");
    card.type = "button";
    card.className = "mp-outlet";
    card.dataset.idx = String(i);
    card.dataset.parent = o.parent;
    card.textContent = o.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 parents = root.querySelectorAll(".mp-parent");
    const outlets = root.querySelectorAll(".mp-outlet");
    outlets.forEach((card) => {
      const pid = card.dataset.parent;
      const p = root.querySelector('.mp-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", "mp-line");
      line.dataset.parent = pid;
      line.dataset.idx    = card.dataset.idx;
      linesEl.appendChild(line);
    });
  }

  let selected = null;
  function showOutlet(card) {
    const idx = +card.dataset.idx;
    const outlet = OUTLETS[idx];
    const parent = PARENTS[outlet.parent];
    const sib = OUTLETS.filter((o, j) => o.parent === outlet.parent && j !== idx);
    detailsEl.innerHTML =
      '<div class="mp-d-name">' + outlet.name + '</div>' +
      '<div class="mp-d-row"><span>' + t("page.media.mp_owned_by", "Owned by") + '</span>' +
        '<span style="color:' + parent.color + '">' + parent.name + '</span></div>' +
      (sib.length
        ? '<div class="mp-d-sib"><span>' + t("page.media.mp_siblings", "Siblings under the same owner") + ':</span> '
            + sib.map(s => s.name).join(", ") + '</div>'
        : '');
    detailsEl.classList.add("visible");
    root.querySelectorAll(".mp-line").forEach((l) => {
      l.classList.toggle("active", l.dataset.parent === outlet.parent);
    });
    root.querySelectorAll(".mp-parent").forEach((p) => {
      p.classList.toggle("active", p.dataset.parent === outlet.parent);
    });
  }
  function clearSelection() {
    if (selected) selected.classList.remove("active");
    selected = null;
    detailsEl.classList.remove("visible");
    root.querySelectorAll(".mp-line").forEach((l) => l.classList.remove("active"));
    root.querySelectorAll(".mp-parent").forEach((p) => p.classList.remove("active"));
    root.querySelectorAll(".mp-outlet").forEach((o) => o.classList.remove("highlight"));
  }

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

  // Click a parent to see all its outlets glow.
  root.querySelector(".mp-top").addEventListener("click", (e) => {
    const p = e.target.closest(".mp-parent");
    if (!p) return;
    const pid = p.dataset.parent;
    const allSel = root.querySelectorAll('.mp-parent.active');
    if (allSel.length === 1 && allSel[0] === p) {
      clearSelection();
      return;
    }
    clearSelection();
    p.classList.add("active");
    root.querySelectorAll('.mp-line[data-parent="' + pid + '"]').forEach((l) => l.classList.add("active"));
    root.querySelectorAll('.mp-outlet[data-parent="' + pid + '"]').forEach((o) => o.classList.add("highlight"));
    detailsEl.innerHTML =
      '<div class="mp-d-name" style="color:' + PARENTS[pid].color + '">' + PARENTS[pid].name + '</div>' +
      '<div class="mp-d-sib"><span>' + t("page.media.mp_owns", "Owns") + ':</span> '
        + OUTLETS.filter(o => o.parent === pid).map(o => o.name).join(", ") + '</div>';
    detailsEl.classList.add("visible");
  });

  // Hover preview on desktop.
  midEl.addEventListener("mouseover", (e) => {
    if (selected) return;
    const card = e.target.closest(".mp-outlet");
    if (!card) return;
    root.querySelectorAll(".mp-line").forEach((l) => {
      l.classList.toggle("hover", l.dataset.idx === card.dataset.idx);
    });
  });
  midEl.addEventListener("mouseout", (e) => {
    if (selected) return;
    if (!e.target.closest(".mp-outlet")) return;
    root.querySelectorAll(".mp-line").forEach((l) => l.classList.remove("hover"));
  });

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

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

  window.addEventListener("resize", () => { if (isActive()) refresh(); });
  document.addEventListener("i18n:change", () => {
    if (selected) showOutlet(selected);
  });

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