// Rewnd — 6 app screens matching the real app spec
// Tabs: Até Aqui · Perguntas · Elenco · Contexto · Chat · Você Pode Gostar

const BRAND = {
  ink: '#1A1A17', shell: '#242420', card1: '#2E2E26', card2: '#383831',
  line: 'rgba(255,255,255,0.06)', lineStrong: '#45443C',
  ember: '#C4944A', emberHi: '#D9B36B',
  cream: '#FFFFFF', mute1: '#BFB9AD', mute2: '#8C877A', mute3: '#66615A',
  shield: '#73B873', warn: '#D98C4D',
};

const Uppercase = ({ children, color = BRAND.mute3, size = 10 }) => (
  <div style={{ fontSize: size, letterSpacing: 1.6, color, textTransform: 'uppercase', fontWeight: 600 }}>{children}</div>
);

function ShieldBadge({ label = 'Conteúdo limitado até E04', small = false }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: small ? 6 : 8, fontSize: small ? 11 : 12, color: BRAND.mute1 }}>
      <span style={{ width: small ? 6 : 8, height: small ? 6 : 8, borderRadius: 99, background: BRAND.shield,
        boxShadow: `0 0 0 ${small ? 2 : 3}px rgba(115,184,115,0.22)` }}/>
      {label}
    </div>
  );
}

function PillTabs({ active = 0 }) {
  const tabs = ['Até Aqui', 'Perguntas', 'Elenco', 'Contexto', 'Chat', 'Você Pode Gostar'];
  return (
    <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '0 20px', marginBottom: 4, scrollbarWidth: 'none' }}>
      {tabs.map((t, i) => (
        <div key={t} style={{
          padding: '8px 14px', borderRadius: 99, fontSize: 13, fontWeight: i === active ? 600 : 500,
          background: i === active ? BRAND.ember : BRAND.card1,
          color: i === active ? BRAND.ink : BRAND.mute1,
          whiteSpace: 'nowrap', flexShrink: 0,
        }}>{t}</div>
      ))}
    </div>
  );
}

// ── REAL POSTERS (TVMaze API, fetched client-side, CORS-enabled) ──
// We cache by query → image URL in localStorage to avoid re-fetching on every reload.
const POSTER_QUERIES = {
  banner:     'under the banner of heaven',
  dark:       'dark',
  severance:  'severance',
  bear:       'the bear',
  succession: 'succession',
  wire:       'the wire',
  yellow:     'yellowjackets',
  wolf:       'wolf hall',
  got:        'game of thrones',
};

const posterCache = (() => {
  try { return JSON.parse(localStorage.getItem('rewnd_posters') || '{}'); }
  catch { return {}; }
})();
const savePosterCache = () => {
  try { localStorage.setItem('rewnd_posters', JSON.stringify(posterCache)); } catch {}
};

function usePoster(tone) {
  const q = POSTER_QUERIES[tone];
  const [src, setSrc] = React.useState(posterCache[q] || null);
  React.useEffect(() => {
    if (!q || posterCache[q]) return;
    let alive = true;
    fetch(`https://api.tvmaze.com/singlesearch/shows?q=${encodeURIComponent(q)}`)
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (!alive || !data || !data.image) return;
        const url = data.image.original || data.image.medium;
        if (url) {
          posterCache[q] = url;
          savePosterCache();
          setSrc(url);
        }
      })
      .catch(() => {});
    return () => { alive = false; };
  }, [q]);
  return src;
}

