// Tela principal: Versículo do dia com animação dos anjos + Modo aleatório
const { useState: useStateHome, useEffect: useEffectHome, useMemo: useMemoHome, useRef: useRefHome } = React;

// Renaissance cherub silhouette — minimal, elegant, monochrome gold
// Inspired by Raphael's putti: head, two wings, no body. Always faces card.
function Cherub({ side = 'left', flap = 0 }) {
  const flip = side === 'left' ? 1 : -1;
  const wingRotate = -8 + flap * 6;

  return (
    <svg viewBox="-52 -62 104 108" width="88" height="88" style={{ overflow: 'visible' }}>
      <g transform={`scale(${flip} 1)`}>

        {/* Asa traseira animada */}
        <g style={{ transformOrigin: '0px -10px', transform: `rotate(${wingRotate}deg)` }}>
          <path d="M-8,-18 C-32,-48 -48,-44 -46,-18 C-44,2 -24,4 -8,0"
            fill="#EDE8DD" stroke="#C4A96D" strokeWidth="1.2"/>
          <path d="M-8,-16 C-26,-42 -40,-38 -38,-16 C-36,0 -22,2 -8,0"
            fill="#F5F0E6" stroke="#C4A96D" strokeWidth="0.7" opacity="0.8"/>
          {/* Penas */}
          <path d="M-12,-22 C-22,-32 -30,-28 -28,-18 M-10,-14 C-18,-20 -24,-16 -22,-8"
            fill="none" stroke="#C4A96D" strokeWidth="0.6" opacity="0.5"/>
        </g>

        {/* Auréola */}
        <ellipse cx="2" cy="-46" rx="16" ry="4.5"
          fill="none" stroke="#C4A96D" strokeWidth="4.5" opacity="0.95"/>
        <ellipse cx="2" cy="-46" rx="16" ry="4.5"
          fill="none" stroke="#E8D08A" strokeWidth="2" opacity="0.6"/>

        {/* Cabelo */}
        <path d="M-14,-38 C-16,-50 -8,-56 2,-56 C12,-56 20,-50 18,-38 C12,-35 -8,-35 -14,-38"
          fill="#C4943A"/>
        <path d="M-14,-38 C-10,-42 10,-42 18,-38" fill="none" stroke="#A07830" strokeWidth="0.8" opacity="0.5"/>

        {/* Cabeça */}
        <circle cx="2" cy="-24" r="18" fill="#F5C9A8"/>

        {/* Bochechas rosadas */}
        <circle cx="-7" cy="-19" r="6" fill="#E8886A" opacity="0.18"/>
        <circle cx="11" cy="-19" r="6" fill="#E8886A" opacity="0.18"/>

        {/* Olhos azuis */}
        <ellipse cx="-5" cy="-26" rx="3.2" ry="3.8" fill="#2A5A8B"/>
        <circle cx="-3.5" cy="-27.5" r="1.1" fill="white"/>
        <ellipse cx="9" cy="-26" rx="3.2" ry="3.8" fill="#2A5A8B"/>
        <circle cx="10.5" cy="-27.5" r="1.1" fill="white"/>

        {/* Nariz */}
        <ellipse cx="2" cy="-21" rx="2.2" ry="1.6" fill="#C4806A" opacity="0.45"/>

        {/* Sorriso */}
        <path d="M-5,-15 Q2,-10 9,-15" fill="none" stroke="#8B4A3A" strokeWidth="1.8" strokeLinecap="round"/>

        {/* Corpo/robe */}
        <path d="M-14,-8 C-18,12 -15,32 -10,38 L14,38 C19,32 22,12 18,-8 C10,-13 -6,-13 -14,-8 Z"
          fill="#F8F3EA" stroke="#D4C5B0" strokeWidth="1"/>
        {/* Dobras do manto */}
        <path d="M-2,-8 C-4,8 -3,28 0,38" fill="none" stroke="#D4C5B0" strokeWidth="0.7" opacity="0.5"/>
        <path d="M8,-8 C9,8 8,28 6,38" fill="none" stroke="#D4C5B0" strokeWidth="0.7" opacity="0.5"/>

        {/* Bracinhos */}
        <ellipse cx="-19" cy="2" rx="8" ry="5" fill="#F5C9A8" transform="rotate(-25,-19,2)"/>
        <ellipse cx="23" cy="2" rx="8" ry="5" fill="#F5C9A8" transform="rotate(25,23,2)"/>

        {/* Asa frontal */}
        <path d="M14,-6 C28,2 34,18 28,30 C20,24 14,12 14,-6"
          fill="#EDE8DD" stroke="#C4A96D" strokeWidth="1" opacity="0.9"/>

      </g>
    </svg>
  );
}

