// Formadores + Testemunhos
const INSTRUCTORS = [
{
  name: 'Renato Foan82', role: 'Design Director & AI Researcher',
  bio: 'Especialista em design digital com mais de 20 anos de experiência. Pioneiro na aplicação de IA generativa no design português.',
  photo: 'assets/renato.png'
},
{
  name: 'Filipe SJ', role: 'Creative Director & AI Researcher',
  bio: 'Creative Director com foco em inovação tecnológica. Investigador ativo no campo da inteligência artificial aplicada à criatividade.',
  photo: 'assets/filipe.png'
},
{
  name: 'Ana Baltazar', role: 'AI First Content Creator',
  bio: 'Especialista em criação de conteúdo digital e estratégias de comunicação com IA.',
  photo: 'assets/ana.jpg'
}];

const GUESTS = [
{ name: 'Margarida Barreto', photo: 'assets/margarida.png', icon: 'sparkles', seal: 'VIP' },
{ name: 'Diana Mota', photo: 'assets/diana.png', icon: 'play', seal: 'VIP' },
{ name: 'Rui Barroca', photo: 'assets/rui.png', icon: 'folder', seal: 'VIP' }];

const SealBadge = ({ label }) =>
<div style={{
  position: 'absolute', top: -6, right: -6, zIndex: 3,
  width: 34, height: 34, borderRadius: '50%',
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  background: 'linear-gradient(120deg, var(--violet), var(--pink))',
  color: '#fff', fontFamily: 'var(--font-mono)', fontSize: 11,
  fontWeight: 700, letterSpacing: '0.04em',
  border: '2px solid var(--bg)',
  boxShadow: '0 6px 16px rgba(0,0,0,0.45)'
}}>
    {label}
  </div>;


const Instructors = () => {
  const { t, dict } = useI18n();
  const people = INSTRUCTORS.map((p, i) => ({ ...p, ...((dict.instructors && dict.instructors[i]) || {}) }));
  return (
  <section className="section" id="formadores">
    <div className="container">
      <h2 className="h-section reveal">{t('instructors.title')}</h2>
      <p className="section-sub reveal">{t('instructors.sub')}</p>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }} className="grid-inst">
        {people.map((p, i) =>
      <div key={i} className="card reveal" style={{ padding: 32, textAlign: 'center' }}>
            <div style={{ position: 'relative', width: 100, height: 100, margin: '0 auto 20px' }}>
              <div style={{
            position: 'absolute', inset: -4, borderRadius: '50%',
            background: 'conic-gradient(from 180deg, var(--violet), var(--pink), var(--cyan), var(--violet))',
            filter: 'blur(6px)', opacity: 0.6
          }} />
              <div style={{
            position: 'relative', width: 100, height: 100, borderRadius: '50%',
            background: '#0f0f18',
            border: '2px solid rgba(255,255,255,0.08)',
            overflow: 'hidden'
          }}>
                <img src={p.photo} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
            </div>
            <h3 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 600 }}>{p.name}</h3>
            <div className="grad-text" style={{ fontSize: 13, marginBottom: 14, fontWeight: 500 }}>{p.role}</div>
            <p style={{ color: 'var(--text-dim)', fontSize: 14, lineHeight: 1.55, margin: '0' }}>
              {p.bio}
            </p>
          </div>
      )}
        {GUESTS.map((g, i) => {
        const tg = (dict.guests && dict.guests[i]) || {};
        return (
      <div key={`guest-${i}`} className="card reveal" style={{ padding: 32, textAlign: 'center' }}>
            <div style={{ position: 'relative', width: 100, height: 100, margin: '0 auto 20px' }}>
              <div style={{
            position: 'absolute', inset: -4, borderRadius: '50%',
            background: 'conic-gradient(from 180deg, var(--violet), var(--pink), var(--cyan), var(--violet))',
            filter: 'blur(6px)', opacity: 0.6
          }} />
              <div style={{
            position: 'relative', width: 100, height: 100, borderRadius: '50%',
            background: '#0f0f18',
            border: '2px solid rgba(255,255,255,0.08)',
            overflow: 'hidden',
            display: 'grid', placeItems: 'center',
            color: 'rgba(255,255,255,0.35)'
          }}>
                {g.photo ?
                <img src={g.photo} alt={g.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> :
                <svg width="44" height="44" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
                  <circle cx="12" cy="7" r="4" />
                </svg>
                }
              </div>
              {g.seal && <SealBadge label={g.seal} />}
            </div>
            <h3 style={{ margin: '0 0 6px', fontSize: 20, fontWeight: 600 }}>{g.name}</h3>
            <div className="grad-text" style={{ fontSize: 13, marginBottom: 14, fontWeight: 500 }}>
              {tg.role || ''}
            </div>
            <p style={{ color: 'var(--text-dim)', fontSize: 14, lineHeight: 1.55, margin: '0', whiteSpace: 'pre-line' }}>{tg.desc || ''}</p>
          </div>);

      })}
      </div>
    </div>
    <style>{`
      @media (max-width: 900px) { .grid-inst { grid-template-columns: 1fr !important; } }
    `}</style>
  </section>);
};


