// instagram.jsx — Live Instagram feed via Behold

const BEHOLD_URL = "https://feeds.behold.so/NqCODI1R1AqrDU5roLJv";

function InstagramFeed() {
  const [posts, setPosts] = React.useState([]);
  const [status, setStatus] = React.useState("loading"); // "loading" | "ok" | "error"

  React.useEffect(() => {
    fetch(BEHOLD_URL)
      .then((r) => {
        if (!r.ok) throw new Error(r.status);
        return r.json();
      })
      .then((data) => {
        const items = Array.isArray(data) ? data : data.posts ?? [];
        setPosts(items.slice(0, 12));
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }, []);

  const ref      = React.useRef(null);
  const pausedRef = React.useRef(false);
  const posRef    = React.useRef(0);
  const halfRef   = React.useRef(0);

  React.useEffect(() => {
    if (status !== "ok") return;
    const track = ref.current;
    if (!track) return;

    posRef.current  = 0;
    halfRef.current = 0;
    let rafId, lastTs = null;

    const loop = (ts) => {
      if (!halfRef.current && track.children[posts.length]) {
        halfRef.current = track.children[posts.length].offsetLeft;
      }
      if (halfRef.current && lastTs !== null && !pausedRef.current) {
        posRef.current += 40 * (ts - lastTs) / 1000;
        if (posRef.current >= halfRef.current) posRef.current -= halfRef.current;
        track.style.transform = `translateX(-${posRef.current}px)`;
      }
      lastTs = ts;
      rafId = requestAnimationFrame(loop);
    };

    let touchStartX = 0, touchStartY = 0, touchStartPos = 0, isHoriz = null;

    const onTouchStart = (e) => {
      pausedRef.current = true;
      touchStartX = e.touches[0].clientX;
      touchStartY = e.touches[0].clientY;
      touchStartPos = posRef.current;
      isHoriz = null;
    };
    const onTouchMove = (e) => {
      if (!halfRef.current) return;
      const dx = e.touches[0].clientX - touchStartX;
      const dy = e.touches[0].clientY - touchStartY;
      if (isHoriz === null) isHoriz = Math.abs(dx) > Math.abs(dy);
      if (!isHoriz) return;
      e.preventDefault();
      posRef.current = ((touchStartPos - dx) % halfRef.current + halfRef.current) % halfRef.current;
      track.style.transform = `translateX(-${posRef.current}px)`;
    };
    const onTouchEnd = () => { setTimeout(() => { pausedRef.current = false; }, 1500); };

    track.addEventListener("touchstart", onTouchStart, { passive: true });
    track.addEventListener("touchmove",  onTouchMove,  { passive: false });
    track.addEventListener("touchend",   onTouchEnd,   { passive: true });
    rafId = requestAnimationFrame(loop);

    return () => {
      cancelAnimationFrame(rafId);
      track.removeEventListener("touchstart", onTouchStart);
      track.removeEventListener("touchmove",  onTouchMove);
      track.removeEventListener("touchend",   onTouchEnd);
    };
  }, [status]);

  const scrollBy = (dir) => {
    const track = ref.current;
    if (!track || !halfRef.current) return;
    pausedRef.current = true;
    const step = (track.children[0]?.offsetWidth ?? 224) + 14;
    posRef.current = ((posRef.current + dir * step) % halfRef.current + halfRef.current) % halfRef.current;
    track.style.transform = `translateX(-${posRef.current}px)`;
    setTimeout(() => { pausedRef.current = false; }, 2000);
  };

  return (
    <section className="ig-feed">
      <div className="wrap ig-feed__head">
        <div>
          <p className="eyebrow eyebrow--maroon">@wrokrugby</p>
          <h2 className="display display-l" style={{ marginTop: 10 }}>
            Från Instagram.
          </h2>
        </div>
        <div className="ig-feed__head-right">
          <p className="text-muted ig-feed__tag">
            Snapshots från träning, match och livet runt laget.
          </p>
          <div className="ig-feed__arrows">
            <button
              type="button"
              className="ig-feed__arrow"
              onClick={() => scrollBy(-1)}
              aria-label="Föregående"
            >
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                <path d="M13 8H3M7 4L3 8l4 4" stroke="currentColor" strokeWidth="1.75" strokeLinecap="square" />
              </svg>
            </button>
            <button
              type="button"
              className="ig-feed__arrow"
              onClick={() => scrollBy(1)}
              aria-label="Nästa"
            >
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                <path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.75" strokeLinecap="square" />
              </svg>
            </button>
          </div>
        </div>
      </div>

      <div className="ig-feed__track-wrap">
        {status === "loading" && (
          <div className="ig-feed__track">
            {Array.from({ length: 6 }).map((_, i) => (
              <div key={i} className="ig-post ig-post--skeleton" aria-hidden="true">
                <div className="ig-post__img" />
              </div>
            ))}
          </div>
        )}

        {status === "error" && (
          <p className="wrap" style={{ padding: "2rem 0", opacity: 0.5 }}>
            Kunde inte ladda Instagram-flödet just nu.
          </p>
        )}

        {status === "ok" && (
          <div className="ig-feed__track" ref={ref}>
            {[...posts, ...posts].map((p, i) => {
              const imgSrc = p.mediaType === "VIDEO" ? p.thumbnailUrl : p.mediaUrl;
              const caption = p.caption ? p.caption.split("\n")[0].slice(0, 100) : "";
              return (
                <a
                  key={i}
                  href={p.permalink}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="ig-post"
                  aria-label={"Instagram-inlägg: " + caption}
                >
                  <div className="ig-post__img">
                    <img src={imgSrc} alt="" loading="lazy" />
                  </div>
                  {caption && (
                    <div className="ig-post__caption">
                      <span>{caption}</span>
                    </div>
                  )}
                </a>
              );
            })}
          </div>
        )}
      </div>

      <div className="wrap ig-feed__foot">
        <p className="ig-feed__foot-note">
          Det här är de senaste inläggen — allt finns inte här.
        </p>
        <a
          href="https://www.instagram.com/wrokrugby/"
          target="_blank"
          rel="noopener noreferrer"
          className="btn btn--ghost"
        >
          Se mer på @wrokrugby ↗
        </a>
      </div>
    </section>
  );
}

Object.assign(window, { InstagramFeed });
