// Shared visual components
const { useState, useEffect, useRef } = React;

// Árvore que cresce — SVG simples, estágios baseados em % de progresso
function ArvoreProgresso({ progresso, cor = '#6b8a5a' }) {
  // progresso: 0..1
  // estágios: 0 = semente, 1 = broto pequeno, 2 = mudinha, 3 = árvore, 4 = árvore com frutos
  const estagio = Math.min(4, Math.floor(progresso * 5));
  return (
    <svg viewBox="0 0 88 88" className="arvore" aria-label={`Árvore estágio ${estagio + 1} de 5`}>
      {/* Vaso/terra sempre */}
      <ellipse cx="44" cy="78" rx="28" ry="5" fill="#8a6a4a" opacity="0.4" />
      <path d="M 22 76 Q 22 84 30 84 L 58 84 Q 66 84 66 76 L 62 70 L 26 70 Z" fill="#a87248" />
      <rect x="24" y="68" width="40" height="4" fill="#8a5a36" rx="1" />

      {estagio === 0 && (
        // semente
        <ellipse cx="44" cy="66" rx="6" ry="4" fill="#6b4a2a" transform="rotate(-15 44 66)" />
      )}
      {estagio >= 1 && (
        <>
          {/* caule */}
          <path d={
            estagio === 1
              ? "M 44 70 Q 44 64 44 58"
              : estagio === 2
              ? "M 44 70 Q 44 60 44 48"
              : "M 44 70 Q 42 56 44 38"
          } stroke="#7a5a3a" strokeWidth={estagio === 1 ? 2 : 3} fill="none" strokeLinecap="round" />
        </>
      )}
      {estagio === 1 && (
        // duas folhinhas
        <>
          <ellipse cx="40" cy="58" rx="5" ry="3" fill={cor} transform="rotate(-30 40 58)" />
          <ellipse cx="48" cy="56" rx="5" ry="3" fill={cor} transform="rotate(30 48 56)" />
        </>
      )}
      {estagio === 2 && (
        <>
          <ellipse cx="36" cy="50" rx="8" ry="5" fill={cor} transform="rotate(-25 36 50)" />
          <ellipse cx="52" cy="48" rx="8" ry="5" fill={cor} transform="rotate(25 52 48)" />
          <ellipse cx="44" cy="42" rx="9" ry="6" fill={cor} />
        </>
      )}
      {estagio >= 3 && (
        <>
          {/* copa principal */}
          <circle cx="32" cy="36" r="14" fill={cor} opacity="0.9" />
          <circle cx="56" cy="34" r="15" fill={cor} opacity="0.95" />
          <circle cx="44" cy="26" r="14" fill={cor} />
          <circle cx="44" cy="38" r="13" fill={cor} opacity="0.92" />
          {estagio === 4 && (
            <>
              {/* frutinhas */}
              <circle cx="34" cy="32" r="2.5" fill="#c97b5e" />
              <circle cx="50" cy="28" r="2.5" fill="#c97b5e" />
              <circle cx="42" cy="40" r="2.5" fill="#c97b5e" />
              <circle cx="56" cy="38" r="2.5" fill="#c97b5e" />
              <circle cx="38" cy="42" r="2.5" fill="#e0a85a" />
            </>
          )}
        </>
      )}
    </svg>
  );
}

// Confete + estrela (animação de celebração — combina ambas)
function Celebracao({ ativo, onDone }) {
  useEffect(() => {
    if (!ativo) return;
    const t = setTimeout(() => onDone && onDone(), 2400);
    return () => clearTimeout(t);
  }, [ativo, onDone]);

  if (!ativo) return null;

  // Mix de emojis em tons da paleta Sol + emojis com cor própria que combinam
  const emojis = ['⭐', '✨', '🌟', '💫', '🌞', '🍯', '🌻', '🍃'];
  // Bolinhas e quadradinhos coloridos da paleta Sol (rendered como SVG inline)
  const cores = ['var(--solu-honey)', 'var(--solu-terracotta)', 'var(--solu-moss)', 'var(--solu-sand)', 'var(--solu-sky)'];
  const formas = ['circle', 'square', 'rect'];

  const pieces = Array.from({ length: 48 }, (_, i) => {
    const left = Math.random() * 100;
    const delay = Math.random() * 0.4;
    const dur = 1.6 + Math.random() * 0.9;
    const rot = (Math.random() * 720 - 360);
    const useEmoji = i % 2 === 0;
    if (useEmoji) {
      const emoji = emojis[i % emojis.length];
      return (
        <div
          key={i}
          className="confete-piece"
          style={{
            left: `${left}vw`,
            top: `-${Math.random() * 20}vh`,
            animationDelay: `${delay}s`,
            animationDuration: `${dur}s`,
            fontSize: `${20 + Math.random() * 18}px`,
            '--rot': `${rot}deg`,
          }}
        >
          {emoji}
        </div>
      );
    }
    const cor = cores[i % cores.length];
    const forma = formas[i % formas.length];
    const tam = 10 + Math.random() * 8;
    return (
      <div
        key={i}
        className="confete-piece confete-forma"
        style={{
          left: `${left}vw`,
          top: `-${Math.random() * 20}vh`,
          animationDelay: `${delay}s`,
          animationDuration: `${dur}s`,
          width: `${tam}px`,
          height: forma === 'rect' ? `${tam * 0.5}px` : `${tam}px`,
          borderRadius: forma === 'circle' ? '50%' : '2px',
          background: cor,
          '--rot': `${rot}deg`,
        }}
      />
    );
  });

  return (
    <>
      <div className="confete-wrap">{pieces}</div>
      <div className="estrela-grande" style={{ color: 'var(--solu-honey)' }}>☀️</div>
    </>
  );
}

window.ArvoreProgresso = ArvoreProgresso;
window.Celebracao = Celebracao;

// blur-up: a foto entra com fade + desfoque que foca quando o arquivo carrega (mascara o load no 4G).
// Trata imagem JÁ cacheada (complete) pra não travar invisível. Uso: <img {...window.blurImg()} src=... />
window.blurImg = function (extraClass) {
  return {
    className: 'foto-blur' + (extraClass ? ' ' + extraClass : ''),
    onLoad: function (e) { e.currentTarget.classList.add('carregada'); },
    ref: function (el) { if (el && el.complete && el.naturalWidth) el.classList.add('carregada'); },
  };
};

// Seletor de idioma — 3 bandeiras (pt/en/es). idioma = atual; onTrocar(id) troca.
function SeletorIdioma({ idioma, onTrocar, className }) {
  const langs = [
    { id: 'pt', flag: '🇧🇷', nome: 'Português' },
    { id: 'en', flag: '🇺🇸', nome: 'English' },
    { id: 'es', flag: '🇪🇸', nome: 'Español' },
  ];
  return (
    <div className={'seletor-idioma' + (className ? ' ' + className : '')}
         role="group" aria-label={window.t ? window.t('idioma.label') : 'Idioma'}>
      {langs.map((l) => (
        <button key={l.id} type="button"
                className={'flag-btn' + (idioma === l.id ? ' on' : '')}
                onClick={() => onTrocar && onTrocar(l.id)}
                aria-label={l.nome} aria-pressed={idioma === l.id} title={l.nome}>
          {l.flag}
        </button>
      ))}
    </div>
  );
}

window.SeletorIdioma = SeletorIdioma;
