// Welcome.jsx — primeira tela do Petal: lista de desafios c/ AUTO-SCROLL infinito
// Conteúdo duplicado + transform translateY animado via rAF → loop seamless

// --- Contador animado ----------------------------------------------
// Sobe de 0 → target (rampa easeOut), depois +1 a cada TICK_MS.
// Determinístico (baseado em PETAL_START_MS) → as duas cópias do loop
// mostram exatamente o mesmo número.
const PETAL_START_MS = performance.now();
const RAMP_MS = 2200;
// cada desafio tem seu próprio ritmo + offset → desincroniza últimos dígitos
const DEFAULT_TICK_MS = 4500;
const DEFAULT_OFFSET_MS = 0;

function computeJoined(target, elapsedMs, tickMs, offsetMs) {
  if (elapsedMs <= 0) return 0;
  if (elapsedMs < RAMP_MS) {
    const t = elapsedMs / RAMP_MS;
    const eased = 1 - Math.pow(1 - t, 3); // easeOutCubic
    return Math.floor(eased * target);
  }
  const sinceRamp = elapsedMs - RAMP_MS + offsetMs;
  return target + Math.max(0, Math.floor(sinceRamp / tickMs));
}

function useJoinedCount(target, tickMs = DEFAULT_TICK_MS, offsetMs = DEFAULT_OFFSET_MS) {
  const [n, setN] = React.useState(() =>
    computeJoined(target, performance.now() - PETAL_START_MS, tickMs, offsetMs)
  );
  React.useEffect(() => {
    let id;
    const update = () => {
      const elapsed = performance.now() - PETAL_START_MS;
      setN(computeJoined(target, elapsed, tickMs, offsetMs));
      const sinceRamp = elapsed - RAMP_MS + offsetMs;
      const next = elapsed < RAMP_MS
        ? 40
        : tickMs - (((sinceRamp % tickMs) + tickMs) % tickMs);
      id = setTimeout(update, Math.max(20, next));
    };
    update();
    return () => clearTimeout(id);
  }, [target, tickMs, offsetMs]);
  return n;
}

function MiniMosaic({ slots, gap = 2 }) {
  // Garantia: sempre EXATAMENTE 4 slots, todos do mesmo tamanho.
  // Retrato (mais alto que largo) pra dar respiro às fotos.
  const four = (slots || []).slice(0, 4);
  while (four.length < 4) four.push('');
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
      gap, borderRadius: 18, overflow: 'hidden',
    }}>
      {four.map((s, i) => {
        const isImg = typeof s === 'object' && s && s.src;
        return (
          <div key={i} data-photo-slot={isImg ? s.src : s} style={{
            aspectRatio: '3 / 4',
            background: isImg
              ? '#EEEAE3'
              : 'repeating-linear-gradient(45deg, #EEEAE3 0 7px, #E4DFD5 7px 14px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            padding: isImg ? 0 : 6, boxSizing: 'border-box',
            color: '#6b6357',
            fontFamily: '"JetBrains Mono", ui-monospace, monospace',
            fontSize: 8, lineHeight: 1.15, textAlign: 'center',
            letterSpacing: 0.15,
            overflow: 'hidden',
          }}>
            {isImg ? (
              <img
                src={s.src}
                alt={s.alt || ''}
                style={{
                  width: '100%', height: '100%',
                  objectFit: 'cover', objectPosition: s.pos || 'center',
                  display: 'block',
                }}
              />
            ) : (
              <span style={{ opacity: 0.75, whiteSpace: 'pre-line' }}>{s}</span>
            )}
          </div>
        );
      })}
    </div>
  );
}

function ChallengeRow({ title, joined, slots, hidePill = false, tickMs, offsetMs }) {
  const live = useJoinedCount(joined, tickMs, offsetMs);
  const formatted = live.toLocaleString('pt-BR');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ position: 'relative' }}>
        <MiniMosaic slots={slots} />
        {!hidePill && (
          <div style={{
            position: 'absolute', top: -14, left: '50%',
            transform: 'translateX(-50%)',
            background: '#FFFFFF',
            borderRadius: 999, padding: '6px 14px',
            boxShadow: '0 4px 14px rgba(0,0,0,0.08), 0 0 0 0.5px rgba(0,0,0,0.04)',
            fontFamily: 'Inter, sans-serif',
            fontSize: 13, fontWeight: 600, color: '#0A0A0A',
            letterSpacing: '-0.005em', whiteSpace: 'nowrap',
            fontVariantNumeric: 'tabular-nums',
          }}>+{formatted} entraram</div>
        )}
      </div>
      <h3 style={{
        fontFamily: 'Fraunces, serif',
        fontWeight: 700, fontSize: 22,
        lineHeight: 1.05,
        letterSpacing: '-0.025em',
        color: '#0A0A0A', margin: 0,
      }}>{title}</h3>
    </div>
  );
}

