/**
 * hero.jsx — above-the-fold pitch (H1 with the main local keyword,
 * call + form CTAs, trust bullets, photo slot) and the stats band
 * that backs up the "24h / fast arrival" claims.
 */

function Hero() {
  const { t } = useLang();
  const B = window.BUSINESS;

  return (
    <section className="hero" id="inicio" data-screen-label="Hero">
      <div className="container">
        <div className="hero__text">
          <span className="kicker">{t.hero.kicker}</span>
          <h1>{t.hero.title}</h1>
          <p className="lead">{t.hero.lead}</p>

          <div className="hero__ctas">
            <a className="btn btn--red" href={B.phoneHref}>
              <Icon name="phone" size={18} /> {t.hero.ctaCall}
            </a>
            <a className="btn btn--ghost" href="#contacto">
              {t.hero.ctaForm} <Icon name="arrow" size={18} />
            </a>
          </div>

          <ul className="hero__bullets">
            {t.hero.bullets.map((b) => (
              <li key={b}>
                <Icon name="check" size={17} /> {b}
              </li>
            ))}
          </ul>
        </div>

        <div className="hero__visual">
          <img
            src="images/Doorimage1.jpeg"
            alt="Cerrajero abriendo una puerta en El Campello"
            style={{ width: "100%", borderRadius: "var(--radius)", boxShadow: "var(--shadow)", objectFit: "cover", aspectRatio: "4 / 3.4" }}
          />
          <span className="hero__badge">
            <span className="dot"></span> {t.hero.badge}
          </span>
        </div>
      </div>
    </section>
  );
}

/** Red full-width band with the four key trust numbers. */
function StatsBand() {
  const { t } = useLang();

  return (
    <section className="stats reveal" aria-label="Datos del servicio">
      <div className="container">
        {t.stats.map((s) => (
          <div className="stat" key={s.label}>
            <CountUpValue value={s.value} />
            <div className="stat__label">{s.label}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

/**
 * CountUpValue — if the value looks countable it animates a counter
 * the first time the stats band scrolls into view. Static labels
 * ("24h", "15–30 min") render as-is.
 */
function CountUpValue({ value }) {
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  const [count, setCount] = React.useState(0);

  /* Parse a target number from the value string. Returns null for
     static labels that make no sense to count. */
  const target = React.useMemo(() => {
    /* "+1.500" style → strip + and . to get an integer */
    const m = value.match(/^\+(\d[\d.]*)$/);
    if (m) return { from: 1, to: parseFloat(m[1].replace(/\./g, "")), decimals: 0, prefix: "+" };
    /* "4,9★" style → decimal with trailing char */
    const d = value.match(/^(\d+),(\d+)/);
    if (d) return { from: 0, to: parseFloat(d[1] + "." + d[2]), decimals: 1, suffix: "★" };
    return null;
  }, [value]);

  /* IntersectionObserver: fire once when the band comes into view */
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([entry]) => { if (entry.isIntersecting) { setVisible(true); io.disconnect(); } },
      { threshold: 0.3 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  /* Animate the counter when visible */
  React.useEffect(() => {
    if (!visible || !target) return;
    const duration = 600; // ms
    const start = performance.now();
    const { from, to, decimals } = target;
    let raf;
    function tick(now) {
      const elapsed = now - start;
      const progress = Math.min(elapsed / duration, 1);
      /* ease-out cubic */
      const eased = 1 - Math.pow(1 - progress, 3);
      const current = from + (to - from) * eased;
      setCount(current);
      if (progress < 1) raf = requestAnimationFrame(tick);
    }
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [visible, target]);

  if (!target) return <div className="stat__value" ref={ref}>{value}</div>;

  /* Format the animated number to match the original locale style */
  const formatted = React.useMemo(() => {
    const n = target.decimals > 0
      ? count.toFixed(target.decimals)
      : Math.floor(count).toLocaleString("es-ES");
    return (target.prefix || "") + n + (target.suffix || "");
  }, [count, target]);

  return (
    <div className="stat__value" ref={ref}>
      {visible ? formatted : (target.prefix || "") + target.from + (target.suffix || "")}
    </div>
  );
}

Object.assign(window, { Hero, StatsBand });
