/* global React */
const { useState, useEffect, useRef } = React;

function TwoTone({ parts, className = "" }) {
  return (
    <h2 className={`h-twotone ${className}`}>
      {parts.map((p, i) => {
        const words = p.text.split(/(\s+)/);
        return words.map((w, j) => {
          if (/^\s+$/.test(w)) return <span key={`s-${i}-${j}`}>{w}</span>;
          return (
            <span key={`w-${i}-${j}`} className={`word ${p.tone}`}>
              {w}
            </span>
          );
        });
      })}
    </h2>
  );
}

function Reveal({ children, className = "", as: Tag = "div" }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            setSeen(true);
            io.disconnect();
          }
        });
      },
      { rootMargin: "0px 0px -10% 0px", threshold: 0 },
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <Tag ref={ref} className={`${seen ? "in-view" : ""} ${className}`}>
      {children}
    </Tag>
  );
}

function LogoBadge({ size = 36 }) {
  return (
    <span className="badge" style={{ width: size, height: size, flexBasis: size }}>
      <img src="/landing/design-system/assets/eoma-logo.svg" alt="" style={{ width: size * 0.5 }} />
    </span>
  );
}
function Logomark({ width = 24 }) {
  return (
    <img
      className="mark"
      src="/landing/design-system/assets/eoma-logo.svg"
      alt="eoma"
      style={{ width }}
    />
  );
}

/* count-up hook */
function useCountUp(target, { duration = 1200, decimals = 0, start = 0 } = {}) {
  const [val, setVal] = useState(start);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf,
      t0,
      started = false;
    const tick = (t) => {
      if (!t0) t0 = t;
      const p = Math.min(1, (t - t0) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(start + (target - start) * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting && !started) {
            started = true;
            raf = requestAnimationFrame(tick);
            io.disconnect();
          }
        });
      },
      { threshold: 0.2 },
    );
    io.observe(el);
    return () => {
      cancelAnimationFrame(raf);
      io.disconnect();
    };
  }, [target, duration]);
  return [val.toFixed(decimals), ref];
}

Object.assign(window, { TwoTone, Reveal, LogoBadge, Logomark, useCountUp });