function Poster({ w = 140, h = 200, tone = 'banner', kenBurns = false, overlay = false, title, subtitle }) {
  const src = usePoster(tone);
  return (
    <div style={{
      width: w, height: h, borderRadius: 10, flexShrink: 0,
      position: 'relative', overflow: 'hidden',
      boxShadow: 'inset 0 0 0 0.5px rgba(255,255,255,0.08)',
      background: `linear-gradient(180deg,#2e2e26,#1a1a17)`,
    }}>
      {src && (
        <img src={src} alt="" loading="lazy"
          style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover',
            animation: kenBurns ? 'kb 14s ease-in-out infinite alternate' : 'none' }}/>
      )}
      {!src && (
        <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <div style={{ width: 28, height: 28, border: `2px solid ${BRAND.ember}40`, borderTopColor: BRAND.ember,
            borderRadius: 99, animation: 'spin 1s linear infinite' }}/>
        </div>
      )}
      {overlay && <div style={{ position:'absolute', inset:0,
        background:'linear-gradient(180deg,transparent 45%,rgba(15,12,10,0.85) 100%)' }}/>}
      {(title || subtitle) && (
        <div style={{ position: 'absolute', bottom: 10, left: 10, right: 10 }}>
          {subtitle && <div style={{ fontSize: 9, color: BRAND.ember, letterSpacing: 1.2, fontWeight: 600, marginBottom: 4 }}>{subtitle}</div>}
          <div style={{ fontSize: 12, fontWeight: 600, color: BRAND.cream, lineHeight: 1.15, letterSpacing: -0.2 }}>{title}</div>
        </div>
      )}
    </div>
  );
}