const TESTIMONIALS = [
{ name: 'Maria Pinho', role: 'Art Director and Designer | Loba Design', quote: 'Que formação incrível. O Filipe SJ e o Renato foram impecáveis a mostrar como podemos usar a AI no design a nosso favor. Super recomendado!' },
{ name: 'Carlos Silva', role: 'Sénior Lead UX/UI Designer', quote: 'Esta experiência reforçou uma mudança de mentalidade, em que a IA não é apenas uma ferramenta para produzir mais depressa. É uma camada que pode reformular a forma como design, produto e execução se ligam. Construo workflows em que a IA reduz a fricção, aumenta a clareza e apoia melhores decisões à escala. Grato ao MDAI por esta abordagem prática, sempre focada na aplicação real e não apenas na teoria.' },
{ name: 'Lia Cervantes Cardoso', role: 'Designer Lead de Produto e Calçado', quote: 'Foi, sem dúvida, uma experiência transformadora para mim. O Renato e o Filipe são formadores absolutamente incríveis.' },
{ name: 'Diogo Bigas', role: 'Designer e Fotógrafo profissional', quote: 'Uma formação intensa e pragática. Saí com ferramentas concretas para integrar IA no meu workflow diário e elevar a qualidade dos projetos.' },
{ name: 'David Cruz', role: 'Senior Product Designer', quote: 'Adorei o curso, superou tudo o que estava à espera, mudou muito o meu mindset de pensar. Fui ficando cada vez mais surpreendido à medida que o contexto aumentava e facilitava a minha conversação com os modelos.' },
{ name: 'Diana Gonçalves', role: 'Senior Designer, Berlim', quote: 'O curso não vendeu a IA como um atalho, mas tratou-a como uma ferramenta, com propriedades, limites e comportamentos específicos consoante o modelo com que estás a trabalhar. Essa perspetiva fez toda a diferença.' },
{ name: 'João Brás', role: 'Senior Designer', quote: 'O MDAI foi uma mudança de mentalidade. Aprendi a integrar a IA desde a geração de ideias até à construção de soluções visuais. Foi uma formação muito bem conduzida, inspiradora e verdadeiramente transformadora.' },
{ name: 'Margarida Mendes', role: 'Senior Visual Designer', quote: 'Foi um mês intenso, mas muito positivo. Destaco a competência, a disponibilidade e a generosidade do Renato e do Filipe, sempre prontos a ajudar, esclarecer dúvidas e partilhar conhecimento com dedicação e simpatia... Recomendo sem dúvida a todos.' }];


