// Countdown hero helper + Audience + Tools + Final Project + Urgency strip

const useCountdown = (target) => {
  const [now, setNow] = React.useState(() => Date.now());
  React.useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  const diff = Math.max(0, target - now);
  return {
    d: Math.floor(diff / 86400000),
    h: Math.floor(diff / 3600000) % 24,
    m: Math.floor(diff / 60000) % 60,
    s: Math.floor(diff / 1000) % 60
  };
};

// Start: 2 Feb 2027 18:30 Lisbon (WET, +00:00)
const START_TARGET = new Date('2027-02-02T18:30:00+00:00').getTime();

const CountdownStrip = () => {
  const c = useCountdown(START_TARGET);
  const Block = ({ v, l }) =>
  <div style={{ textAlign: 'center', minWidth: 62 }}>
      <div className="grad-text" style={{
      fontSize: 36, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.03em',
      fontVariantNumeric: 'tabular-nums'
    }}>{String(v).padStart(2, '0')}</div>
      <div style={{ fontSize: 10, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.12em', marginTop: 6 }}>{l}</div>
    </div>;

  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 20,
      padding: '18px 28px',
      background: 'rgba(124,92,255,0.06)',
      border: '1px solid rgba(124,92,255,0.2)',
      borderRadius: 16,
      backdropFilter: 'blur(12px)'
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingRight: 18, borderRight: '1px solid rgba(255,255,255,0.08)' }}>
        <span style={{
          width: 8, height: 8, borderRadius: '50%', background: '#ff6b8e',
          boxShadow: '0 0 12px #ff6b8e',
          animation: 'pulse 1.5s infinite'
        }} />
        <span style={{ fontSize: 12, color: 'var(--text-dim)', letterSpacing: '0.05em', fontWeight: 500 }}>Início em</span>
      </div>
      <Block v={c.d} l="dias" />
      <Block v={c.h} l="horas" />
      <Block v={c.m} l="min" />
      <Block v={c.s} l="seg" />
      <style>{`@keyframes pulse { 0%,100% { opacity:1 } 50% { opacity:.3 } }`}</style>
    </div>);

};

/* ===================== AUDIENCE ===================== */
const AUDIENCE = [
  { title: 'Criativos',      verb: 'Imagina',  desc: 'Explora novas formas de criar, conceptualizar e entregar ideias.',     color: '#b6a0ff' },
  { title: 'Designers',      verb: 'Desenha',  desc: 'Integra IA no teu processo: comunicação, produto digital, branding.',  color: '#ff8ad6' },
  { title: 'Marketers',      verb: 'Acelera',  desc: 'Acelera campanhas, research e produção de conteúdo em escala.',         color: '#6ad4ff' },
  { title: 'Gestores',       verb: 'Lidera',   desc: 'Lidera equipas que usam IA com método, ética e visão de futuro.',       color: '#b6a0ff' },
  { title: 'Empreendedores', verb: 'Constrói', desc: 'Domina a Gen AI de forma estruturada e prática para o teu negócio.',    color: '#ff8ad6' },
];

