// The Food page — The Illusion of Choice Pyramid.
//
// 10 mega-corporations own the brands behind almost everything on the
// supermarket shelves: cereal aisle, drink aisle, snack aisle, dairy, frozen.
// Nestlé alone owns 2,000+ brands worldwide. Click a brand to see its
// parent and siblings; click a parent to see everything it owns.

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

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

  const PARENTS = {
    nestle: { name: "Nestlé",             color: "#0288d1" },
    coke:   { name: "Coca-Cola",          color: "#ef4444" },
    pepsi:  { name: "PepsiCo",            color: "#1d4ed8" },
    mond:   { name: "Mondelez",           color: "#a855f7" },
    unil:   { name: "Unilever",           color: "#0d9488" },
    mars:   { name: "Mars",               color: "#dc2626" },
    gmills: { name: "General Mills",      color: "#f59e0b" },
    kellg:  { name: "Kellogg's / Kellanova", color: "#dc7633" },
    danone: { name: "Danone",             color: "#10b981" },
    abf:    { name: "Associated British Foods", color: "#6366f1" }
  };

  const BRANDS = [
    // Nestlé
    { name: "KitKat",          parent: "nestle" },
    { name: "Nescafé",         parent: "nestle" },
    { name: "Nespresso",       parent: "nestle" },
    { name: "Maggi",           parent: "nestle" },
    { name: "Perrier",         parent: "nestle" },
    { name: "San Pellegrino",  parent: "nestle" },
    { name: "Häagen-Dazs (intl.)", parent: "nestle" },
    { name: "Stouffer's",      parent: "nestle" },
    { name: "Gerber",          parent: "nestle" },
    { name: "Purina",          parent: "nestle" },
    // Coca-Cola
    { name: "Coca-Cola",       parent: "coke"   },
    { name: "Sprite",          parent: "coke"   },
    { name: "Fanta",           parent: "coke"   },
    { name: "Minute Maid",     parent: "coke"   },
    { name: "Dasani",          parent: "coke"   },
    { name: "Smartwater",      parent: "coke"   },
    { name: "Vitaminwater",    parent: "coke"   },
    { name: "Powerade",        parent: "coke"   },
    { name: "Topo Chico",      parent: "coke"   },
    { name: "Costa Coffee",    parent: "coke"   },
    { name: "Innocent",        parent: "coke"   },
    // PepsiCo
    { name: "Pepsi",           parent: "pepsi"  },
    { name: "Mountain Dew",    parent: "pepsi"  },
    { name: "Lay's",           parent: "pepsi"  },
    { name: "Doritos",         parent: "pepsi"  },
    { name: "Cheetos",         parent: "pepsi"  },
    { name: "Quaker Oats",     parent: "pepsi"  },
    { name: "Gatorade",        parent: "pepsi"  },
    { name: "7Up",             parent: "pepsi"  },
    { name: "Aquafina",        parent: "pepsi"  },
    { name: "Tropicana",       parent: "pepsi"  },
    // Mondelez
    { name: "Oreo",            parent: "mond"   },
    { name: "Cadbury",         parent: "mond"   },
    { name: "Toblerone",       parent: "mond"   },
    { name: "Ritz",            parent: "mond"   },
    { name: "Trident",         parent: "mond"   },
    { name: "Sour Patch Kids", parent: "mond"   },
    { name: "Halls",           parent: "mond"   },
    // Unilever
    { name: "Ben & Jerry's",   parent: "unil"   },
    { name: "Magnum",          parent: "unil"   },
    { name: "Hellmann's",      parent: "unil"   },
    { name: "Knorr",           parent: "unil"   },
    { name: "Lipton",          parent: "unil"   },
    { name: "Marmite",         parent: "unil"   },
    { name: "Dove",            parent: "unil"   },
    { name: "Axe",             parent: "unil"   },
    // Mars
    { name: "M&M's",           parent: "mars"   },
    { name: "Snickers",        parent: "mars"   },
    { name: "Twix",            parent: "mars"   },
    { name: "Milky Way",       parent: "mars"   },
    { name: "Skittles",        parent: "mars"   },
    { name: "Uncle Ben's",     parent: "mars"   },
    { name: "Pedigree",        parent: "mars"   },
    { name: "Whiskas",         parent: "mars"   },
    // General Mills
    { name: "Cheerios",        parent: "gmills" },
    { name: "Häagen-Dazs (US)",parent: "gmills" },
    { name: "Pillsbury",       parent: "gmills" },
    { name: "Betty Crocker",   parent: "gmills" },
    { name: "Yoplait",         parent: "gmills" },
    { name: "Old El Paso",     parent: "gmills" },
    { name: "Nature Valley",   parent: "gmills" },
    // Kellogg's
    { name: "Frosted Flakes",  parent: "kellg"  },
    { name: "Corn Flakes",     parent: "kellg"  },
    { name: "Pringles",        parent: "kellg"  },
    { name: "Pop-Tarts",       parent: "kellg"  },
    { name: "Eggo",            parent: "kellg"  },
    { name: "Special K",       parent: "kellg"  },
    // Danone
    { name: "Activia",         parent: "danone" },
    { name: "Evian",           parent: "danone" },
    { name: "Volvic",          parent: "danone" },
    { name: "Dannon",          parent: "danone" },
    { name: "Alpro",           parent: "danone" },
    // ABF
    { name: "Twinings",        parent: "abf"    },
    { name: "Ovaltine",        parent: "abf"    },
    { name: "Patak's",         parent: "abf"    },
    { name: "Mazola",          parent: "abf"    }
  ];

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

  BRANDS.forEach((b, i) => {
    const card = document.createElement("button");
    card.type = "button";
    card.className = "fp-brand";
    card.dataset.idx = String(i);
    card.dataset.parent = b.parent;
    card.textContent = b.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 brands = root.querySelectorAll(".fp-brand");
    brands.forEach((card) => {
      const pid = card.dataset.parent;
      const p = root.querySelector('.fp-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", "fp-line");
      line.dataset.parent = pid;
      line.dataset.idx    = card.dataset.idx;
      linesEl.appendChild(line);
    });
  }

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

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

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

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

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

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

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