const PETAL_CHALLENGES = [
  {
    title: 'Petal 21', joined: 2999, tickMs: 3200, offsetMs: 800,
    slots: [
      { src: 'uploads/pasted-1778958683567-0.png', alt: 'esteiras vista tropical' },
      { src: 'uploads/pasted-1778959147035-0.png', alt: 'athleisure + café' },
      { src: 'uploads/pasted-1778959186404-0.png', alt: 'laptop praia + coco' },
      { src: 'uploads/pasted-1778959214914-0.png', alt: 'sacola de frutas' },
    ],
  },
  {
    title: 'Petal 75', joined: 9999, tickMs: 2300, offsetMs: 0,
    slots: [
      { src: 'uploads/pasted-1778959487342-0.png', alt: 'amigas montanha pôr-do-sol' },
      { src: 'uploads/pasted-1778959555368-0.png', alt: 'yoga em casa' },
      { src: 'uploads/pasted-1778959623522-0.png', alt: 'salada colorida' },
      { src: 'uploads/pasted-1778959666913-0.png', alt: 'livros de desenvolvimento' },
    ],
  },
  {
    title: 'Petal 30', joined: 4999, tickMs: 5100, offsetMs: 1700,
    slots: [
      { src: 'uploads/pasted-1778959989182-0.png', alt: 'praia + suco' },
      { src: 'uploads/pasted-1778960007247-0.png', alt: 'caixas de pêssego' },
      { src: 'uploads/pasted-1778960018965-0.png', alt: 'bronzeando boné amarelo' },
      { src: 'uploads/pasted-1778960027932-0.png', alt: 'mercado bebidas' },
    ],
  },
  {
    title: 'Petal Glow', joined: 7499, tickMs: 4300, offsetMs: 2600,
    slots: [
      { src: 'uploads/pasted-1778958004646-0.png', alt: 'academia c/ esteiras' },
      { src: 'uploads/pasted-1778958054785-0.png', alt: 'caixas de manga' },
      { src: 'uploads/pasted-1778958168399-0.png', alt: 'sauna de madeira' },
      { src: 'uploads/pasted-1778958242982-0.png', alt: 'compras saudáveis' },
    ],
  },
];

function ChallengeList() {
  // renderiza a lista — usado 2× pra loop seamless
  return (
    <div>
      {PETAL_CHALLENGES.map((c, i) => (
        <React.Fragment key={i}>
          <div style={{ padding: '0 24px' }}>
            <ChallengeRow
              title={c.title}
              joined={c.joined}
              slots={c.slots}
              tickMs={c.tickMs}
              offsetMs={c.offsetMs}
            />
          </div>
          <div style={{ height: 1, background: '#EEEEEE', margin: '28px 24px' }} />
        </React.Fragment>
      ))}
    </div>
  );
}

function Welcome({ onNext, onLogin }) {
  const trackRef = React.useRef(null);
  const firstHalfRef = React.useRef(null);

  React.useEffect(() => {
    const SPEED = 22; // px/segundo — vibe video chill
    let y = 0;
    let last = performance.now();
    let raf;
    const tick = (now) => {
      const dt = (now - last) / 1000;
      last = now;
      y += SPEED * dt;
      // tamanho de UMA cópia da lista (medido a partir do primeiro filho)
      const h = firstHalfRef.current?.offsetHeight || 0;
      if (h && y >= h) y -= h; // wrap seamless
      if (trackRef.current) {
        trackRef.current.style.transform = `translateY(${-y}px)`;
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div style={{
      position: 'relative', height: '100%', width: '100%',
      background: '#FFFFFF', overflow: 'hidden',
    }}>
      {/* viewport do scroll automático */}
      <div style={{
        position: 'absolute', inset: 0,
        paddingTop: 56,
        overflow: 'hidden',
      }}>
        <div ref={trackRef} style={{ willChange: 'transform' }}>
          <div ref={firstHalfRef}>
            <ChallengeList />
          </div>
          {/* segunda cópia idêntica pra loop seamless */}
          <ChallengeList />
        </div>
      </div>

      {/* footer fixo c/ fade gigante cobrindo a parte de baixo */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        paddingTop: 100,
        background: 'linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.92) 30%, #FFFFFF 60%)',
        pointerEvents: 'none',
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        gap: 24,
      }}>
        <h1 style={{
          fontFamily: 'Fraunces, serif',
          fontWeight: 900,
          fontSize: 56,
          lineHeight: 1.0,
          letterSpacing: '-0.04em',
          color: '#0A0A0A',
          margin: 0,
          textAlign: 'center',
          textWrap: 'pretty',
          pointerEvents: 'auto',
        }}>
          Escolha<br/>
          <span style={{ fontStyle: 'italic', fontWeight: 400 }}>seu </span>
          <em style={{ fontStyle: 'italic', fontWeight: 800 }}>desafio</em>
        </h1>

        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          gap: 12, paddingBottom: 28, pointerEvents: 'auto',
        }}>
          <button
            onClick={onNext}
            style={{
              background: '#000', color: '#FFF',
              border: 'none', borderRadius: 28,
              padding: '18px 64px',
              fontFamily: 'Inter, sans-serif',
              fontWeight: 600, fontSize: 17,
              cursor: 'pointer',
              boxShadow: '0 6px 22px rgba(0,0,0,0.22)',
              minWidth: 280,
            }}
          >Começar</button>
          <button
            onClick={onLogin}
            style={{
              background: 'transparent', border: 'none',
              fontFamily: 'Inter, sans-serif',
              fontWeight: 500, fontSize: 14,
              color: '#9B9B9B',
              textDecoration: 'underline',
              textUnderlineOffset: 3,
              cursor: 'pointer',
              padding: '4px 8px',
            }}
          >Já tenho uma conta</button>
        </div>
      </div>
    </div>
  );
}

window.Welcome = Welcome;