// ── Screen 1 · HOME (with horizontal scroll episodes + shield tied to selected ep) ──
function ScreenHome() {
  const [ep, setEp] = React.useState(4);
  const bannerSrc = usePoster('banner');
  return (
    <div style={{ background: BRAND.shell, minHeight: '100%', color: BRAND.cream, paddingBottom: 40 }}>
      <div style={{ padding: '62px 20px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 11, color: BRAND.mute2, letterSpacing: 1.3, marginBottom: 4 }}>SEXTA · 23H04</div>
          <div style={{ fontFamily: '"Instrument Serif", serif', fontStyle: 'italic', fontSize: 24, letterSpacing: -0.4, lineHeight: 1.1 }}>
            Oi Enrique, vamos <span style={{ color: BRAND.ember }}>assistir?</span>
          </div>
        </div>
      </div>

      <div style={{ padding: '8px 20px 20px', display: 'flex', justifyContent: 'center' }}>
        <div style={{ position: 'relative', width: 260, height: 350, animation: 'float 6s ease-in-out infinite' }}>
          <Poster tone="banner" w={260} h={350} kenBurns={true} overlay={true}/>
          <div style={{ position: 'absolute', bottom: 16, left: 14, right: 14 }}>
            <div style={{ fontSize: 10, color: BRAND.ember, letterSpacing: 1.4, fontWeight: 600, marginBottom: 6 }}>FX · MINISSÉRIE · 7 EPISÓDIOS</div>
            <div style={{ fontFamily: '"Instrument Serif", serif', fontStyle: 'italic', fontSize: 28, lineHeight: 1.0, letterSpacing: -0.5, color: BRAND.cream }}>Under the Banner<br/>of Heaven</div>
          </div>
        </div>
      </div>

      <div style={{ padding: '0 20px 16px' }}>
        <div style={{ fontSize: 13, color: BRAND.mute1, lineHeight: 1.55, marginBottom: 12, textWrap: 'pretty' }}>
          Um detetive mórmon investiga um assassinato que abala sua fé. Baseado em fatos reais.
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {['Drama', 'True crime', 'Religião'].map(g => (
            <div key={g} style={{ padding: '4px 10px', borderRadius: 99, background: BRAND.card1, fontSize: 11, color: BRAND.mute1 }}>{g}</div>
          ))}
        </div>
      </div>

      <div style={{ padding: '12px 20px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Temporada 1 · Episódios</div>
        <div style={{ fontSize: 11, color: BRAND.mute2 }}>Você está no E{String(ep).padStart(2,'0')}</div>
      </div>
      {/* horizontal scroll */}
      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '4px 20px 16px',
        scrollbarWidth: 'none', WebkitOverflowScrolling: 'touch' }}>
        {[1,2,3,4,5,6,7].map(i => (
          <div key={i} style={{ flexShrink: 0, width: 88, cursor: 'pointer' }} onClick={() => setEp(i)}>
            <div style={{
              width: 88, height: 56, borderRadius: 8, overflow:'hidden',
              border: i === ep ? `2px solid ${BRAND.ember}` : `0.5px solid ${BRAND.line}`,
              position: 'relative', filter: i > ep ? 'brightness(0.4) saturate(0.5)' : 'none',
              background: BRAND.card1,
              transition: 'all 0.2s ease',
            }}>
              {bannerSrc && <img src={bannerSrc} alt="" style={{ width:'100%', height:'100%', objectFit:'cover', objectPosition:`${(i-1)*16}% 30%` }}/>}
              {i > ep && <div style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', background:'rgba(0,0,0,0.55)' }}>
                <svg width="12" height="14" viewBox="0 0 12 14"><path d="M2 6V4a4 4 0 018 0v2M1 6h10v7H1z" fill="none" stroke={BRAND.mute1} strokeWidth="1.2"/></svg>
              </div>}
              {i === ep && <div style={{ position:'absolute', top:4, right:4, width:8, height:8, borderRadius:99, background:BRAND.ember, boxShadow:`0 0 0 2px rgba(196,148,74,0.3)`, animation:'pulse 2s ease-in-out infinite' }}/>}
            </div>
            <div style={{ fontSize: 10, color: i === ep ? BRAND.ember : BRAND.mute2, marginTop: 4, textAlign: 'center', fontWeight: i === ep ? 600 : 400 }}>E{String(i).padStart(2,'0')}</div>
          </div>
        ))}
      </div>

      <div style={{ padding: '8px 20px' }}>
        <div style={{ background: BRAND.ember, color: BRAND.ink, padding: '14px 16px', borderRadius: 14,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontWeight: 600, fontSize: 14,
          cursor: 'pointer', animation: 'ctaPulse 2.4s ease-in-out infinite' }}
          onClick={() => { if (window.__scrollScreens) window.__scrollScreens(); }}>
          <span>Consultar Episódio {ep}</span>
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M4 2l5 5-5 5" stroke={BRAND.ink} strokeWidth="2" fill="none" strokeLinecap="round"/></svg>
        </div>
        <div style={{ textAlign:'center', marginTop: 10 }}>
          <ShieldBadge label={`Conteúdo limitado até E${String(ep).padStart(2,'0')}`}/>
        </div>
      </div>
    </div>
  );
}

// ── Screen 2 · PERGUNTAS ─────────────────────────
function ScreenPerguntas() {
  const [openIdx, setOpenIdx] = React.useState(0);
  const qs = [
    { q: 'O que é Blood Atonement?', a: 'Doutrina mórmon extrema que Ron está invocando para justificar violência contra membros que ele considera "pecadores". Apresentada ao espectador através de uma pregação tensa em família no E04.', src: 'Reddit · 412 menções' },
    { q: 'Quem é o Profeta Onias?', a: 'Personagem apresentado brevemente no jantar do E02. É um líder não-oficial — fundamentalistas o seguem por "revelação pessoal", não porque a igreja o ordenou.', src: 'IMDb · 287 menções' },
    { q: 'Por que Brenda é vista como ameaça?', a: 'Ela é jornalista e questiona abertamente a hierarquia da família. Para os irmãos mais radicalizados, isso é subversão direta à autoridade masculina.', src: 'Reddit · 198 menções' },
    { q: 'O que é "revelação pessoal"?', a: 'Conceito central do mormonismo — fundamentalistas acreditam receber mensagens diretas de Deus, sem intermediação da igreja. No E03 isso é usado para justificar desde mudanças de rota até violência.', src: 'Fóruns · 156 menções' },
  ];
  return (
    <div style={{ background: BRAND.shell, minHeight: '100%', color: BRAND.cream }}>
      <div style={{ padding: '58px 20px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 15, fontWeight: 600 }}>Under the Banner of Heaven</div>
        <ShieldBadge label="E04" small/>
      </div>
      <div style={{ padding: '4px 20px 14px' }}>
        <Uppercase>Episódio 4 · Church and State</Uppercase>
      </div>
      <PillTabs active={1}/>
      <div style={{ padding: '16px 20px 4px' }}>
        <Uppercase size={11}>As dúvidas mais comuns desse episódio</Uppercase>
      </div>
      <div style={{ padding: '10px 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {qs.map((x, i) => {
          const open = i === openIdx;
          return (
            <div key={i} onClick={() => setOpenIdx(open ? -1 : i)}
              style={{ background: BRAND.card1, borderRadius: 14, padding: 14, cursor:'pointer',
                border: open ? `1px solid ${BRAND.lineStrong}` : '1px solid transparent',
                transition: 'all 0.25s ease',
                animation: (!open && i === 1) ? 'cardHint 2.8s ease-in-out infinite' : 'none' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: -0.2, lineHeight: 1.25 }}>{x.q}</div>
                  {open && (
                    <div style={{ fontSize: 13, color: BRAND.mute1, lineHeight: 1.55, marginTop: 8, textWrap: 'pretty',
                      animation: 'fadeUp 0.3s ease-out' }}>
                      {x.a}
                    </div>
                  )}
                  <div style={{ fontSize: 10, color: BRAND.mute3, marginTop: 8, letterSpacing: 0.8 }}>{x.src}</div>
                </div>
                <svg width="11" height="11" viewBox="0 0 11 11"
                  style={{ marginTop: 4, transform: open ? 'rotate(45deg)' : 'none', transition: 'transform 0.25s ease',
                    animation: open ? 'none' : 'chevronHint 1.8s ease-in-out infinite' }}>
                  <path d="M5.5 1v9M1 5.5h9" stroke={BRAND.mute2} strokeWidth="1.5" strokeLinecap="round"/>
                </svg>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ padding: '16px 20px 24px' }}>
        <ShieldBadge/>
      </div>
    </div>
  );
}

// ── Screen 3 · ELENCO ────────────────────────────
function ScreenElenco() {
  const chars = [
    { n: 'Jeb Pyre', a: 'Andrew Garfield', c: BRAND.ember, desc: 'Detetive, SLC PD. Em crise de fé.', status: 'Visto no E04' },
    { n: 'Brenda Wright Lafferty', a: 'Daisy Edgar-Jones', c: '#6B8BA8', desc: 'Jornalista, esposa de Allen. Questiona a família.', status: 'Desde o E01' },
    { n: 'Ron Lafferty', a: 'Sam Worthington', c: '#C96A58', desc: 'Irmão mais velho. Radicalizado no E03.', status: 'Visto no E03' },
    { n: 'Dan Lafferty', a: 'Wyatt Russell', c: '#B07C3E', desc: 'Segundo irmão. Seguidor de Ron.', status: 'Visto no E03' },
    { n: 'Allen Lafferty', a: 'Billy Howle', c: '#7FC085', desc: 'Marido de Brenda. Sob custódia.', status: 'Desde o E01' },
    { n: 'Bill Taba', a: 'Gil Birmingham', c: '#8F7AB8', desc: 'Parceiro de Jeb. Detetive Paiute.', status: 'Desde o E01' },
  ];
  return (
    <div style={{ background: BRAND.shell, minHeight: '100%', color: BRAND.cream }}>
      <div style={{ padding: '58px 20px 10px' }}>
        <div style={{ fontSize: 15, fontWeight: 600 }}>Under the Banner of Heaven</div>
        <Uppercase>Episódio 4 · 6 personagens apresentados</Uppercase>
      </div>
      <PillTabs active={2}/>
      <div style={{ padding: '14px 20px 24px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {chars.map((p, i) => (
          <div key={i} style={{ background: BRAND.card1, borderRadius: 14, padding: 12,
            display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 44, height: 44, borderRadius: 99, flexShrink: 0,
              background: `radial-gradient(70% 70% at 30% 25%, ${p.c}, ${p.c}90)`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 16, fontWeight: 600, color: BRAND.ink,
              boxShadow: `0 2px 12px ${p.c}40`,
            }}>{p.n[0]}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: -0.15 }}>{p.n}</div>
              <div style={{ fontSize: 11, color: BRAND.mute2, marginTop: 2 }}>{p.a}</div>
              <div style={{ fontSize: 12, color: BRAND.mute1, marginTop: 5, lineHeight: 1.4 }}>{p.desc}</div>
            </div>
            <div style={{ fontSize: 9, color: BRAND.mute3, flexShrink: 0, letterSpacing: 0.6 }}>{p.status}</div>
          </div>
        ))}
      </div>
      <div style={{ padding: '8px 20px 24px' }}>
        <ShieldBadge/>
      </div>
    </div>
  );
}

// ── Screen 4 · CHAT (interactive input) ──────────
const CHAT_ANSWERS = [
  { trigger: ['jantar', 'onias', 'profeta'], a: 'É o Profeta Onias, um líder não-oficial apresentado no E02. Fundamentalistas o seguem por "revelação pessoal" — não é ordenado pela igreja.', warn: false },
  { trigger: ['brenda', 'morre', 'morrer', 'morre a'], a: 'Isso será abordado mais pra frente — continue assistindo.', warn: true },
  { trigger: ['ron', 'radical'], a: 'Ron Lafferty é o irmão mais velho, radicalizado ao longo do E03. No E04 você vê ele invocando Blood Atonement pela primeira vez em família.', warn: false },
  { trigger: ['blood atonement', 'atonement'], a: 'Doutrina mórmon extrema usada por Ron para justificar violência. Apresentada numa pregação tensa no jantar do E04.', warn: false },
  { trigger: ['jeb', 'detetive'], a: 'Jeb Pyre é o detetive protagonista. Mórmon devoto investigando um crime dentro da própria comunidade — o conflito entre fé e dever é o eixo da série.', warn: false },
  { trigger: ['lafferty'], a: 'A família Lafferty: Allen (marido de Brenda, sob custódia), Ron (mais velho, radicalizado), Dan (segue Ron), e mais três irmãos que aparecem depois do E04.', warn: false },
];
function ScreenChat() {
  const [messages, setMessages] = React.useState([
    { role: 'user', text: 'Quem era aquele cara no jantar do começo do episódio?' },
    { role: 'bot',  text: 'É o Profeta Onias, um líder não-oficial apresentado rapidamente no E02. Não é ordenado pela igreja — fundamentalistas o seguem por "revelação pessoal".', warn: false },
  ]);
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const [placeholder, setPlaceholder] = React.useState('');
  const scrollRef = React.useRef(null);
  const hints = ['Pergunte qualquer coisa…', 'O que é Blood Atonement?', 'Quem é o Ron Lafferty?', 'Por que Brenda é ameaça?'];
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, typing]);
  React.useEffect(() => {
    if (input.length > 0) { setPlaceholder(''); return; }
    let hintIdx = 0, charIdx = 0, deleting = false, timeout;
    const tick = () => {
      const full = hints[hintIdx];
      if (!deleting) {
        charIdx++;
        setPlaceholder(full.slice(0, charIdx));
        if (charIdx === full.length) { deleting = true; timeout = setTimeout(tick, 1600); return; }
      } else {
        charIdx--;
        setPlaceholder(full.slice(0, charIdx));
        if (charIdx === 0) { deleting = false; hintIdx = (hintIdx + 1) % hints.length; }
      }
      timeout = setTimeout(tick, deleting ? 32 : 52);
    };
    timeout = setTimeout(tick, 400);
    return () => clearTimeout(timeout);
  }, [input]);

  const send = () => {
    const q = input.trim();
    if (!q) return;
    setInput('');
    setMessages(m => [...m, { role: 'user', text: q }]);
    setTyping(true);
    setTimeout(() => {
      const lower = q.toLowerCase();
      const match = CHAT_ANSWERS.find(a => a.trigger.some(t => lower.includes(t)));
      const reply = match || { a: 'Essa é uma boa pergunta sobre esse episódio. Posso te contar mais sobre Blood Atonement, o Profeta Onias, ou os personagens que aparecem no E04.', warn: false };
      setMessages(m => [...m, { role: 'bot', text: reply.a, warn: reply.warn }]);
      setTyping(false);
    }, 900);
  };

  return (
    <div style={{ background: BRAND.shell, minHeight: '100%', color: BRAND.cream, display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '58px 20px 10px' }}>
        <div style={{ fontSize: 15, fontWeight: 600 }}>Under the Banner of Heaven</div>
        <Uppercase>Chat livre · E04</Uppercase>
      </div>
      <PillTabs active={4}/>
      <div ref={scrollRef} style={{ flex: 1, padding: '14px 20px', display: 'flex', flexDirection: 'column', gap: 12, overflowY: 'auto' }}>
        {messages.map((m, i) => {
          if (m.role === 'user') return (
            <div key={i} style={{ alignSelf: 'flex-end', maxWidth: '78%', background: BRAND.ember, color: BRAND.ink,
              padding: '10px 14px', borderRadius: 18, borderBottomRightRadius: 6,
              fontSize: 14, lineHeight: 1.35, fontWeight: 500,
              animation: 'fadeUp 0.25s ease-out' }}>{m.text}</div>
          );
          return (
            <div key={i} style={{ alignSelf: 'flex-start', maxWidth: '84%',
              background: m.warn ? 'rgba(217,140,77,0.1)' : BRAND.card1,
              border: m.warn ? `1px solid ${BRAND.warn}40` : 'none',
              padding: '12px 14px 10px', borderRadius: 18, borderBottomLeftRadius: 6,
              animation: 'fadeUp 0.25s ease-out' }}>
              <Uppercase color={m.warn ? BRAND.warn : BRAND.ember} size={10}>Rewnd{m.warn ? '' : ' · Sem spoiler'}</Uppercase>
              <div style={{ fontSize: 13.5, lineHeight: 1.55, color: BRAND.cream, marginTop: 6, textWrap: 'pretty' }}>
                {m.text}
              </div>
            </div>
          );
        })}
        {typing && (
          <div style={{ alignSelf: 'flex-start', background: BRAND.card1,
            padding: '14px 18px', borderRadius: 18, borderBottomLeftRadius: 6,
            display:'flex', gap: 4, alignItems:'center' }}>
            {[0,1,2].map(i => (
              <div key={i} style={{ width: 6, height: 6, borderRadius: 99, background: BRAND.mute1,
                animation: `typing 1.2s ${i*0.15}s ease-in-out infinite` }}/>
            ))}
          </div>
        )}
      </div>
      <div style={{ padding: '10px 16px 34px' }}>
        <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{
          background: 'rgba(255,255,255,0.06)',
          backdropFilter: 'blur(20px)',
          borderRadius: 24, padding: '10px 10px 10px 14px',
          display: 'flex', alignItems: 'center', gap: 10,
          border: `0.5px solid rgba(255,255,255,0.1)`,
          animation: 'ctaPulse 3s ease-in-out infinite',
        }}>
          <div style={{ flex: 1, position: 'relative', display: 'flex', alignItems: 'center' }}>
            <input value={input} onChange={e => setInput(e.target.value)}
              placeholder=""
              style={{ flex: 1, fontSize: 14, color: BRAND.cream, background: 'transparent', border: 'none', outline: 'none',
                fontFamily: 'inherit', width: '100%' }}/>
            {input.length === 0 && (
              <div style={{ position: 'absolute', left: 0, top: '50%', transform: 'translateY(-50%)',
                pointerEvents: 'none', color: BRAND.mute2, fontSize: 14, display: 'flex', alignItems: 'center' }}>
                {placeholder}
                <span style={{ display: 'inline-block', width: 1.5, height: 14, background: BRAND.ember, marginLeft: 2,
                  animation: 'caretBlink 1s steps(1) infinite' }}/>
              </div>
            )}
          </div>
          <button type="submit" style={{ width: 30, height: 30, borderRadius: 99, background: BRAND.ember,
            display: 'flex', alignItems: 'center', justifyContent: 'center', border: 'none', cursor: 'pointer',
            flexShrink: 0 }}>
            <svg width="12" height="12" viewBox="0 0 12 12"><path d="M6 10V2M2 6l4-4 4 4" stroke={BRAND.ink} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </form>
      </div>
    </div>
  );
}

