/** Video carousel — YouTube embeds.
 * Paste each YouTube link (or video ID) in the `youtube` field below. Empty = placeholder.
 * Only a thumbnail loads until the visitor clicks play; the player is then embedded from youtube-nocookie.com.
 */
const TCC_VIDEOS = [
  { youtube: 'https://www.youtube.com/watch?v=dwPYXfMvurU', title: 'Serie "MemoriaTribal". Episodio 1: El Costo Invisible de las Empresas Familiares' },
  { youtube: 'https://www.youtube.com/watch?v=TNmV69cQ6DM', title: 'Serie "MemoriaTribal". Episodio 2: Codificando el ADN empresarial' },
  { youtube: 'https://www.youtube.com/watch?v=HHrF_YsnNyk', title: 'Serie "MemoriaTribal". Episodio 3: El Plano Completo de tu Empresa' },
  { youtube: 'https://www.youtube.com/watch?v=B8JfU9qmOe8', title: 'Serie "MemoriaTribal". Episodio 4: Lo más valio es el humano' },
  { youtube: 'https://www.youtube.com/watch?v=Y1ZPnbq_UVc', title: 'Serie "Memoria Tribal". Episodio 5 - Te mostramos nuestro taller' }
].map((v, i) => ({ id: String(i + 1).padStart(2, '0'), ytId: ytIdFrom(v.youtube), title: { es: v.title, en: v.title } }));

function ytIdFrom(s) {
  if (!s) return null;
  const m = String(s).match(/(?:youtu\.be\/|v=|embed\/|shorts\/|live\/)([\w-]{11})/);
  return m ? m[1] : (/^[\w-]{11}$/.test(s.trim()) ? s.trim() : null);
}

function VideoSlot({ v, active }) {
  const { t, lang } = useLang();
  const [playing, setPlaying] = React.useState(false);
  React.useEffect(() => { if (!active) setPlaying(false); }, [active]);
  const title = lang === 'EN' ? v.title.en : v.title.es;

  if (!v.ytId) return (
    <div className="vc-slot">
      <div className="vc-empty">
        <span className="vc-play"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"></path></svg></span>
        <span className="vc-label">{t('Video', 'Video')} {v.id}</span>
      </div>
    </div>
  );

  return (
    <div className="vc-slot">
      {playing ? (
        <iframe src={`https://www.youtube-nocookie.com/embed/${v.ytId}?autoplay=1&rel=0&modestbranding=1&playsinline=1`} title={title} allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerPolicy="strict-origin-when-cross-origin" allowFullScreen></iframe>
      ) : (
        <button className="vc-thumb" onClick={() => setPlaying(true)} aria-label={`${t('Reproducir', 'Play')}: ${title}`}>
          <img src={`https://i.ytimg.com/vi/${v.ytId}/hqdefault.jpg`} alt="" loading="lazy"></img>
          <span className="vc-play"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"></path></svg></span>
        </button>
      )}
    </div>
  );
}

function VideoCarousel() {
  const { t, lang } = useLang();
  const trackRef = React.useRef(null);
  const [idx, setIdx] = React.useState(0);

  const go = (i) => {
    const el = trackRef.current; if (!el) return;
    const n = Math.max(0, Math.min(TCC_VIDEOS.length - 1, i));
    const card = el.children[n];
    el.scrollTo({ left: card.offsetLeft - el.offsetLeft, behavior: 'smooth' });
  };
  const onScroll = () => {
    const el = trackRef.current; if (!el) return;
    const w = el.children[0]?.getBoundingClientRect().width || 1;
    const i = Math.round(el.scrollLeft / (w + 24));
    if (i !== idx) setIdx(i);
  };

  return (
    <section id="videos" className="section">
      <div className="container">
        <div style={{ marginBottom: 56, display: 'flex', justifyContent: 'space-between', alignItems: 'end', gap: 32, flexWrap: 'wrap' }}>
          <div>
            <Eyebrow>{t('· Videos', '· Videos')}</Eyebrow>
            <h2 style={{ marginTop: 18, fontFamily: 'var(--tcc-font-display)', fontSize: 'clamp(2rem, 4.5vw, 3.75rem)', fontWeight: 300, lineHeight: 1.05, letterSpacing: '-0.03em', color: 'var(--tcc-on-surface)', maxWidth: '18ch', textWrap: 'balance' }}>
              {t('Te explicamos lo que hacemos y', 'We explain what we do and')} <span className="accent-italic" style={{ color: 'var(--tcc-primary)' }}>{t('cómo lo hacemos', 'how we do it')}</span>
            </h2>
          </div>
          <div style={{ display: 'flex', gap: 12 }}>
            <button className="vc-nav" onClick={() => go(idx - 1)} disabled={idx === 0} aria-label={t('Anterior', 'Previous')}><span style={{ transform: 'rotate(180deg)', display: 'flex' }}><Icon.ChevronRight /></span></button>
            <button className="vc-nav" onClick={() => go(idx + 1)} disabled={idx >= TCC_VIDEOS.length - 1} aria-label={t('Siguiente', 'Next')}><Icon.ChevronRight /></button>
          </div>
        </div>
        <div className="vc-track" ref={trackRef} onScroll={onScroll}>
          {TCC_VIDEOS.map((v, i) => (
            <div className="vc-card" key={v.id}>
              <VideoSlot v={v} active={idx === i} />
              <div className="vc-title"><span className="vc-num">{v.id}</span>{lang === 'EN' ? v.title.en : v.title.es}</div>
            </div>
          ))}
        </div>
        <div className="vc-dots">
          {TCC_VIDEOS.map((v, i) => <button key={v.id} className={i === idx ? 'on' : ''} onClick={() => go(i)} aria-label={`${i + 1}`} />)}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { VideoCarousel, TCC_VIDEOS });
