/** Home page work tile: hover-play video, company icon row, editorial title. */
function kernFindingTitle(title) {
  if (typeof title !== "string") return title;
  const i = title.indexOf("Fi");
  if (i === -1) return title;
  return (
    <React.Fragment>
      {title.slice(0, i)}
      <span className="kern-fi">Fi</span>
      {title.slice(i + 2)}
    </React.Fragment>
  );
}

function HomeWorkTile({ href, company, icon, title, videoUrl, coverUrl, autoplay }) {
  const [active, setActive] = React.useState(!!autoplay);
  const videoRef = React.useRef(null);

  React.useEffect(() => {
    const video = videoRef.current;
    if (!video) return;
    const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (autoplay && !reduceMotion) {
      setActive(true);
      const playPromise = video.play();
      if (playPromise && typeof playPromise.catch === "function") {
        playPromise.catch(() => {});
      }
      return;
    }
    if (active && !reduceMotion) {
      const playPromise = video.play();
      if (playPromise && typeof playPromise.catch === "function") {
        playPromise.catch(() => {});
      }
    } else if (!autoplay) {
      video.pause();
      try {
        video.currentTime = 0;
      } catch (e) {
        /* seeking can throw before metadata loads */
      }
    }
  }, [active, autoplay]);

  return (
    <a
      className="home-tile"
      href={href}
      onMouseEnter={() => setActive(true)}
      onMouseLeave={() => setActive(!!autoplay)}
      onFocus={() => setActive(true)}
      onBlur={() => setActive(!!autoplay)}
    >
      <div className="home-tile__media">
        {coverUrl ? (
          <img className="home-tile__cover" src={coverUrl} alt="" />
        ) : null}
        <video
          ref={videoRef}
          className={coverUrl ? (active || autoplay ? "is-playing" : "") : undefined}
          src={videoUrl}
          muted
          loop
          playsInline
          autoPlay={!!autoplay}
          preload={autoplay ? "auto" : "metadata"}
          aria-hidden="true"
        />
      </div>
      <div className="home-tile__text">
        <p className="home-tile__company">
          <img src={icon} width="30" height="30" alt="" />
          {company}
        </p>
        <h2 className="home-tile__title">{kernFindingTitle(title)}</h2>
      </div>
    </a>
  );
}

Object.assign(window, { HomeWorkTile });
