/* ============================================================
   CIEN — router + mount
   ============================================================ */
function useHashRoute(){
  const [route, setRoute] = useState(window.location.hash.replace(/^#\/?/,"") || "");
  useEffect(()=>{
    const on = ()=> setRoute(window.location.hash.replace(/^#\/?/,"") || "");
    window.addEventListener("hashchange", on);
    return ()=> window.removeEventListener("hashchange", on);
  },[]);
  return route;
}

function useReveal(route){
  useEffect(()=>{
    const targets = [...document.querySelectorAll("main section, .chart-rule-wrap")];
    const vh = window.innerHeight || 800;
    const io = new IntersectionObserver((ents)=>{
      ents.forEach(e=>{ if(e.isIntersecting){ e.target.classList.add("is-in"); io.unobserve(e.target); } });
    }, { rootMargin: "0px 0px -10% 0px", threshold: 0.04 });
    // Solo ocultamos lo que está por debajo del fold; lo visible queda intacto.
    targets.forEach(el=>{
      if(el.getBoundingClientRect().top > vh * 0.82){
        el.classList.add("reveal");
        io.observe(el);
      }
    });
    return ()=> io.disconnect();
  }, [route]);
}

function useParallax(route){
  useEffect(()=>{
    let raf = 0;
    const apply = ()=>{
      const y = window.scrollY || 0;
      // Skyline de fondo: una onda recorre las barras según el scroll.
      const bg = document.querySelectorAll(".data-backdrop .b");
      bg.forEach((b,i)=>{
        const w = 1 + Math.sin(y*0.006 + i*0.45) * 0.16;
        b.style.setProperty("--w", w.toFixed(3));
      });
    };
    const onScroll = ()=>{ cancelAnimationFrame(raf); raf = requestAnimationFrame(apply); };
    window.addEventListener("scroll", onScroll, { passive:true });
    apply();
    return ()=>{ window.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, [route]);
}

function App(){
  const route = useHashRoute();
  const [base, a, b] = route.split("/");
  useReveal(route);
  useParallax(route);

  let page;
  switch(base){
    case "": page = <Home/>; break;
    case "institucional": page = <Institucional/>; break;
    case "informes": page = <Informes/>; break;
    case "informe": page = <InformeDetalle slug={a}/>; break;
    case "actividades": page = <Actividades/>; break;
    case "actividad": page = <ActividadDetalle slug={a}/>; break;
    case "medios": page = <Medios/>; break;
    default: page = <NotFound/>;
  }

  return (
    <React.Fragment>
      <DataBackdrop/>
      <Header route={route}/>
      {React.cloneElement(page, { key: route })}
      <BarChartRule/>
      <Footer/>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
