// The Counterfeit Power Pyramid (Power page).
//
// Top: the three asset managers that hold the largest passive index stakes
// in nearly every major US-listed company — BlackRock, Vanguard, State Street.
// Middle: a grid of well-known corporations that appear to compete in their
// markets but share the same dominant institutional shareholders.
// Bottom: "You" — the consumer at the base of the pyramid.
//
// SVG lines fan from each owner down to every corp. Click a corp to see
// the three combined stakes (drawn from publicly filed 13F numbers, rounded).

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

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

  // Approximate combined-three holdings from public 13F filings (2024).
  // Real numbers, rounded; vary slightly quarter to quarter.
  const CORPS = [
    { name: "Coca-Cola",       vng: 8.6, blk: 7.0, sst: 4.0 },
    { name: "PepsiCo",         vng: 9.1, blk: 7.4, sst: 4.5 },
    { name: "Apple",           vng: 8.7, blk: 6.6, sst: 4.0 },
    { name: "Microsoft",       vng: 9.0, blk: 7.0, sst: 3.9 },
    { name: "Alphabet",        vng: 7.5, blk: 6.4, sst: 3.4 },
    { name: "Meta",            vng: 7.6, blk: 6.5, sst: 3.6 },
    { name: "Pfizer",          vng: 9.3, blk: 7.7, sst: 4.6 },
    { name: "Johnson & Johnson", vng: 9.5, blk: 7.5, sst: 4.7 },
    { name: "Disney",          vng: 9.0, blk: 6.8, sst: 4.1 },
    { name: "Comcast",         vng: 9.2, blk: 7.1, sst: 4.3 },
    { name: "JPMorgan",        vng: 8.9, blk: 6.9, sst: 4.2 },
    { name: "ExxonMobil",      vng: 9.4, blk: 7.0, sst: 6.2 }
  ];

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

  // Build the corp cards.
  CORPS.forEach((c, i) => {
    const card = document.createElement("button");
    card.type = "button";
    card.className = "pp-corp";
    card.dataset.idx = String(i);
    card.textContent = c.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 owners = root.querySelectorAll(".pp-owner");
    const corps  = root.querySelectorAll(".pp-corp");
    owners.forEach((top) => {
      const tr = top.getBoundingClientRect();
      const x1 = (tr.left + tr.width / 2) - rr.left;
      const y1 = tr.bottom - rr.top;
      corps.forEach((corp) => {
        const cr = corp.getBoundingClientRect();
        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("class", "pp-line");
        line.dataset.owner = top.dataset.owner;
        line.dataset.corp  = corp.dataset.idx;
        linesEl.appendChild(line);
      });
    });
  }

  let selected = null;
  function showCorp(card) {
    const corp = CORPS[+card.dataset.idx];
    const total = (corp.vng + corp.blk + corp.sst).toFixed(1);
    detailsEl.innerHTML =
      '<div class="pp-d-name">' + corp.name + '</div>' +
      '<div class="pp-d-row"><span>Vanguard</span><span>' + corp.vng.toFixed(1) + '%</span></div>' +
      '<div class="pp-d-row"><span>BlackRock</span><span>' + corp.blk.toFixed(1) + '%</span></div>' +
      '<div class="pp-d-row"><span>State Street</span><span>' + corp.sst.toFixed(1) + '%</span></div>' +
      '<div class="pp-d-total"><span>' + t("page.power.pp_combined", "Combined") + '</span><span>' + total + '%</span></div>';
    detailsEl.classList.add("visible");
    root.querySelectorAll(".pp-line").forEach((l) => {
      l.classList.toggle("active", l.dataset.corp === card.dataset.idx);
    });
  }
  function clearSelection() {
    if (selected) selected.classList.remove("active");
    selected = null;
    detailsEl.classList.remove("visible");
    root.querySelectorAll(".pp-line").forEach((l) => l.classList.remove("active"));
  }

  midEl.addEventListener("click", (e) => {
    const card = e.target.closest(".pp-corp");
    if (!card) return;
    if (card === selected) { clearSelection(); return; }
    if (selected) selected.classList.remove("active");
    selected = card;
    card.classList.add("active");
    showCorp(card);
  });

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

  // First-time reveal: fan the lines in one owner at a time.
  let revealed = false;
  function reveal() {
    if (revealed) return;
    revealed = true;
    root.classList.add("pp-ready");
    const owners = ["vng", "blk", "sst"];
    owners.forEach((id, i) => {
      setTimeout(() => {
        root.querySelectorAll('.pp-line[data-owner="' + id + '"]').forEach((l) => l.classList.add("drawn"));
      }, 500 + i * 600);
    });
  }

  function refresh() {
    drawLines();
    // Re-apply 'drawn' state on resize so lines stay visible.
    if (revealed) {
      root.querySelectorAll(".pp-line").forEach((l) => l.classList.add("drawn"));
    }
  }

  // Pause / resume reveal when view becomes active.
  function isActive() { return view.classList.contains("active"); }
  function start() {
    refresh();
    // Slight delay before reveal so layout settles.
    setTimeout(reveal, 350);
  }
  function stop() {
    clearSelection();
    revealed = false;
    root.classList.remove("pp-ready");
    root.querySelectorAll(".pp-line").forEach((l) => l.classList.remove("drawn"));
  }

  window.addEventListener("resize", () => { if (isActive()) refresh(); });
  // i18n changes — re-render the open details panel.
  document.addEventListener("i18n:change", () => {
    if (selected) showCorp(selected);
  });

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