const Audience = () => {
  const { t, dict } = useI18n();
  const A = AUDIENCE.map((a, i) => ({ ...a, ...(dict.audience && dict.audience[i]) }));
  const [active, setActive] = React.useState(0);
  const trackRef = React.useRef(null);
  const setRef = React.useRef(null);

  // Cycle the highlighted persona
  React.useEffect(() => {
    const id = setInterval(() => {
      setActive((i) => (i + 1) % A.length);
    }, 3500);
    return () => clearInterval(id);
  }, []);

  // Continuous horizontal marquee for the verbs row
  React.useEffect(() => {
    let raf;
    let pos = 0;
    let prev = performance.now();
    const SPEED = 50; // px/s

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

    const tick = (now) => {
      const dt = Math.min(0.05, (now - prev) / 1000);
      prev = now;
      pos -= SPEED * dt;
      const tr = trackRef.current;
      if (tr) {
        const w = measureCopy();
        if (w > 0) {
          while (pos <= -w) pos += w;
          tr.style.transform = `translate3d(${pos.toFixed(2)}px,0,0)`;
        }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    const ro = new ResizeObserver(() => {
      const w = measureCopy();
      if (w > 0) pos = ((pos % w) + w) % w - w;
    });
    if (setRef.current) ro.observe(setRef.current);

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

  const current = A[active];

  return (
    <section className="section" id="audiencia" style={{ overflow: 'hidden', paddingBottom: 40 }}>
      <div className="container">
        <div style={{ maxWidth: 1100 }}>
          <div className="reveal" style={{
            color: 'var(--text-muted)',
            fontSize: 13,
            letterSpacing: '0.12em',
            textTransform: 'uppercase',
            marginBottom: 18,
            fontFamily: 'var(--font-mono)',
          }}>
            {t('audience.eyebrow')}
          </div>

          <h2 className="aud-title reveal" style={{
            margin: 0,
            fontWeight: 700,
            fontSize: 'clamp(44px, 6.5vw, 92px)',
            lineHeight: 1.02,
            letterSpacing: '-0.035em',
            textWrap: 'balance',
          }}>
            <span style={{ color: 'var(--text)' }}>{t('audience.madeFor')}</span>
            <span
              key={`name-${active}`}
              className="aud-word"
              style={{
                color: current.color,
                display: 'inline-block',
                textShadow: `0 0 80px ${current.color}55`,
              }}>
              {current.title}.
            </span>
          </h2>

          <p
            key={`desc-${active}`}
            className="aud-desc reveal"
            style={{
              color: 'var(--text-dim)',
              fontSize: 'clamp(16px, 1.4vw, 19px)',
              maxWidth: 560,
              margin: '24px 0 0',
              lineHeight: 1.55,
              minHeight: 56,
            }}>
            {current.desc}
          </p>
        </div>
      </div>

      {/* Verbs marquee — supporting visual rhythm, NOT the persona names */}
      <div className="aud-marquee-wrap" style={{ marginTop: 72, position: 'relative' }}>
        <div className="aud-track" ref={trackRef}>
          <div className="aud-set" ref={setRef}>
            {A.map((a, i) => <AudVerb a={a} active={i === active} onClick={() => setActive(i)} key={`s1-${i}`} />)}
          </div>
          <div className="aud-set" aria-hidden="true">
            {A.map((a, i) => <AudVerb a={a} active={i === active} onClick={() => setActive(i)} key={`s2-${i}`} />)}
          </div>
        </div>
      </div>

      <style>{`
        .aud-word {
          animation: audSwap 0.6s cubic-bezier(0.22, 1, 0.36, 1) both;
        }
        .aud-desc {
          animation: audFade 0.6s cubic-bezier(0.22, 1, 0.36, 1) both;
        }
        @keyframes audSwap {
          from { opacity: 0; transform: translateY(0.35em); filter: blur(8px); }
          to   { opacity: 1; transform: translateY(0);     filter: blur(0); }
        }
        @keyframes audFade {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        .aud-marquee-wrap {
          mask-image: linear-gradient(90deg, transparent 0%, #000 6%, #000 94%, transparent 100%);
          -webkit-mask-image: linear-gradient(90deg, transparent 0%, #000 6%, #000 94%, transparent 100%);
          padding: 18px 0 24px;
        }
        @media (max-width: 720px) {
          .aud-marquee-wrap {
            margin-top: 36px !important;
            padding: 12px 0 16px;
          }
          .aud-word {
            display: block !important;
          }
        }
        .aud-track {
          display: inline-flex;
          gap: 56px;
          align-items: center;
          will-change: transform;
          backface-visibility: hidden;
          padding: 0 32px;
        }
        .aud-set {
          display: inline-flex;
          gap: 56px;
          align-items: center;
          flex-shrink: 0;
        }
        .aud-verb {
          font-weight: 600;
          font-size: clamp(34px, 4.5vw, 64px);
          line-height: 1.25;
          letter-spacing: -0.03em;
          white-space: nowrap;
          font-style: italic;
          cursor: pointer;
          opacity: 0.55;
          transition: opacity 0.4s ease;
        }
        .aud-verb.is-active {
          opacity: 1;
        }
        .aud-verb:hover {
          opacity: 0.75;
        }
        .aud-sep {
          display: inline-block;
          width: 10px; height: 10px;
          border-radius: 50%;
          background: currentColor;
          opacity: 0.4;
          flex-shrink: 0;
        }
      `}</style>
    </section>
  );
};

const AudVerb = ({ a, active, onClick }) => (
  <React.Fragment>
    <span
      className={`aud-verb ${active ? 'is-active' : ''}`}
      style={{ color: active ? '#ffffff' : 'var(--text-muted)' }}
      onClick={onClick}>
      {a.verb}
    </span>
    <span className="aud-sep" style={{ color: 'var(--text-muted)' }} />
  </React.Fragment>
);


/* ===================== TOOLS ===================== */
const TOOLS = [
{ name: 'ChatGPT', cat: 'Multi-modal', color: '#10a37f', mark: 'GPT' },
{ name: 'Claude', cat: 'Raciocínio', color: '#d97757', mark: 'C' },
{ name: 'Gemini', cat: 'Multi-modal', color: '#4285f4', mark: '✦' },
{ name: 'Midjourney', cat: 'Imagem', color: '#9b8cff', mark: 'M' },
{ name: 'Leonardo', cat: 'Imagem', color: '#f59e0b', mark: 'L' },
{ name: 'Flux', cat: 'Imagem', color: '#ec4899', mark: 'F' },
{ name: 'Runway', cat: 'Vídeo', color: '#00d4aa', mark: 'R' },
{ name: 'Seedance', cat: 'Vídeo', color: '#6366f1', mark: 'S' },
{ name: 'Kling', cat: 'Vídeo', color: '#3b82f6', mark: 'K' },
{ name: 'Veo 3', cat: 'Vídeo', color: '#ff6b8e', mark: 'V' },
{ name: 'ElevenLabs', cat: 'Voz', color: '#a78bfa', mark: '11' },
{ name: 'Suno', cat: 'Música', color: '#f43f5e', mark: 'S' },
{ name: 'Figma AI', cat: 'Produto', color: '#a78bfa', mark: '◇' },
{ name: 'Perplexity', cat: 'Research', color: '#22d3ee', mark: 'P' },
{ name: 'Manus', cat: 'Research', color: '#facc15', mark: 'M' },
{ name: 'NotebookLM', cat: 'Research', color: '#fbbc04', mark: 'N' },
{ name: 'Cursor', cat: 'Código', color: '#ffffff', mark: '⌘' }];


const Tools = () => {
  const { t: tr, dict } = useI18n();
  const sectionRef = React.useRef(null);
  const trackLeftRef = React.useRef(null);
  const trackRightRef = React.useRef(null);
  const setLeftRef = React.useRef(null);
  const setRightRef = React.useRef(null);

  // JS-driven marquee using rAF. We translate the track each frame by
  // (speed * dt). When position passes one "copy width", we add/subtract
  // that exact width to wrap seamlessly. Copy width is measured precisely
  // (offsetLeft of the 2nd copy) so the loop is invisible.
  React.useEffect(() => {
    let lastY = window.scrollY;
    let lastT = performance.now();
    let boost = 0;
    let posLeft = 0;
    let posRight = 0;
    let raf;

    const BASE = 30; // px / s

    const measureCopy = (trackEl) => {
      // trackEl has two <.tools-set> children; copy width = offsetLeft of 2nd child
      const sets = trackEl.querySelectorAll('.tools-set');
      if (sets.length < 2) return 0;
      return sets[1].offsetLeft - sets[0].offsetLeft;
    };

    const onScroll = () => {
      const now = performance.now();
      const dy = window.scrollY - lastY;
      const dt = Math.max(1, now - lastT);
      const v = Math.abs(dy) / dt; // px / ms
      boost = Math.min(5, boost + v * 0.5);
      lastY = window.scrollY;
      lastT = now;
    };
    window.addEventListener('scroll', onScroll, { passive: true });

    let prev = performance.now();
    const tick = (now) => {
      const dt = Math.min(0.05, (now - prev) / 1000);
      prev = now;
      // smooth exponential decay of boost (~half-life ~250ms)
      boost *= Math.pow(0.06, dt);
      const speed = BASE * (1 + boost * 0.6);
      posLeft -= speed * dt;
      posRight += speed * dt;

      const tl = trackLeftRef.current;
      const tr = trackRightRef.current;
      if (tl) {
        const w = measureCopy(tl);
        if (w > 0) {
          if (posLeft <= -w) posLeft += w;
          else if (posLeft >= w) posLeft -= w;
          tl.style.transform = `translate3d(${posLeft.toFixed(2)}px,0,0)`;
        }
      }
      if (tr) {
        const w = measureCopy(tr);
        if (w > 0) {
          if (posRight >= 0) posRight -= w;
          else if (posRight <= -w) posRight += w;
          tr.style.transform = `translate3d(${posRight.toFixed(2)}px,0,0)`;
        }
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);

    // If layout grows after fonts/images load, the modulo width changes.
    // Re-clamp positions inside the new range to avoid a jump.
    const ro = new ResizeObserver(() => {
      [trackLeftRef.current, trackRightRef.current].forEach((tr2) => {
        if (!tr2) return;
        const w = measureCopy(tr2);
        if (w > 0) {
          if (tr2 === trackLeftRef.current) posLeft = ((posLeft % w) + w) % w - w;
          if (tr2 === trackRightRef.current) posRight = ((posRight % w) - w + w) % w - w;
        }
      });
    });
    if (setLeftRef.current) ro.observe(setLeftRef.current);
    if (setRightRef.current) ro.observe(setRightRef.current);

    return () => {
      window.removeEventListener('scroll', onScroll);
      cancelAnimationFrame(raf);
      ro.disconnect();
    };
  }, []);

  const Pill = ({ t, idx }) =>
  <div className="tool-pill" key={idx} style={{
    display: 'inline-flex', alignItems: 'center', gap: 14,
    padding: '14px 22px 14px 14px',
    background: `linear-gradient(135deg, ${t.color}18, rgba(255,255,255,0.02))`,
    border: `1px solid ${t.color}40`,
    borderRadius: 999,
    flexShrink: 0,
    transition: 'transform 0.3s, border-color 0.3s, box-shadow 0.3s'
  }}>
      <div style={{
      width: 36, height: 36, borderRadius: '50%',
      background: `linear-gradient(135deg, ${t.color}, ${t.color}aa)`,
      border: `1px solid ${t.color}`,
      display: 'grid', placeItems: 'center',
      fontSize: t.mark.length > 1 ? 12 : 16,
      fontWeight: 700,
      color: t.color === '#ffffff' ? '#000' : 'white',
      fontFamily: 'var(--font-mono)',
      boxShadow: `0 0 20px ${t.color}55`,
      flexShrink: 0
    }}>
        {t.mark}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', whiteSpace: 'nowrap' }}>
        <span style={{ fontWeight: 600, fontSize: 15, color: 'var(--text)' }}>{t.name}</span>
        <span style={{ color: 'var(--text-muted)', fontSize: 11, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{(dict.cats && dict.cats[t.cat]) || t.cat}</span>
      </div>
    </div>;


  // Split into two rows
  const row1 = TOOLS.slice(0, 8);
  const row2 = TOOLS.slice(8);

  return (
    <section className="section" id="ferramentas" ref={sectionRef}>
      <div className="container" style={{ marginBottom: 50 }}>
        <h2 className="h-section reveal">{tr('tools.titlePre')}<span className="grad-text">{tr('tools.titleGrad')}</span></h2>
        <p className="section-sub reveal">{tr('tools.sub')}</p>
      </div>

      <div className="tools-marquee-wrap">
        <div className="tools-row">
          <div className="tools-track" ref={trackLeftRef}>
            <div className="tools-set" ref={setLeftRef}>
              {row1.map((t, i) => <Pill t={t} idx={`a1-${i}`} key={`a1-${i}`} />)}
            </div>
            <div className="tools-set" aria-hidden="true">
              {row1.map((t, i) => <Pill t={t} idx={`a2-${i}`} key={`a2-${i}`} />)}
            </div>
          </div>
        </div>
        <div className="tools-row" style={{ marginTop: 18 }}>
          <div className="tools-track" ref={trackRightRef}>
            <div className="tools-set" ref={setRightRef}>
              {row2.map((t, i) => <Pill t={t} idx={`b1-${i}`} key={`b1-${i}`} />)}
            </div>
            <div className="tools-set" aria-hidden="true">
              {row2.map((t, i) => <Pill t={t} idx={`b2-${i}`} key={`b2-${i}`} />)}
            </div>
          </div>
        </div>
      </div>



      <style>{`
        .tools-marquee-wrap {
          position: relative;
          overflow: hidden;
          mask-image: linear-gradient(90deg, transparent 0%, #000 8%, #000 92%, transparent 100%);
          -webkit-mask-image: linear-gradient(90deg, transparent 0%, #000 8%, #000 92%, transparent 100%);
        }
        .tools-row {
          display: flex;
          width: 100%;
          overflow: hidden;
        }
        .tools-track {
          display: inline-flex;
          gap: 14px;
          flex-shrink: 0;
          will-change: transform;
          backface-visibility: hidden;
        }
        .tools-set {
          display: inline-flex;
          gap: 14px;
          flex-shrink: 0;
        }
        .tool-pill:hover {
          transform: translateY(-2px);
        }
      `}</style>
    </section>);

};


/* ===================== FINAL PROJECT ===================== */
const FinalProject = () =>
<section className="section" id="projeto">
    <div className="container">
      <div className="card reveal" style={{
      padding: 60, position: 'relative', overflow: 'hidden',
      background: 'linear-gradient(135deg, rgba(124,92,255,0.08), rgba(255,110,199,0.05) 50%, var(--surface))',
      borderColor: 'rgba(124,92,255,0.2)'
    }}>
        <div className="ambient" style={{
        width: 500, height: 500, right: -200, top: -200,
        background: 'radial-gradient(circle, rgba(255,110,199,0.25), transparent 60%)'
      }} />
        <div style={{
        position: 'relative', display: 'grid',
        gridTemplateColumns: '1fr 1fr', gap: 60, alignItems: 'center'
      }} className="grid-project">
          <div>
            <h2 style={{
            fontSize: 'clamp(32px, 4vw, 48px)', fontWeight: 700, margin: '0 0 20px',
            letterSpacing: '-0.02em', lineHeight: 1.05
          }}>
              Termina com um <span className="grad-text">projeto real</span> no teu portefólio
            </h2>
            <p style={{ color: 'var(--text-dim)', fontSize: 16, lineHeight: 1.65, margin: '0 0 28px' }}>Ao longo da formação vais desenvolver um projeto da concepção à entrega aplicando tudo o que aprendes e diversos workflows.
Sais com um caso real para mostrar a clientes ou empregadores.

          </p>
            <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'grid', gap: 12 }}>
              {[
            'Briefing real, trabalhado em fases ao longo do curso',
            'Mentoria individual para aprofundar a tua ideia',
            'Caso de estudo pronto para partilhar publicamente'].
            map((x, i) =>
            <li key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 15, color: 'var(--text)' }}>
                  <span className="check-bullet" style={{ marginTop: 4 }}><Icon name="check" size={11} stroke={3} /></span>
                  {x}
                </li>
            )}
            </ul>
          </div>
          <div style={{ position: 'relative' }}>
            {/* Mock portfolio cards stack */}
            <div style={{ position: 'relative', height: 360 }}>
              {[
            { top: 20, left: 40, rot: -6, z: 1, color: 'rgba(255,110,199,0.15)', label: 'Caso de estudo', sub: 'Brand · Motion' },
            { top: 60, left: 0, rot: 3, z: 2, color: 'rgba(124,92,255,0.18)', label: 'Projeto final', sub: 'UX/UI · Gen AI' },
            { top: 120, left: 80, rot: -2, z: 3, color: 'rgba(79,208,255,0.12)', label: 'Portefólio 2028', sub: 'Visual · Video' }].
            map((c, i) =>
            <div key={i} style={{
              position: 'absolute', top: c.top, left: c.left,
              width: 280, height: 180,
              background: `linear-gradient(135deg, ${c.color}, #14141f)`,
              border: '1px solid var(--border-strong)',
              borderRadius: 18, padding: 22,
              transform: `rotate(${c.rot}deg)`,
              zIndex: c.z,
              boxShadow: '0 20px 50px -20px rgba(0,0,0,0.6)'
            }}>
                  <div style={{
                width: '100%', height: 90, borderRadius: 10, marginBottom: 14,
                background: `
                      repeating-linear-gradient(135deg, rgba(255,255,255,0.04) 0, rgba(255,255,255,0.04) 1px, transparent 1px, transparent 8px),
                      rgba(255,255,255,0.02)
                    `,
                border: '1px solid var(--border)'
              }} />
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{c.label}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', marginTop: 4 }}>{c.sub}</div>
                </div>
            )}
            </div>
          </div>
        </div>
      </div>
    </div>
    <style>{`
      @media (max-width: 900px) { .grid-project { grid-template-columns: 1fr !important; } }
    `}</style>
  </section>;


/* ===================== URGENCY STRIP (between Hero and Stats) ===================== */
const UrgencyStrip = () => {
  const { t } = useI18n();
  const [seats, setSeats] = React.useState(7);
  return (
    <section style={{ padding: '40px 0', borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)', background: 'rgba(124,92,255,0.03)' }}>
      <div className="container" style={{ display: 'flex', gap: 28, justifyContent: 'space-around', alignItems: 'center', flexWrap: 'wrap' }}>
        <UStat icon="users" val={t('urgency.seats')} sub={t('urgency.seatsSub')} accent="var(--pink)" />
        <div style={{ width: 1, height: 40, background: 'var(--border)' }} className="urgency-divider" />
        <UStat icon="sparkles" val="−50%" sub={t('urgency.discountSub')} accent="var(--violet-2)" />
        <div style={{ width: 1, height: 40, background: 'var(--border)' }} className="urgency-divider" />
        <UStat icon="globe" val={t('urgency.remote')} sub={t('urgency.remoteSub')} accent="var(--cyan)" />
      </div>
      <style>{`
        @media (max-width: 800px) { .urgency-divider { display: none; } }
      `}</style>
    </section>);

};

const UStat = ({ icon, val, sub, accent }) =>
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
    <span style={{ color: accent }}><Icon name={icon} size={18} /></span>
    <div>
      <div style={{ fontWeight: 600, fontSize: 15 }}>{val}</div>
      <div style={{ color: 'var(--text-muted)', fontSize: 12 }}>{sub}</div>
    </div>
  </div>;


Object.assign(window, { CountdownStrip, Audience, Tools, FinalProject, UrgencyStrip, START_TARGET, useCountdown });