// Celtis — qué es. Primer screen: definición editorial.
// Segundo screen: sticky scroll-stage. Logo SVG se dibuja progresivamente con el scroll
// (stroke-dashoffset 0→1) mientras los 3 pilares (Entender / Diseñar / Implementar)
// se intercambian a la izquierda según el bucket actual de scroll.
function Celtis() {
  const [lang] = window.useLang();
  const isEn = lang === "en";

  const pilares = isEn
    ? [
        { k: "Understand", d: "We study how your operation actually works." },
        { k: "Design",     d: "We craft the tool you need to make your time count." },
        { k: "Implement",  d: "We ship it, then iterate and improve over time." },
      ]
    : [
        { k: "Entender",    d: "Estudiamos tu flujo de trabajo. Mapeamos cada proceso. Detectamos dónde actuar." },
        { k: "Diseñar",     d: "Creamos la herramienta que necesites para eficientizar tu tiempo." },
        { k: "Implementar", d: "Implementamos la herramienta, iteramos y mejoramos con el tiempo." },
      ];

  const stageRef = React.useRef(null);
  const rowRefs = React.useRef([]);
  const [progress, setProgress] = React.useState(0);
  const [seenMap, setSeenMap] = React.useState({});

  // Mobile sticky scroll: progresa por buckets para swap + logo draw
  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        const el = stageRef.current;
        if (el) {
          const rect = el.getBoundingClientRect();
          const total = Math.max(1, rect.height - window.innerHeight);
          const scrolled = -rect.top;
          const p = Math.max(0, Math.min(1, scrolled / total));
          setProgress(p);
        }
        raf = 0;
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  // Desktop: IntersectionObserver por fila — cada pilar se highlightea cuando
  // entra al viewport. Una vez seen, se queda highlighted (cumulativo).
  React.useEffect(() => {
    const observers = rowRefs.current.map((el, i) => {
      if (!el) return null;
      const io = new IntersectionObserver(
        ([entry]) => {
          if (entry.isIntersecting) {
            setSeenMap((prev) => (prev[i] ? prev : { ...prev, [i]: true }));
          }
        },
        { threshold: 0.45, rootMargin: "0px 0px -10% 0px" }
      );
      io.observe(el);
      return io;
    });
    return () => observers.forEach((io) => io && io.disconnect());
  }, [pilares.length]);

  // 4 buckets para mobile sticky: vacío → Entender → Diseñar → Implementar.
  const buckets = pilares.length + 1;
  const step = Math.min(pilares.length - 1, Math.floor(progress * buckets) - 1);
  const drawEnd = (buckets - 1) / buckets;
  const draw = Math.max(0, Math.min(1, progress / drawEnd));

  return (
    <section className="ce" id="celtis">
      <div className="ce-screen">
        <div className="container">
          <div className="ce-body">
            <Reveal as="p" className="ce-lede rv-up" delay={0}>
              {isEn ? (
                <><em>Celtis</em> is the genus of the tala — a native Argentine tree whose wood was used to make tools.</>
              ) : (
                <><em>Celtis</em> es el género del tala — un árbol nativo argentino cuya madera servía para crear herramientas.</>
              )}
            </Reveal>
            <Reveal as="p" className="ce-lede rv-up" delay={120}>
              {isEn ? (
                <>That's what we do. We build <span className="title-hl">tools</span> to make your work flow.</>
              ) : (
                <>Eso hacemos. Creamos <span className="title-hl">herramientas</span> para optimizar tu trabajo.</>
              )}
            </Reveal>
          </div>
        </div>
      </div>

      <div className="ce-screen-pillars" ref={stageRef}>
        <div className="ce-pillars-sticky">
          <div className="container">
            <div className="ce-pillars-deck">
              <div className="ce-pillars-text">
                {pilares.map((p, i) => (
                  <article
                    key={p.k}
                    ref={(el) => (rowRefs.current[i] = el)}
                    className={
                      "ce-pillar-step" +
                      (seenMap[i] ? " is-seen" : "") +
                      (i === step ? " is-on" : i < step ? " is-past" : "")
                    }
                  >
                    <div className="ce-pillar-side">
                      <h3 className="ce-pillar-title"><span className="ce-pillar-title-text">{p.k}</span></h3>
                    </div>
                    <div className="ce-pillar-card">
                      <p className="ce-pillar-desc">{p.d}</p>
                    </div>
                  </article>
                ))}
              </div>
              <div className="ce-pillars-logo" aria-hidden="true">
                <svg viewBox="0 0 392 310" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">
                  <path
                    d="M227.89 2.5L336.475 105.573L371.816 139.111C376.536 143.59 381.48 148.166 386.203 152.703L317.947 152.733C299.275 152.733 280.249 152.935 261.666 152.704L255.99 152.633L259.77 156.868C264.02 161.631 268.348 166.953 272.556 171.945L295.491 199.158L358.447 273.849C367.356 284.416 376.405 295.379 385.462 305.997C381.538 305.074 377.528 304.063 373.717 303.157H373.716L340.916 295.38C313.839 288.962 289.078 283.302 262.666 275.018C186.188 250.966 114.958 213.917 52.4492 165.685C35.4035 152.471 19.0114 138.517 3.32129 123.87C6.46027 120.077 10.1275 115.167 12.8398 111.734L34.7217 84.041L99.1465 2.5H227.89Z"
                    fill="var(--celtis-orange)"
                    fillOpacity={draw >= 1 ? 1 : 0}
                    stroke="var(--celtis-orange)"
                    strokeWidth="2.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    pathLength="1"
                    strokeDasharray="1"
                    strokeDashoffset={1 - draw}
                    vectorEffect="non-scaling-stroke"
                    style={{ transition: "fill-opacity .55s var(--ease-out)" }}
                  />
                </svg>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.Celtis = Celtis;