// Mensagens de conforto personalizadas por tema e idioma
const COMFORT = {
  graca: {
    en: "You don't have to earn it. Grace is freely given. You are already enough, exactly as you are.",
    pt: "Você não precisa merecê-la. A graça é dada livremente. Você já é suficiente, exatamente como é.",
    es: "No tienes que ganártela. La gracia se da libremente. Ya eres suficiente, exactamente como eres."
  },
  fe: {
    en: "Your faith moves mountains. Even the smallest step forward is an act of trust in God's plan for you.",
    pt: "Sua fé move montanhas. Até o menor passo à frente é um ato de confiança no plano de Deus.",
    es: "Tu fe mueve montañas. Incluso el paso más pequeño hacia adelante es un acto de confianza en el plan de Dios."
  },
  amor: {
    en: "You are deeply and completely loved — not for what you do, but simply for who you are.",
    pt: "Você é profundamente amado — não pelo que faz, mas simplesmente por quem você é.",
    es: "Eres profunda y completamente amado — no por lo que haces, sino simplemente por quien eres."
  },
  esperanca: {
    en: "Your story is not over. The best chapters are still being written by the Author of life.",
    pt: "Sua história não acabou. Os melhores capítulos ainda estão sendo escritos pelo Autor da vida.",
    es: "Tu historia no ha terminado. Los mejores capítulos aún están siendo escritos por el Autor de la vida."
  },
  sabedoria: {
    en: "Every challenge you face is shaping you into exactly who you're meant to become.",
    pt: "Cada desafio que você enfrenta está moldando você em exatamente quem você deve se tornar.",
    es: "Cada desafío que enfrentas te está moldeando exactamente en quien estás destinado a convertirte."
  },
  paz: {
    en: "In the middle of every storm, there is a place of perfect stillness. Let this verse guide you there.",
    pt: "No meio de toda tempestade, há um lugar de perfeita quietude. Deixe este versículo guiá-lo até lá.",
    es: "En medio de toda tormenta, hay un lugar de perfecta quietud. Deja que este versículo te guíe allí."
  },
  gratidao: {
    en: "Gratitude unlocks the fullness of life. Today, even one blessing counted is enough to change everything.",
    pt: "A gratidão abre a plenitude da vida. Hoje, até uma bênção contada é suficiente para mudar tudo.",
    es: "La gratitud desbloquea la plenitud de la vida. Hoy, incluso una bendición contada es suficiente para cambiarlo todo."
  },
};

