const values = [0.35, 0.50, 0.68, 0.82]; // A, B, C, D

const colorScale = v => {
  if (v < 0.5) {
    const t = v / 0.5;
    const r = Math.round(139 + (245-139)*t);
    const g = Math.round(195 + (158-195)*t);
    const b = Math.round( 74 + ( 11- 74)*t);
    return `rgb(${r},${g},${b})`;
  } else {
    const t = (v-0.5)/0.5;
    const r = Math.round(245 + (239-245)*t);
    const g = Math.round(158 + ( 68-158)*t);
    const b = Math.round( 11 + ( 68- 11)*t);
    return `rgb(${r},${g},${b})`;
  }
};

(function buildAndAnimate(){
  const svg   = document.getElementById('hyChart');
  const gBars = document.getElementById('bars');

  // zone utile dans le viewBox
  const chart = { x: 70, y: 50, w: 690, h: 250 };
  const n     = values.length;
  const gap   = 28;
  const bw    = (chart.w - gap*(n+1)) / n;

  // construire les barres (hauteur 0 au départ)
  const rects = values.map((v, i) => {
    const x = chart.x + gap + i*(bw+gap);
    const y = chart.y + chart.h; // baseline
    const r = rect(x, y, bw, 0, 'bar'); // h=0, y=baseline
    r.setAttribute('fill', colorScale(v));
    gBars.appendChild(r);

    // label X
    const tx = text(x + bw/2, chart.y + chart.h + 22, `Baie ${String.fromCharCode(65+i)}`);
    tx.setAttribute('text-anchor', 'middle');
    gBars.appendChild(tx);

    return { el: r, v };
  });

  // animation: de 0 -> valeur cible (transition CSS dans style.css)
  const toH = v => v * chart.h;
  const play = () => {
    rects.forEach(({ el, v }) => {
      const h = toH(v);
      const y = chart.y + (chart.h - h);
      el.setAttribute('y', y);
      el.setAttribute('height', h);
    });
  };

  // lancer l'anim quand le SVG entre dans le viewport
  const io = new IntersectionObserver((entries) => {
    for (const e of entries) if (e.isIntersecting) { play(); io.disconnect(); }
  }, { threshold: 0.25 });
  io.observe(svg);

  // utils SVG
  function rect(x,y,w,h,cls){
    const el = document.createElementNS('http://www.w3.org/2000/svg','rect');
    el.setAttribute('x',x); el.setAttribute('y',y);
    el.setAttribute('width',w); el.setAttribute('height',h);
    if (cls) el.setAttribute('class',cls);
    return el;
  }
  function text(x,y,str){
    const el = document.createElementNS('http://www.w3.org/2000/svg','text');
    el.setAttribute('x',x); el.setAttribute('y',y);
    el.textContent = str;
    return el;
  }
})();