// ── Screen 5 · CONTEXTO (expandable) ─────────────
function ScreenContexto() {
  const [openIdx, setOpenIdx] = React.useState(0);
  const blocks = [
    { icon: '◐', label: 'Geografia', title: 'Salt Lake City, Utah', body: 'Capital do estado de Utah, onde 80% da população era mórmon em 1984. A série retrata como a hierarquia informal da Igreja SUD influenciava desde decisões familiares até investigações policiais — Jeb Pyre é um detetive mórmon num departamento mórmon investigando um crime numa família mórmon.' },
    { icon: '▲', label: 'Religião', title: 'Fundamentalismo mórmon', body: 'Dissidência radical que manteve a poligamia após a igreja oficial aboli-la em 1890. Fundamentalistas rejeitam a hierarquia SUD e seguem líderes que alegam "revelação pessoal" direta de Deus — o que dá margem para abusos. Os Lafferty caem nessa linha ao longo do E03.' },
    { icon: '◆', label: 'Histórico', title: '1984 · contexto', body: 'Reagan é reeleito. A seita Lafferty opera em paralelo a outras comunidades fundamentalistas no oeste dos EUA. O FBI ainda não tratava esses grupos como prioridade — é nesse vácuo que o crime da série acontece.' },
    { icon: '●', label: 'Curiosidade', title: 'Livro-fonte', body: 'Adaptação do livro homônimo de Jon Krakauer (2003), que mistura o caso Lafferty com a história do mormonismo desde Joseph Smith. Dustin Lance Black (Milk) adaptou pra TV.' },
  ];
  return (
    <div style={{ background: BRAND.shell, minHeight: '100%', color: BRAND.cream }}>
      <div style={{ padding: '58px 20px 10px' }}>
        <div style={{ fontSize: 15, fontWeight: 600 }}>Under the Banner of Heaven</div>
        <Uppercase>O que a série não te explica</Uppercase>
      </div>
      <PillTabs active={3}/>
      <div style={{ padding: '16px 20px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {blocks.map((b, i) => {
          const open = i === openIdx;
          return (
            <div key={i} onClick={() => setOpenIdx(open ? -1 : i)}
              style={{ background: BRAND.card1, borderRadius: 14, padding: 14, cursor: 'pointer',
                border: open ? `1px solid ${BRAND.lineStrong}` : '1px solid transparent',
                transition: 'all 0.25s ease',
                animation: (!open && i === 1) ? 'cardHint 2.8s ease-in-out infinite' : 'none' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ width: 28, height: 28, borderRadius: 7, background: BRAND.card2,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: BRAND.ember, fontSize: 14 }}>{b.icon}</div>
                  <div>
                    <Uppercase size={9}>{b.label}</Uppercase>
                    <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2, letterSpacing: -0.15 }}>{b.title}</div>
                  </div>
                </div>
                <svg width="11" height="11" viewBox="0 0 11 11" style={{ transform: open ? 'rotate(45deg)' : 'none', transition: 'transform 0.25s ease', animation: open ? 'none' : 'chevronHint 1.8s ease-in-out infinite' }}>
                  <path d="M5.5 1v9M1 5.5h9" stroke={BRAND.mute2} strokeWidth="1.5" strokeLinecap="round"/>
                </svg>
              </div>
              {open && (
                <div style={{ fontSize: 13, color: BRAND.mute1, lineHeight: 1.6, marginTop: 12, textWrap: 'pretty',
                  animation: 'fadeUp 0.3s ease-out' }}>
                  {b.body}
                </div>
              )}
            </div>
          );
        })}
      </div>
      <div style={{ padding: '8px 20px 24px' }}>
        <ShieldBadge/>
      </div>
    </div>
  );
}