/* ---------- Vertical-marquee column with drag + pause-on-hover ---------- */
const VerticalMarquee = ({ items, speed = 30 }) => {
  const wrapRef = React.useRef(null);
  const trackRef = React.useRef(null);
  const setRef = React.useRef(null);
  const stateRef = React.useRef({
    pos: 0,
    hovering: false,
    dragging: false,
    dragStartY: 0,
    dragStartPos: 0,
    lastT: 0
  });

  React.useEffect(() => {
    let raf;
    let prev = performance.now();

    const measure = () => {
      const sets = trackRef.current?.querySelectorAll('.tm-set');
      if (!sets || sets.length < 2) return 0;
      return sets[1].offsetTop - sets[0].offsetTop;
    };

    const tick = (now) => {
      const dt = Math.min(0.05, (now - prev) / 1000);
      prev = now;
      const s = stateRef.current;
      if (!s.hovering && !s.dragging) {
        s.pos -= speed * dt;
      }
      const tr = trackRef.current;
      if (tr) {
        const h = measure();
        if (h > 0) {
          while (s.pos <= -h) s.pos += h;
          while (s.pos >= 0) s.pos -= h;
          tr.style.transform = `translate3d(0, ${s.pos.toFixed(2)}px, 0)`;
        }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    const ro = new ResizeObserver(() => {
      const h = measure();
      if (h > 0) stateRef.current.pos = (stateRef.current.pos % h - h) % h;
    });
    if (setRef.current) ro.observe(setRef.current);

    return () => {cancelAnimationFrame(raf);ro.disconnect();};
  }, [speed]);

  const onEnter = () => {stateRef.current.hovering = true;};
  const onLeave = () => {stateRef.current.hovering = false;stateRef.current.dragging = false;};

  const onPointerDown = (e) => {
    const s = stateRef.current;
    s.dragging = true;
    s.dragStartY = e.clientY;
    s.dragStartPos = s.pos;
    wrapRef.current?.setPointerCapture(e.pointerId);
  };
  const onPointerMove = (e) => {
    const s = stateRef.current;
    if (!s.dragging) return;
    s.pos = s.dragStartPos + (e.clientY - s.dragStartY);
  };
  const onPointerUp = (e) => {
    stateRef.current.dragging = false;
    try {wrapRef.current?.releasePointerCapture(e.pointerId);} catch (_) {}
  };

  return (
    <div
      className="tm-wrap"
      ref={wrapRef}
      onMouseEnter={onEnter}
      onMouseLeave={onLeave}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={onPointerUp}
      onPointerCancel={onPointerUp}
      style={{
        position: 'relative',
        height: '100%',
        overflow: 'hidden',
        cursor: 'grab',
        touchAction: 'pan-x'
      }}>
      
      <div
        ref={trackRef}
        style={{
          position: 'absolute', top: 0, left: 0, right: 0,
          willChange: 'transform',
          backfaceVisibility: 'hidden'
        }}>
        
        <div className="tm-set" ref={setRef} style={{ display: 'flex', flexDirection: 'column', gap: 20, paddingBottom: 20 }}>
          {items.map((t, i) => <TCard t={t} key={`m1-${i}`} />)}
        </div>
        <div className="tm-set" aria-hidden="true" style={{ display: 'flex', flexDirection: 'column', gap: 20, paddingBottom: 20 }}>
          {items.map((t, i) => <TCard t={t} key={`m2-${i}`} />)}
        </div>
      </div>
    </div>);

};

const RoundedPlayIcon = ({ size = 20 }) =>
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" strokeWidth="3" strokeLinejoin="round" strokeLinecap="round" style={{ display: 'block', transform: 'translateX(1.5px)' }}>
    <path d="M8.5 6 L19 12 L8.5 18 Z" />
  </svg>;

const Testimonials = () => {
  const { t, dict } = useI18n();
  const T = TESTIMONIALS.map((x, i) => ({ ...x, ...((dict.testimonials && dict.testimonials[i]) || {}) }));
  const [playing, setPlaying] = React.useState(false);
  const [mobilePlaying, setMobilePlaying] = React.useState(false);
  const videoRef = React.useRef(null);
  const mobileVideoRef = React.useRef(null);

  const onPlay = () => {
    const v = videoRef.current;
    if (!v) return;
    v.play().then(() => setPlaying(true)).catch(() => {});
  };

  const togglePlay = () => {
    const v = videoRef.current;
    if (!v) return;
    if (v.paused) v.play().then(() => setPlaying(true)).catch(() => {});else
    {v.pause();setPlaying(false);}
  };

  const onMobilePlay = () => {
    const v = mobileVideoRef.current;
    if (!v) return;
    v.play().then(() => setMobilePlaying(true)).catch(() => {});
  };

  const toggleMobilePlay = () => {
    const v = mobileVideoRef.current;
    if (!v) return;
    if (v.paused) v.play().then(() => setMobilePlaying(true)).catch(() => {});else
    {v.pause();setMobilePlaying(false);}
  };

  // Split into 2 columns + a phone column (all items in 1)
  const leftItems = T.slice(0, 4);
  const rightItems = T.slice(4);
  const allItems = T;

  return (
    <section className="section" id="testemunhos">
      <div className="container">
        <h2 className="h-section reveal">{t('test.titlePre')}<span className="grad-text">{t('test.titleGrad')}</span></h2>
        <p className="section-sub reveal">{t('test.sub')}</p>

        {/* DESKTOP: 3 columns */}
        <div className="test-grid" style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: 24,
          alignItems: 'stretch'
        }}>
          <div className="test-col test-col-side">
            <VerticalMarquee items={leftItems} speed={28} />
          </div>

          <div className="test-col-video" onClick={togglePlay} style={{
            position: 'relative',
            borderRadius: 20,
            overflow: 'hidden',
            border: '1px solid var(--border)',
            background: '#0a0a16',
            aspectRatio: '1 / 1',
            cursor: 'pointer'
          }}>
            <video
              ref={videoRef}
              src="assets/testemunhos.mp4"
              poster="assets/testemunhos-poster.jpg"
              playsInline
              preload="metadata"
              disablePictureInPicture
              controlsList="nodownload noremoteplayback noplaybackrate nofullscreen"
              style={{
                position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
                background: '#0a0a16'
              }} />
            
            {!playing &&
            <button onClick={(e) => {e.stopPropagation();onPlay();}} aria-label="Play" className="test-play-btn" style={{
              position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 2,
              width: 60, height: 60, borderRadius: '50%',
              background: 'rgba(255,255,255,0.7)', color: '#0a0a16',
              display: 'grid', placeItems: 'center',
              boxShadow: '0 14px 36px rgba(0,0,0,0.55)',
              backdropFilter: 'blur(6px)',
              WebkitBackdropFilter: 'blur(6px)',
              cursor: 'pointer',
              border: 'none'
            }}>
                <RoundedPlayIcon size={26} />
              </button>
            }
            {!playing &&
            <div style={{
              position: 'absolute', inset: 0,
              background: 'linear-gradient(180deg, rgba(0,0,0,0.15) 0%, rgba(0,0,0,0.45) 100%)',
              pointerEvents: 'none'
            }} />
            }
          </div>

          <div className="test-col test-col-side">
            <VerticalMarquee items={rightItems} speed={26} />
          </div>
        </div>

        {/* MOBILE: video first, then single draggable column */}
        <div className="test-mobile" style={{ display: 'none' }}>
          <div
            onClick={toggleMobilePlay}
            style={{
              position: 'relative', borderRadius: 20, overflow: 'hidden',
              border: '1px solid var(--border)', background: '#0a0a16',
              aspectRatio: '1 / 1', marginBottom: 24, cursor: 'pointer'
            }}>
            <video
              ref={mobileVideoRef}
              src="assets/testemunhos.mp4"
              poster="assets/testemunhos-poster.jpg"
              playsInline preload="metadata"
              disablePictureInPicture
              controlsList="nodownload noremoteplayback noplaybackrate nofullscreen"
              style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} />
            {!mobilePlaying &&
            <button onClick={(e) => {e.stopPropagation();onMobilePlay();}} aria-label="Play" className="test-play-btn" style={{
              position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', zIndex: 2,
              width: 56, height: 56, borderRadius: '50%',
              background: 'rgba(255,255,255,0.7)', color: '#0a0a16',
              display: 'grid', placeItems: 'center',
              boxShadow: '0 14px 36px rgba(0,0,0,0.55)',
              backdropFilter: 'blur(6px)',
              WebkitBackdropFilter: 'blur(6px)',
              cursor: 'pointer',
              border: 'none'
            }}>
                <RoundedPlayIcon size={24} />
              </button>
            }
            {!mobilePlaying &&
            <div style={{
              position: 'absolute', inset: 0,
              background: 'linear-gradient(180deg, rgba(0,0,0,0.15) 0%, rgba(0,0,0,0.45) 100%)',
              pointerEvents: 'none'
            }} />
            }
          </div>
          <div style={{ height: 480 }}>
            <VerticalMarquee items={allItems} speed={28} />
          </div>
        </div>
      </div>
      <style>{`
        .tm-wrap::before, .tm-wrap::after {
          content: '';
          position: absolute;
          left: 0; right: 0;
          height: 60px;
          pointer-events: none;
          z-index: 1;
        }
        .tm-wrap::before {
          top: 0;
          background: linear-gradient(180deg, var(--bg) 0%, transparent 100%);
        }
        .tm-wrap::after {
          bottom: 0;
          background: linear-gradient(0deg, var(--bg) 0%, transparent 100%);
        }
        .tm-wrap:active { cursor: grabbing; }
        @media (max-width: 900px) {
          .test-grid { display: none !important; }
          .test-mobile { display: block !important; }
        }
      `}</style>
    </section>);

};

const TCard = ({ t }) =>
<div className="card" style={{
  padding: 24,
  pointerEvents: 'none' /* let the wrapper handle drag */
}}>
    <div style={{ color: 'var(--violet-2)', marginBottom: 12, fontFamily: 'var(--font-display)', fontSize: 32, lineHeight: 0.7, letterSpacing: '-0.05em' }}>
      &ldquo;
    </div>
    <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--text)', margin: '0 0 18px' }}>
      {t.quote}
    </p>
    <div style={{ fontWeight: 600, fontSize: 14 }}>{t.name}</div>
    <div className="grad-text" style={{ fontSize: 12, fontWeight: 500 }}>{t.role}</div>
  </div>;


Object.assign(window, { Instructors, Testimonials });