/* ===================================================
   TAG CAROUSEL — random rows, infinite drift L→R
   The component generates lanes; each lane carries a
   shuffled set of tag pills moving at slightly
   different speeds. When a pill exits the right edge
   it loops back to the left.
   =================================================== */

/* Fisher-Yates shuffle — reliable across all browsers */
function shuffleArray(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

function TagCarousel({ tags }) {
  const ref = React.useRef(null);
  const animRef = React.useRef(null);

  React.useEffect(() => {
    if (!tags || !ref.current) return;
    const root = ref.current;
    /* Use fallback to window size if the container hasn't been laid out yet */
    const W = () => root.clientWidth || window.innerWidth || 1200;
    const H = () => root.clientHeight || 600;

    // build lanes (7 rows for taller bleed)
    const ROWS = 7;
    const laneH = () => H() / ROWS;

    // distribute tags across lanes — duplicate so each lane has enough
    const pool = [...tags, ...tags];
    const shuffled = shuffleArray(pool);

    let items = [];

    /* Defer element creation until the container has a real width.
       On some browsers / slow connections, clientWidth is still 0
       at the moment useEffect fires.                               */
    function buildItems() {
      const w = W();
      items = shuffled.map((tag, i) => {
        const el = document.createElement('div');
        el.className = 'tag-pill';
        el.innerHTML =
          `<span class="tag-pill__dot"></span>` +
          `<span>${tag.name}</span>` +
          `<span class="tag-pill__kind">${tag.kind}</span>`;
        root.appendChild(el);

        const lane = i % ROWS;
        const speed = 18 + Math.random() * 22; // px / sec
        const yJitter = (Math.random() - 0.5) * (laneH() * 0.5);
        const x = Math.random() * w * 1.5 - w * 0.25;
        return { el, x, lane, speed, yJitter };
      });
    }

    /* Wait one rAF so the browser has laid out the container */
    const initFrame = requestAnimationFrame(() => {
      buildItems();

      let last = performance.now();
      const tick = (now) => {
        const dt = Math.min((now - last) / 1000, 0.1); // cap delta to 100ms to avoid jumps after tab switch
        last = now;
        const w = W();
        const h = H();
        const lh = h / ROWS;
        items.forEach(it => {
          it.x += it.speed * dt;
          const elW = it.el.offsetWidth || 120;
          if (it.x > w + 80) {
            it.x = -elW - 40 - Math.random() * 200;
          }
          const y = it.lane * lh + lh / 2 + it.yJitter;
          it.el.style.transform = `translate3d(${it.x}px, ${y - 22}px, 0)`;
        });
        animRef.current = requestAnimationFrame(tick);
      };
      animRef.current = requestAnimationFrame(tick);
    });

    return () => {
      cancelAnimationFrame(initFrame);
      cancelAnimationFrame(animRef.current);
      items.forEach(it => it.el.remove());
    };
  }, [tags]);

  return (
    <div className="carousel">
      <div className="carousel__track" ref={ref}></div>
    </div>
  );
}

/* ===================================================
   AUTHOR CARD — 3D tilt on hover
   =================================================== */
function AuthorCard({ author }) {
  const ref = React.useRef(null);

  const onMove = (e) => {
    const card = ref.current;
    if (!card) return;
    const rect = card.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const rx = ((y / rect.height) - 0.5) * -10;
    const ry = ((x / rect.width)  - 0.5) *  12;
    card.style.transform = `perspective(1000px) rotateX(${rx}deg) rotateY(${ry}deg) translateZ(0)`;
    card.style.setProperty('--mx', (x / rect.width * 100) + '%');
    card.style.setProperty('--my', (y / rect.height * 100) + '%');
  };
  const onLeave = () => {
    const card = ref.current;
    if (!card) return;
    card.style.transform = '';
  };

  const onClick = (e) => {
    e.preventDefault();
    navigateWithTransition(`autor/${author.id}`);
  };

  return (
    <a
      href={`autor/${author.id}`}
      className="author-card"
      ref={ref}
      onClick={onClick}
      onMouseMove={onMove}
      onMouseLeave={onLeave}
    >
      <div className="author-card__shine"></div>
      <div className="author-card__inner">
        <div className="author-card__row">
          <a href={author.github_url} target="_blank" rel="noreferrer" className="author-card__avatar-link" onClick={e => e.stopPropagation()}>
            <img className="author-card__avatar" src={author.avatar} alt={author.name} loading="lazy" />
          </a>
          <div>
            <h3 className="author-card__name">{author.name}</h3>
            <p className="author-card__user">@{author.username}</p>
          </div>
        </div>
        <p className="author-card__bio">{author.bio}</p>
        
        <div className="author-card__socials">
          {author.socials.slice(0, 3).map((s, i) => (
            <a key={i} href={s.url} target="_blank" rel="noreferrer" className="author-card__social-icon" onClick={e => e.stopPropagation()} title={s.label}>
              {s.type === 'github' && <Icon.Github />}
              {s.type === 'twitter' && <Icon.Twitter />}
              {s.type === 'linkedin' && <Icon.Linkedin />}
              {s.type === 'instagram' && <Icon.Instagram />}
              {s.type === 'web' && <Icon.Globe />}
            </a>
          ))}
        </div>

        <span className="author-card__cta">
          ver perfil <Icon.ArrowRight />
        </span>
      </div>
    </a>
  );
}

Object.assign(window, { TagCarousel, AuthorCard });