// ── Screen 6 · VOCÊ PODE GOSTAR ──────────────────
function ScreenVoceVaiGostar() {
  const recs = [
    { t: 'Dark',           s: 'Netflix',    c: '#E50914', tone: 'dark', sz: '3 temporadas' },
    { t: 'The Wire',       s: 'HBO Max',    c: '#8B1FD1', tone: 'wire', sz: '5 temporadas' },
    { t: 'Severance',      s: 'Apple TV+',  c: '#000',    tone: 'severance', sz: '2 temporadas' },
    { t: 'The Bear',       s: 'Disney+',    c: '#0067B8', tone: 'bear', sz: '3 temporadas' },
    { t: 'Succession',     s: 'HBO Max',    c: '#8B1FD1', tone: 'succession', sz: '4 temporadas' },
    { t: 'Yellowjackets',  s: 'Paramount+', c: '#0064FF', tone: 'yellow', sz: '2 temporadas' },
    { t: 'Wolf Hall',      s: 'Disney+',    c: '#0067B8', tone: 'wolf', sz: '2 temporadas' },
    { t: 'Game of Thrones',s: 'HBO Max',    c: '#8B1FD1', tone: 'got',    sz: '8 temporadas' },
  ];
  return (
    <div style={{ background: BRAND.shell, minHeight: '100%', color: BRAND.cream }}>
      <div style={{ padding: '58px 20px 10px' }}>
        <div style={{ fontSize: 15, fontWeight: 600 }}>Under the Banner of Heaven</div>
        <Uppercase>O que assistir depois</Uppercase>
      </div>
      <PillTabs active={5}/>
      <div style={{ padding: '16px 20px 32px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {recs.map((r, i) => (
          <div key={i}>
            <div style={{ position: 'relative' }}>
              <Poster tone={r.tone} w={'100%'} h={210}/>
              <div style={{ position: 'absolute', top: 8, left: 8, padding: '4px 8px', borderRadius: 6,
                background: r.c, color: '#fff', fontSize: 9, fontWeight: 700, letterSpacing: 0.5,
                textTransform: 'uppercase' }}>{r.s}</div>
            </div>
            <div style={{ fontSize: 13, fontWeight: 600, marginTop: 8, letterSpacing: -0.1 }}>{r.t}</div>
            <div style={{ fontSize: 10, color: BRAND.mute2, marginTop: 2 }}>{r.sz}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Siri Discovery Popup ─────────────────────────
function ScreenSiri() {
  const [dismissed, setDismissed] = React.useState(false);
  return (
    <div style={{ background: BRAND.shell, minHeight: '100%', color: BRAND.cream, position: 'relative', overflow:'hidden' }}>
      <div style={{ padding: '58px 20px 10px', opacity: dismissed ? 1 : 0.3, filter: dismissed ? 'none' : 'blur(2px)', transition: 'opacity 0.4s ease, filter 0.4s ease' }}>
        <div style={{ fontSize: 15, fontWeight: 600 }}>Under the Banner of Heaven</div>
        <Uppercase>Episódio 4</Uppercase>
        <div style={{ marginTop: 20, height: 180, background: BRAND.card1, borderRadius: 14 }}/>
        <div style={{ marginTop: 10, height: 120, background: BRAND.card1, borderRadius: 14 }}/>
      </div>
      {!dismissed && (
        <div style={{ position: 'absolute', left: 16, right: 16, top: 180,
          borderRadius: 22, padding: 3,
          background: 'conic-gradient(from var(--grad-angle, 0deg), #8A7BE8, #5EA9E8, #7FC085, #E8A6C4, #8A7BE8)',
          animation: 'gradRotate 3s linear infinite, float 5s ease-in-out infinite',
        }}>
          <div style={{ background: BRAND.card1, borderRadius: 20, padding: 22, textAlign: 'center' }}>
            <div style={{ width: 56, height: 56, margin: '0 auto 14px', borderRadius: 99,
              background: 'conic-gradient(from var(--grad-angle, 0deg), #8A7BE8, #5EA9E8, #7FC085, #E8A6C4, #8A7BE8)',
              animation: 'gradRotate 1.8s linear infinite, orb-pulse 2.5s ease-in-out infinite',
              display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <div style={{ width: 48, height: 48, borderRadius: 99, background: BRAND.card1,
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20 }}>✦</div>
            </div>
            <div style={{ fontSize: 11, color: BRAND.ember, letterSpacing: 1.4, fontWeight: 600, marginBottom: 6 }}>DICA · SIRI</div>
            <div style={{ fontFamily: '"Instrument Serif", serif', fontStyle: 'italic', fontSize: 22, lineHeight: 1.15, letterSpacing: -0.3, marginBottom: 10 }}>
              Pergunte sem tirar os olhos da TV.
            </div>
            <div style={{ fontSize: 13, color: BRAND.mute1, lineHeight: 1.5, marginBottom: 16, textWrap: 'pretty' }}>
              "Siri, quem é o Jeb Pyre no Rewnd?"
            </div>
            <div onClick={() => setDismissed(true)} style={{ padding: '12px 20px', borderRadius: 12, background: BRAND.ember,
              color: BRAND.ink, fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>Entendi</div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  ScreenHome, ScreenPerguntas, ScreenElenco, ScreenChat, ScreenContexto, ScreenVoceVaiGostar, ScreenSiri,
  BRAND,
});
