/* ui.jsx — shared helpers & primitives for RS Vial */
const { useState, useEffect, useRef, useCallback } = React;

/* Reveal-on-scroll wrapper */
function Reveal({ children, as = "div", delay = 0, className = "", style = {}, ...rest }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (es) => es.forEach((e) => { if (e.isIntersecting) { setShown(true); io.disconnect(); } }),
      { threshold: 0.14, rootMargin: "0px 0px -8% 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className={`reveal ${shown ? "in" : ""} ${className}`}
      style={{ transitionDelay: `${delay}ms`, ...style }} {...rest}>
      {children}
    </Tag>
  );
}

/* Small arrow glyph */
function Arrow({ size = 16 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path d="M5 12h13M12 5l7 7-7 7" stroke="currentColor" strokeWidth="2.4" strokeLinecap="square" />
    </svg>
  );
}

/* Section header block (kicker + title) */
function SecHead({ num, kicker, title, intro, onDark = false, align = "left", max = 640 }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === "center" ? max : "none", marginInline: align === "center" ? "auto" : 0 }}>
      <span className={`kicker ${onDark ? "on-dark" : ""}`}>{num ? num + " · " : ""}{kicker}</span>
      <h2 className="display" style={{
        fontSize: "clamp(2rem,4.6vw,3.6rem)", marginTop: 18,
        color: onDark ? "var(--on-dark)" : "var(--ink)", maxWidth: max,
        marginInline: align === "center" ? "auto" : 0,
      }}>{title}</h2>
      {intro && (
        <p style={{
          marginTop: 18, fontSize: "1.075rem", lineHeight: 1.6, maxWidth: max,
          marginInline: align === "center" ? "auto" : 0,
          color: onDark ? "var(--on-dark-2)" : "var(--ink-2)",
        }}>{intro}</p>
      )}
    </div>
  );
}

/* Logo — real image, picks light/dark version by background */
function Logo({ name = "RS CONSTRUCTORA", onDark = false, size = 1 }) {
  return (
    <a href="#top" onClick={(e) => { e.preventDefault(); scrollToId("top"); }}
      aria-label={name} style={{ display: "inline-flex", alignItems: "center", lineHeight: 0 }}>
      <img src={onDark ? "assets/logo-light.png" : "assets/logo-dark.png"} alt={name}
        style={{ height: `${52 * size}px`, width: "auto", display: "block" }} />
    </a>
  );
}

Object.assign(window, { Reveal, Arrow, SecHead, Logo, scrollToId });

/* Safe smooth scroll to a section id (avoids scrollIntoView) */
function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const top = el.getBoundingClientRect().top + window.scrollY - 64;
  window.scrollTo({ top, behavior: "smooth" });
}