function VerseScreen({ t, lang, mode, profile, onShare, onFavToggle, isFav, onNewRandom, randomSeed, animateOnMount }) {
  const today = new Date();
  const data = useMemoHome(() => {
    if (mode === 'random') return window.getRandomVerse(randomSeed);
    return window.getVerseForDate(today);
  }, [mode, randomSeed, today.toDateString()]);

  // Reveal sequence:
  // 0 = deck closed, 1 = card lifting, 2 = card open & content visible
  const [phase, setPhase] = useStateHome(animateOnMount ? 0 : 2);
  const [flap, setFlap] = useStateHome(0);
  const cardKey = data.verse.ref.pt + mode;
  const isFirstRender = useRefHome(true);

  useEffectHome(() => {
    // Re-rolls no modo especial pulam a animação — botão sempre visível
    if (mode === 'random' && !isFirstRender.current) {
      setPhase(2);
      return;
    }
    isFirstRender.current = false;
    if (!animateOnMount) { setPhase(2); return; }
    setPhase(0);
    const t1 = setTimeout(() => setPhase(1), 350);
    const t2 = setTimeout(() => setPhase(2), 2150);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [cardKey, animateOnMount]);

  // Wing flap loop while phase 1
  useEffectHome(() => {
    if (phase !== 1) return;
    let raf, start = performance.now();
    const tick = (now) => {
      setFlap(0.5 + 0.5 * Math.sin((now - start) / 320));
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [phase]);

  const themeName = data.theme[lang];
  const dateLabel = mode === 'random'
    ? t.special_verse
    : `${t.days[today.getDay()]}, ${today.getDate()} ${t.months[today.getMonth()]}`;

  const verseText = data.verse[lang];
  const verseRef = data.verse.ref[lang];
  const fav = isFav(verseRef);

  const cardStyle = {
    '--card-paper': data.theme.paper,
    '--card-edge': data.theme.edge,
    '--card-accent': data.theme.accent,
    '--card-ink': data.theme.ink,
    '--card-glow': data.theme.glow,
  };

  return (
    <div className={'mv-verse-scr mv-verse-themed phase-' + phase + (phase >= 2 ? ' is-on' : '')} style={cardStyle}>
      <div className="mv-verse-head">
        <span className="mv-theme-pill"><span className="mv-theme-icon">{data.theme.icon}</span>{themeName}</span>
        <span className="mv-date">{dateLabel}</span>
      </div>

      <div className="mv-stage-area">
        {/* Glow halo behind the rising card */}
        <div className="mv-stage-glow" />

        {/* Deck of background cards (other days) */}
        <div className="mv-deck">
          {[0, 1, 2, 3, 4, 5].map(i => {
            const t2 = window.THEMES[(data.theme.day + i + 1) % 7];
            return (
              <div key={i} className="mv-deck-card" style={{
                '--idx': i,
                '--paper': t2.paper,
                '--edge': t2.edge,
              }}>
                <span className="mv-deck-icon" style={{ color: t2.accent }}>{t2.icon}</span>
              </div>
            );
          })}
        </div>

        {/* Two angels — appear when phase >= 1 */}
        <div className="mv-angel mv-angel-l">
          <Cherub side="left" flap={flap} />
        </div>
        <div className="mv-angel mv-angel-r">
          <Cherub side="right" flap={flap} />
        </div>

        {/* The featured verse card — being lifted */}
        <div className="mv-card mv-card-featured" key={cardKey}>
          <div className="mv-card-inner">
            <span className="mv-card-corner top-l" aria-hidden>{data.theme.icon}</span>
            <span className="mv-card-corner top-r" aria-hidden>{data.theme.icon}</span>
            <span className="mv-card-corner bot-l" aria-hidden>{data.theme.icon}</span>
            <span className="mv-card-corner bot-r" aria-hidden>{data.theme.icon}</span>
            <span className="mv-card-quote" aria-hidden>"</span>
            <p className="mv-card-text">{verseText}</p>
            <p className="mv-card-ref">{verseRef}</p>
            <span className="mv-card-rule" aria-hidden />
            <span className="mv-card-theme">{themeName}</span>
          </div>
        </div>
      </div>

      <div className="mv-verse-actions">
        {phase >= 2 && COMFORT[data.theme.id]?.[lang] && (
          <p className="mv-comfort-msg">
            {COMFORT[data.theme.id][lang]}
          </p>
        )}
        {mode === 'random' ? (
          <button className="mv-action-btn mv-action-primary" onClick={onNewRandom}>
            <span aria-hidden>↻</span> {t.new_verse}
          </button>
        ) : (
          <span className="mv-greeting">
            {profile?.name ? `${greetingFor(today, lang)}, ${profile.name.split(' ')[0]}.` : greetingFor(today, lang) + '.'}
          </span>
        )}
        <div className="mv-action-row">
          <button className={'mv-icon-btn' + (fav ? ' is-on' : '')} onClick={() => {
            const currentData = mode === 'random' ? window.getRandomVerse(randomSeed) : window.getVerseForDate(new Date());
            const currentRef = currentData.verse.ref[lang];
            const currentText = currentData.verse[lang];
            const currentTheme = currentData.theme.id;
            onFavToggle({ verse_ref: currentRef, theme_id: currentTheme, text: currentText });
          }} aria-label="favorite">
            {fav ? '♥' : '♡'}
          </button>
          <button className="mv-icon-btn" onClick={() => onShare({ text: verseText, ref: verseRef, theme: themeName, themeId: data.theme.id })} aria-label="share">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
              <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>
              <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

function greetingFor(d, lang) {
  const h = d.getHours();
  const map = {
    pt: ['Boa noite', 'Bom dia', 'Boa tarde', 'Boa noite'],
    en: ['Good night', 'Good morning', 'Good afternoon', 'Good evening'],
    es: ['Buenas noches', 'Buenos días', 'Buenas tardes', 'Buenas noches'],
  }[lang];
  if (h < 5) return map[0];
  if (h < 12) return map[1];
  if (h < 18) return map[2];
  return map[3];
}

Object.assign(window, { VerseScreen });
