// ═══ Cinema · catálogo do navio (Jellyfin) ═══════════════════════════════════
const _cineImg = (id, w = 300) => `/api/cinema/capa/${id}?w=${w}`;
const _cineDur = (min) => { if (!min) return ''; const h = Math.floor(min / 60), m = min % 60; return h ? `${h}h${m ? ' ' + m + 'min' : ''}` : `${m}min`; };

const CinemaCard = ({ item, onClick, largura }) => {
  const w = largura || 142;
  return (
    <div onClick={() => onClick(item)} style={{ width: w, flexShrink: 0, cursor: 'pointer', scrollSnapAlign: 'start' }} className="cine-card">
      <div style={{ width: w, height: Math.round(w * 1.5), borderRadius: 10, overflow: 'hidden', background: 'var(--cream-3)', boxShadow: 'var(--shadow-sm)', position: 'relative' }}>
        {item.temCapa
          ? <img src={_cineImg(item.id, 300)} alt={item.nome} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
          : <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 10, textAlign: 'center', fontFamily: 'var(--fs)', fontSize: 15, color: 'var(--muted)' }}>{item.nome}</div>}
        {item.tipo === 'Series' && <span style={{ position: 'absolute', top: 6, left: 6, fontFamily: 'var(--fm)', fontSize: 8.5, letterSpacing: 0.5, textTransform: 'uppercase', background: 'rgba(31,42,46,0.8)', color: 'var(--cream)', padding: '2px 6px', borderRadius: 5 }}>série</span>}
      </div>
      <div style={{ marginTop: 6, fontSize: 12, fontWeight: 500, lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.nome}</div>
      <div style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--muted)' }}>{item.ano || ''}</div>
    </div>
  );
};

const CinemaFileira = ({ titulo, itens, genero, token, onItem, isMobile }) => {
  const [lista, setLista] = React.useState(itens || null);
  React.useEffect(() => {
    if (itens) { setLista(itens); return; }
    if (genero) {
      fetch(`/api/cinema/biblioteca?genero=${encodeURIComponent(genero)}&limit=20`, { headers: { Authorization: `Bearer ${token()}` } })
        .then(r => r.ok ? r.json() : { itens: [] }).then(d => setLista(d.itens || [])).catch(() => setLista([]));
    }
  }, [genero, itens]);
  if (lista && !lista.length) return null;
  return (
    <div style={{ marginBottom: 26 }}>
      <div style={{ fontFamily: 'var(--fs)', fontSize: 18, marginBottom: 10, paddingLeft: 2 }}>{titulo}</div>
      <div className="cine-row" style={{ display: 'flex', gap: 12, overflowX: 'auto', paddingBottom: 6, scrollSnapType: 'x proximity' }}>
        {lista === null
          ? Array.from({ length: 6 }).map((_, i) => <div key={i} style={{ width: isMobile ? 120 : 142, height: (isMobile ? 120 : 142) * 1.5, borderRadius: 10, background: 'var(--cream-3)', flexShrink: 0, opacity: 0.5 }} />)
          : lista.map(it => <CinemaCard key={it.id} item={it} onClick={onItem} largura={isMobile ? 120 : 142} />)}
      </div>
    </div>
  );
};

const CinemaHero = ({ item, onItem, lang }) => {
  if (!item) return null;
  return (
    <div style={{ position: 'relative', borderRadius: 18, overflow: 'hidden', marginBottom: 30, minHeight: 230, background: 'var(--ink)' }}>
      {item.temCapa && <img src={_cineImg(item.id, 800)} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.55 }} />}
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(90deg, rgba(20,26,29,0.96) 25%, rgba(20,26,29,0.35) 100%)' }} />
      <div style={{ position: 'relative', padding: '30px 32px', maxWidth: 580, color: 'var(--cream)' }}>
        <div style={{ fontFamily: 'var(--fm)', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', opacity: 0.7, marginBottom: 10 }}>{lang === 'pt' ? 'em destaque' : 'featured'}</div>
        <div style={{ fontFamily: 'var(--fs)', fontSize: 32, lineHeight: 1.08, marginBottom: 12 }}>{item.nome}</div>
        <div style={{ fontFamily: 'var(--fm)', fontSize: 11, opacity: 0.85, marginBottom: 18 }}>{[item.ano, _cineDur(item.duracaoMin), item.genero].filter(Boolean).join('  ·  ')}</div>
        <button className="btn" onClick={() => onItem(item)} style={{ background: 'var(--accent)', color: '#fff', border: 'none' }}>{lang === 'pt' ? 'ver detalhes' : 'view details'}</button>
      </div>
    </div>
  );
};

const _cineIcon = (nome) => {
  const p = { width: 15, height: 15, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    direcao: <><path d="M3 8h18M6 4l2 4M11 4l2 4M16 4l2 4" /><rect x="3" y="8" width="18" height="12" rx="1" /></>,
    roteiro: <><path d="M12 20h9" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z" /></>,
    elenco: <><circle cx="9" cy="7" r="3" /><path d="M3 20c0-3 3-5 6-5s6 2 6 5" /><path d="M16 3.5a3 3 0 0 1 0 7M22 20c0-2.5-2-4.2-4.5-4.8" /></>,
    pais: <><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c2.5 2.7 2.5 15.3 0 18M12 3c-2.5 2.7-2.5 15.3 0 18" /></>,
    idioma: <><path d="M4 5h16M9 3v2M12 20l4-9 4 9M13.5 17h5" /><path d="M5 5c0 4 3 8 7 9" /></>,
    legendas: <><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M7 15h4M13 15h4M7 11h2M11 11h6" /></>,
    audio: <><path d="M11 5 6 9H3v6h3l5 4z" /><path d="M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13" /></>,
    resolucao: <><rect x="2" y="4" width="20" height="14" rx="2" /><path d="M8 21h8M12 18v3" /></>,
  };
  return <svg {...p}>{paths[nome] || null}</svg>;
};

// logo do Jellyfin (gradiente roxo→azul oficial)
const _cineJellyfinLogo = (size) => (
  <svg width={size} height={size} viewBox="0 0 512 512" fill="none" aria-hidden="true">
    <defs>
      <linearGradient id="jfLogo" x1="122" y1="386" x2="389" y2="122" gradientUnits="userSpaceOnUse">
        <stop stopColor="#AA5CC3" /><stop offset="1" stopColor="#00A4DC" />
      </linearGradient>
    </defs>
    <path fill="url(#jfLogo)" d="M256 201.6c-25.8 0-78.5 88.4-65.6 111 12.9 22.6 118.4 22.6 131.2 0 12.9-22.6-39.8-111-65.6-111z" />
    <path fill="url(#jfLogo)" d="M256 23C161.5 23-30.4 343.6 16.9 425c47.2 81.4 430.9 81.4 478.2 0C542.4 343.6 350.5 23 256 23zm175.3 380.4c-32.4 55.8-318.2 55.8-350.6 0-32.4-55.8 111.9-303.4 175.3-303.4s207.7 247.6 175.3 303.4z" />
  </svg>
);

// carrega hls.js sob demanda (cai no HLS nativo do Safari se não precisar)
const _cineLoadHls = () => new Promise((resolve, reject) => {
  if (window.Hls) return resolve(window.Hls);
  let s = document.getElementById('hlsjs-cdn');
  if (s) { s.addEventListener('load', () => resolve(window.Hls)); s.addEventListener('error', () => reject(new Error('hls'))); return; }
  s = document.createElement('script');
  s.id = 'hlsjs-cdn';
  s.src = 'https://cdn.jsdelivr.net/npm/hls.js@1.5.13/dist/hls.min.js';
  s.onload = () => resolve(window.Hls);
  s.onerror = () => reject(new Error('hls'));
  document.head.appendChild(s);
});

const CinemaPlayer = ({ id, nome, token, lang, onClose, onJellyfin }) => {
  const videoRef = React.useRef(null);
  const jellyTokenRef = React.useRef(null);
  const hlsRef = React.useRef(null);
  const [carregando, setCarregando] = React.useState(true);
  const [erro, setErro] = React.useState(null); // 'senha' | 'erro' | null
  const pt = lang === 'pt';

  React.useEffect(() => {
    let vivo = true;
    let timer = null;
    const reportar = (evento, paused) => {
      const jt = jellyTokenRef.current, v = videoRef.current;
      if (!jt || !v) return;
      fetch(`/api/cinema/progresso/${id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token()}` },
        body: JSON.stringify({ positionSec: Math.floor(v.currentTime || 0), token: jt, evento, paused: !!paused }),
        keepalive: evento === 'stop',
      }).catch(() => {});
    };

    (async () => {
      try {
        const r = await fetch(`/api/cinema/stream/${id}`, { headers: { Authorization: `Bearer ${token()}` } });
        const d = await r.json().catch(() => ({}));
        if (!r.ok) { if (vivo) setErro(d.error === 'senha_trocada' ? 'senha' : 'erro'); return; }
        if (!vivo) return;
        jellyTokenRef.current = d.token;
        const v = videoRef.current;
        if (!v) return;
        if (v.canPlayType('application/vnd.apple.mpegurl')) {
          v.src = d.streamUrl; // Safari / iOS: HLS nativo
        } else {
          let Hls = null;
          try { Hls = await _cineLoadHls(); } catch (_) { Hls = null; }
          if (Hls && Hls.isSupported()) {
            const hls = new Hls({ enableWorker: true, lowLatencyMode: false });
            hlsRef.current = hls;
            hls.on(Hls.Events.ERROR, (_e, data) => { if (data && data.fatal && vivo) setErro('erro'); });
            hls.loadSource(d.streamUrl);
            hls.attachMedia(v);
          } else {
            v.src = d.streamUrl; // última tentativa
          }
        }
        if (vivo) setCarregando(false);
        v.addEventListener('playing', () => reportar('start'));
        v.addEventListener('pause', () => reportar('progress', true));
        v.addEventListener('ended', () => reportar('stop'));
        timer = setInterval(() => { if (v && !v.paused && !v.ended) reportar('progress', false); }, 10000);
      } catch (e) { if (vivo) setErro('erro'); }
    })();

    return () => {
      vivo = false;
      if (timer) clearInterval(timer);
      reportar('stop');
      if (hlsRef.current) { try { hlsRef.current.destroy(); } catch (_) {} }
    };
  }, [id]);

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 400, background: '#000', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 20px', color: '#F3EEE4', background: 'linear-gradient(180deg, rgba(0,0,0,0.7), transparent)' }}>
        <button onClick={onClose} title={pt ? 'voltar' : 'back'} style={{ background: 'rgba(255,255,255,0.12)', border: 'none', borderRadius: '50%', width: 40, height: 40, cursor: 'pointer', color: '#fff', fontSize: 18, display: 'grid', placeItems: 'center', flexShrink: 0 }}>‹</button>
        <div style={{ fontFamily: 'var(--fs)', fontSize: 18, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{nome}</div>
      </div>

      <div style={{ flex: 1, position: 'relative', display: 'grid', placeItems: 'center', minHeight: 0 }}>
        {!erro && <video ref={videoRef} controls autoPlay playsInline style={{ width: '100%', height: '100%', maxHeight: '100%', background: '#000' }} />}
        {carregando && !erro && <div style={{ position: 'absolute', fontFamily: 'var(--fm)', fontSize: 13, color: 'rgba(243,238,228,0.7)' }}>{pt ? 'preparando o filme…' : 'preparing…'}</div>}
        {erro && (
          <div style={{ textAlign: 'center', color: '#F3EEE4', padding: 30, maxWidth: 460 }}>
            <div style={{ fontSize: 40, marginBottom: 14 }}>🎬</div>
            <div style={{ fontFamily: 'var(--fs)', fontSize: 20, marginBottom: 10 }}>{pt ? 'Não deu pra tocar aqui' : "Couldn't play here"}</div>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'rgba(243,238,228,0.65)', lineHeight: 1.6, marginBottom: 20 }}>
              {erro === 'senha'
                ? (pt ? 'A senha do teu acesso ao cinema foi trocada no Jellyfin, então não consegui autenticar por aqui. Dá pra assistir direto no Jellyfin.' : 'Your cinema password was changed in Jellyfin. You can watch directly there.')
                : (pt ? 'O servidor de mídia não conseguiu preparar o vídeo (formato ou transcodificação). Tenta no Jellyfin.' : 'The media server could not prepare the video. Try on Jellyfin.')}
            </div>
            <button onClick={() => { onClose(); onJellyfin && onJellyfin(); }} style={{ background: 'var(--accent)', color: '#fff', border: 'none', borderRadius: 999, padding: '11px 22px', fontFamily: 'var(--f)', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>{pt ? 'Assistir no Jellyfin' : 'Watch on Jellyfin'}</button>
          </div>
        )}
      </div>
    </div>
  );
};

const CinemaDetalheModal = ({ id, token, toast, onClose, onTrocar, lang }) => {
  const [det, setDet] = React.useState(null);
  const [erro, setErro] = React.useState(false);
  const [abrindo, setAbrindo] = React.useState(false);
  const [assistindo, setAssistindo] = React.useState(false);
  const [similares, setSimilares] = React.useState(null);
  const [favorito, setFavorito] = React.useState(false);
  const [favLoading, setFavLoading] = React.useState(false);
  const pt = lang === 'pt';

  React.useEffect(() => {
    let vivo = true;
    setDet(null); setErro(false); setSimilares(null); setFavorito(false);
    fetch(`/api/cinema/item/${id}`, { headers: { Authorization: `Bearer ${token()}` } })
      .then(r => r.ok ? r.json() : Promise.reject()).then(d => { if (vivo) setDet(d); }).catch(() => { if (vivo) setErro(true); });
    fetch(`/api/cinema/item/${id}/similar`, { headers: { Authorization: `Bearer ${token()}` } })
      .then(r => r.ok ? r.json() : { itens: [] }).then(d => { if (vivo) setSimilares(d.itens || []); }).catch(() => { if (vivo) setSimilares([]); });
    fetch(`/api/cinema/favorito/${id}`, { headers: { Authorization: `Bearer ${token()}` } })
      .then(r => r.ok ? r.json() : { favorito: false }).then(d => { if (vivo) setFavorito(!!d.favorito); }).catch(() => {});
    return () => { vivo = false; };
  }, [id]);

  const toggleFav = async () => {
    if (favLoading) return;
    const novo = !favorito;
    setFavorito(novo); setFavLoading(true); // otimista
    try {
      const r = await fetch(`/api/cinema/favorito/${id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token()}` },
        body: JSON.stringify({ favorito: novo }),
      });
      if (!r.ok) throw new Error();
    } catch (e) {
      setFavorito(!novo); // desfaz se falhar
      toast.push({ icon: 'x', title: pt ? 'Não consegui salvar o favorito' : 'Could not save favorite' });
    }
    setFavLoading(false);
  };

  const assistir = async () => {
    setAbrindo(true);
    try {
      let acc = await fetch('/api/cinema/meu-acesso', { headers: { Authorization: `Bearer ${token()}` } }).then(r => r.json());
      if (!acc.temAcesso) {
        acc = await fetch('/api/cinema/provisionar', { method: 'POST', headers: { Authorization: `Bearer ${token()}` } }).then(r => r.json());
        if (acc && acc.login) toast.push({ icon: 'check', title: pt ? 'Acesso ao cinema criado' : 'Cinema access created', body: `login: ${acc.login}` });
      }
      const base = String(acc.servidor || '').replace(/\/+$/, '');
      if (base) window.open(`${base}/web/index.html#!/details?id=${id}`, '_blank', 'noopener');
      else toast.push({ icon: 'x', title: pt ? 'Servidor do cinema não configurado' : 'Cinema server not set' });
    } catch (e) {
      toast.push({ icon: 'x', title: pt ? 'Não consegui abrir o Jellyfin' : 'Could not open Jellyfin' });
    }
    setAbrindo(false);
  };


  // ── cores do tema escuro do cinema ──
  const C = { bg: 'var(--surface)', panel: 'var(--cream-2)', line: 'var(--line-soft)', fg: 'var(--ink)', mut: 'var(--muted)', mut2: 'var(--muted-2)' };
  const fichaLinha = (icone, label, valor) => {
    if (!valor || (Array.isArray(valor) && !valor.length)) return null;
    return (
      <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '9px 0', borderTop: `1px solid ${C.line}` }}>
        <span style={{ color: C.mut2, marginTop: 1, flexShrink: 0 }}>{_cineIcon(icone)}</span>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--fm)', fontSize: 9.5, letterSpacing: 0.8, textTransform: 'uppercase', color: C.mut2, marginBottom: 2 }}>{label}</div>
          <div style={{ fontFamily: 'var(--f)', fontSize: 13, color: C.fg, lineHeight: 1.35 }}>{Array.isArray(valor) ? valor.join(', ') : valor}</div>
        </div>
      </div>
    );
  };

  return (
    <>
    {assistindo && <CinemaPlayer id={det ? det.id : id} nome={det ? det.nome : ''} token={token} lang={lang} onClose={() => setAssistindo(false)} onJellyfin={assistir} />}
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(31,42,46,0.6)', backdropFilter: 'blur(5px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '5vh 16px', overflowY: 'auto' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: 1000, background: C.bg, borderRadius: 22, boxShadow: '0 30px 80px rgba(0,0,0,0.5)', position: 'relative', color: C.fg, overflow: 'hidden' }}>
        <button onClick={onClose} title={pt ? 'fechar' : 'close'} style={{ position: 'absolute', top: 16, right: 16, zIndex: 5, width: 38, height: 38, borderRadius: '50%', border: 'none', background: 'var(--cream-2)', color: C.fg, cursor: 'pointer', fontSize: 17, display: 'grid', placeItems: 'center' }}>✕</button>

        {!det && !erro && <div style={{ padding: 80, textAlign: 'center', fontFamily: 'var(--fm)', fontSize: 12, color: C.mut }}>{pt ? 'carregando…' : 'loading…'}</div>}
        {erro && <div style={{ padding: 50, textAlign: 'center' }}><div style={{ fontFamily: 'var(--fm)', fontSize: 13, color: 'var(--rose)' }}>{pt ? 'não consegui carregar este título' : 'could not load this title'}</div></div>}

        {det && (
          <div style={{ padding: '30px 32px' }}>
            <div style={{ display: 'flex', gap: 26, flexWrap: 'wrap' }}>
              {/* Bloco esquerdo: [poster + info] em cima, sinopse atravessando embaixo */}
              <div style={{ flex: '1 1 420px', minWidth: 280 }}>
                <div style={{ display: 'flex', gap: 26, flexWrap: 'wrap' }}>
                  {/* Poster */}
                  <div style={{ width: 210, flexShrink: 0 }}>
                    <div style={{ width: 210, borderRadius: 14, overflow: 'hidden', background: 'var(--cream-3)', boxShadow: '0 12px 30px rgba(0,0,0,0.4)' }}>
                      {det.temCapa
                        ? <img src={_cineImg(det.id, 500)} alt={det.nome} style={{ width: '100%', display: 'block' }} />
                        : <div style={{ height: 300, display: 'grid', placeItems: 'center', fontFamily: 'var(--fs)', color: C.mut, padding: 12, textAlign: 'center' }}>{det.nome}</div>}
                    </div>
                  </div>

                  {/* Info: título, meta, gêneros, botões */}
                  <div style={{ flex: '1 1 240px', minWidth: 240 }}>
                    <div style={{ fontFamily: 'var(--fs)', fontSize: 34, lineHeight: 1.05, marginBottom: 12, paddingRight: 40 }}>{det.nome}</div>
                    <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center', fontFamily: 'var(--fm)', fontSize: 13, color: C.mut, marginBottom: 16 }}>
                      {det.ano && <span>{det.ano}</span>}
                      {det.duracaoMin ? <span>{_cineDur(det.duracaoMin)}</span> : null}
                      {det.tipo === 'Series' && <span>{pt ? 'série' : 'series'}</span>}
                      {det.classificacao && <span style={{ border: `1px solid ${C.line}`, borderRadius: 5, padding: '2px 8px', color: C.fg }}>{det.classificacao}</span>}
                      {det.nota ? <span style={{ color: 'var(--sun)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>★ {det.nota}</span> : null}
                    </div>
                    {det.generos && det.generos.length > 0 && (
                      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 22 }}>
                        {det.generos.slice(0, 4).map(g => <span key={g} style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--teal)', background: 'rgba(31,87,85,0.08)', border: '1px solid var(--teal)', borderRadius: 999, padding: '4px 14px' }}>{g}</span>)}
                      </div>
                    )}
                    <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start', flexWrap: 'wrap' }}>
                      {/* Assistir agora — play branco em fundo laranja */}
                      <button onClick={() => setAssistindo(true)} title={pt ? 'Assistir agora' : 'Watch now'} style={{ width: 52, height: 52, flexShrink: 0, borderRadius: '50%', background: 'var(--accent)', border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', boxShadow: '0 2px 8px rgba(217,105,75,0.35)' }}>
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="#fff"><path d="M8 5v14l11-7z" /></svg>
                      </button>
                      {/* Jellyfin — logo em fundo branco */}
                      <button onClick={assistir} disabled={abrindo} title={pt ? 'Assistir no App' : 'Watch on the app'} style={{ width: 52, height: 52, flexShrink: 0, borderRadius: '50%', background: '#fff', border: '1px solid var(--line-soft)', cursor: abrindo ? 'default' : 'pointer', display: 'grid', placeItems: 'center', opacity: abrindo ? 0.6 : 1, boxShadow: 'var(--shadow-sm)' }}>
                        {_cineJellyfinLogo(26)}
                      </button>
                      {/* Favorito — nativo do Jellyfin */}
                      <button onClick={toggleFav} title={favorito ? (pt ? 'Remover dos favoritos' : 'Remove from favorites') : (pt ? 'Favoritar' : 'Add to favorites')} style={{ flexShrink: 0, background: 'transparent', border: 'none', cursor: favLoading ? 'default' : 'pointer', color: C.fg, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, width: 56, opacity: favLoading ? 0.7 : 1 }}>
                        <span style={{ width: 52, height: 52, borderRadius: '50%', border: `1.5px solid ${favorito ? 'var(--rose)' : C.line}`, background: favorito ? 'var(--rose)' : 'transparent', color: favorito ? '#fff' : C.fg, display: 'grid', placeItems: 'center', transition: 'all .15s' }}>
                          <svg width="20" height="20" viewBox="0 0 24 24" fill={favorito ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.8"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.6l-1-1a5.5 5.5 0 0 0-7.8 7.8l1 1L12 21l7.8-7.6 1-1a5.5 5.5 0 0 0 0-7.8z" /></svg>
                        </span>
                        <span style={{ fontFamily: 'var(--fm)', fontSize: 9.5, color: favorito ? 'var(--rose)' : C.mut, whiteSpace: 'nowrap' }}>{pt ? 'Favorito' : 'Favorite'}</span>
                      </button>
                    </div>
                  </div>
                </div>

                {/* Sinopse — atravessa embaixo do poster + info */}
                {det.sinopse && <div style={{ fontFamily: 'var(--f)', fontSize: 14.5, lineHeight: 1.6, color: 'var(--ink)', marginTop: 24, textAlign: 'justify' }}>{det.sinopse}</div>}
              </div>

              {/* Ficha técnica — à direita de tudo */}
              <div style={{ flex: '0 0 260px', minWidth: 240, background: C.panel, border: `1px solid ${C.line}`, borderRadius: 16, padding: '6px 18px 14px', alignSelf: 'flex-start' }}>
                {fichaLinha('direcao', pt ? 'Direção' : 'Directing', det.direcao)}
                {fichaLinha('roteiro', pt ? 'Roteiro' : 'Writing', det.roteiro)}
                {fichaLinha('elenco', pt ? 'Elenco' : 'Cast', det.elenco)}
                {fichaLinha('pais', pt ? 'País' : 'Country', det.pais)}
                {fichaLinha('idioma', pt ? 'Idioma' : 'Language', det.audio && det.audio[0])}
                {fichaLinha('legendas', pt ? 'Legendas' : 'Subtitles', det.legendas)}
                {fichaLinha('audio', pt ? 'Áudio' : 'Audio', det.audio && det.audio.length ? (det.audio.join(', ') + (det.audioLayout ? ` (${det.audioLayout})` : '')) : null)}
                {fichaLinha('resolucao', pt ? 'Resolução' : 'Resolution', det.resolucao)}
              </div>
            </div>

            {/* Talvez você também goste */}
            {similares && similares.length > 0 && (
              <div style={{ marginTop: 30 }}>
                <div style={{ fontFamily: 'var(--fs)', fontSize: 20, marginBottom: 14 }}>{pt ? 'Talvez você também goste:' : 'You might also like:'}</div>
                <div className="cine-row" style={{ display: 'flex', gap: 14, overflowX: 'auto', paddingBottom: 6 }}>
                  {similares.map(s => (
                    <div key={s.id} onClick={() => onTrocar && onTrocar(s.id)} style={{ width: 130, flexShrink: 0, cursor: 'pointer' }} className="cine-card">
                      <div style={{ width: 130, height: 195, borderRadius: 10, overflow: 'hidden', background: 'var(--cream-3)' }}>
                        {s.temCapa
                          ? <img src={_cineImg(s.id, 300)} alt={s.nome} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                          : <div style={{ height: '100%', display: 'grid', placeItems: 'center', fontFamily: 'var(--fs)', color: C.mut, fontSize: 13, padding: 8, textAlign: 'center' }}>{s.nome}</div>}
                      </div>
                      <div style={{ marginTop: 6, fontSize: 12, fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.nome}</div>
                      <div style={{ fontFamily: 'var(--fm)', fontSize: 10, color: C.mut, display: 'flex', gap: 8 }}>
                        <span>{s.ano || ''}</span>{s.nota ? <span style={{ color: 'var(--sun)' }}>★ {s.nota}</span> : null}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
    </>
  );
};

// ═══ Clube do Filme ══════════════════════════════════════════════════════════
const ClubeOpcao = ({ op, total, meuVoto, onVotar, onAbrirFilme, encerrada, votando, lang }) => {
  const pt = lang === 'pt';
  const pct = total > 0 ? Math.round((op.votos / total) * 100) : 0;
  const meu = meuVoto === op.id;
  const w = 132;
  return (
    <div style={{ width: w, flexShrink: 0 }}>
      <div onClick={() => op.jellyfin_id && onAbrirFilme(op.jellyfin_id)} title={pt ? 'ver sinopse' : 'details'} style={{ width: w, height: Math.round(w * 1.5), borderRadius: 10, overflow: 'hidden', background: 'var(--cream-3)', cursor: op.jellyfin_id ? 'pointer' : 'default', border: meu ? '2px solid var(--accent)' : '2px solid transparent', position: 'relative', boxShadow: 'var(--shadow-sm)' }}>
        {op.jellyfin_id
          ? <img src={_cineImg(op.jellyfin_id, 300)} alt={op.nome} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : <div style={{ height: '100%', display: 'grid', placeItems: 'center', fontFamily: 'var(--fs)', color: 'var(--muted)', padding: 8, textAlign: 'center', fontSize: 13 }}>{op.nome}</div>}
        {meu && <span style={{ position: 'absolute', top: 6, right: 6, width: 22, height: 22, borderRadius: '50%', background: 'var(--accent)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 12 }}>✓</span>}
      </div>
      <div style={{ marginTop: 7, fontSize: 12, fontWeight: 500, lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{op.nome}{op.ano ? ` (${op.ano})` : ''}</div>
      <div style={{ marginTop: 5, height: 6, borderRadius: 3, background: 'var(--cream-3)', overflow: 'hidden' }}>
        <div style={{ width: pct + '%', height: '100%', background: meu ? 'var(--accent)' : 'var(--teal)', transition: 'width .3s' }} />
      </div>
      <div style={{ marginTop: 4, fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--muted)' }}>{op.votos} {pt ? 'votos' : 'votes'} · {pct}%</div>
      {!encerrada && (
        <button onClick={() => onVotar(op.id)} disabled={votando} style={{ marginTop: 7, width: '100%', padding: '6px 0', borderRadius: 8, cursor: votando ? 'default' : 'pointer', fontFamily: 'var(--fm)', fontSize: 11, border: meu ? 'none' : '1px solid var(--line)', background: meu ? 'var(--accent)' : 'var(--surface)', color: meu ? '#fff' : 'var(--ink)' }}>
          {meu ? (pt ? '✓ seu voto' : '✓ your vote') : (pt ? 'votar' : 'vote')}
        </button>
      )}
    </div>
  );
};

const ClubeMontar = ({ token, lang, onCriar, onCancelar }) => {
  const pt = lang === 'pt';
  const H = () => ({ 'Content-Type': 'application/json', Authorization: `Bearer ${token()}` });
  const [titulo, setTitulo] = React.useState('');
  const [termo, setTermo] = React.useState('');
  const [resultados, setResultados] = React.useState(null);
  const [candidatos, setCandidatos] = React.useState([]);
  const [criando, setCriando] = React.useState(false);

  React.useEffect(() => {
    const t = termo.trim();
    if (t.length < 2) { setResultados(null); return; }
    const timer = setTimeout(() => {
      fetch(`/api/cinema/biblioteca?q=${encodeURIComponent(t)}&limit=24`, { headers: H() })
        .then(r => r.ok ? r.json() : { itens: [] }).then(d => setResultados(d.itens || [])).catch(() => setResultados([]));
    }, 350);
    return () => clearTimeout(timer);
  }, [termo]);

  const jaTem = (id) => candidatos.some(c => c.jellyfin_id === id);
  const add = (it) => { if (!jaTem(it.id)) setCandidatos(c => [...c, { jellyfin_id: it.id, nome: it.nome, ano: it.ano, temCapa: it.temCapa }]); };
  const rem = (id) => setCandidatos(c => c.filter(x => x.jellyfin_id !== id));

  const criar = async () => {
    if (candidatos.length < 2) return;
    setCriando(true);
    try {
      const r = await fetch('/api/cinema/votacao', { method: 'POST', headers: H(), body: JSON.stringify({ titulo: titulo.trim() || null, opcoes: candidatos.map(c => ({ jellyfin_id: c.jellyfin_id, nome: c.nome, ano: c.ano })) }) });
      if (!r.ok) throw new Error();
      onCriar();
    } catch (e) { setCriando(false); }
  };

  return (
    <div>
      <input className="input" value={titulo} onChange={e => setTitulo(e.target.value)} placeholder={pt ? 'Título (ex: Sessão de sexta) — opcional' : 'Title — optional'} style={{ width: '100%', boxSizing: 'border-box', marginBottom: 12 }} />

      {candidatos.length > 0 && (
        <div style={{ marginBottom: 14 }}>
          <div style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 8 }}>{pt ? 'Candidatos' : 'Candidates'} ({candidatos.length})</div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            {candidatos.map(c => (
              <div key={c.jellyfin_id} style={{ position: 'relative', width: 76 }}>
                <div style={{ width: 76, height: 114, borderRadius: 8, overflow: 'hidden', background: 'var(--cream-3)' }}>
                  {c.temCapa ? <img src={_cineImg(c.jellyfin_id, 200)} alt={c.nome} style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <div style={{ height: '100%', display: 'grid', placeItems: 'center', fontSize: 10, color: 'var(--muted)', padding: 4, textAlign: 'center' }}>{c.nome}</div>}
                </div>
                <button onClick={() => rem(c.jellyfin_id)} title={pt ? 'remover' : 'remove'} style={{ position: 'absolute', top: -6, right: -6, width: 22, height: 22, borderRadius: '50%', border: 'none', background: 'var(--rose)', color: '#fff', cursor: 'pointer', fontSize: 13 }}>×</button>
              </div>
            ))}
          </div>
        </div>
      )}

      <input className="input" value={termo} onChange={e => setTermo(e.target.value)} placeholder={pt ? 'Buscar filme na biblioteca…' : 'Search library…'} style={{ width: '100%', boxSizing: 'border-box', marginBottom: 12 }} />
      {resultados && resultados.length > 0 && (
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', maxHeight: 260, overflowY: 'auto', marginBottom: 14 }}>
          {resultados.map(it => (
            <div key={it.id} onClick={() => add(it)} style={{ width: 76, cursor: jaTem(it.id) ? 'default' : 'pointer', opacity: jaTem(it.id) ? 0.4 : 1 }}>
              <div style={{ width: 76, height: 114, borderRadius: 8, overflow: 'hidden', background: 'var(--cream-3)' }}>
                {it.temCapa ? <img src={_cineImg(it.id, 200)} alt={it.nome} loading="lazy" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : <div style={{ height: '100%', display: 'grid', placeItems: 'center', fontSize: 10, color: 'var(--muted)', padding: 4, textAlign: 'center' }}>{it.nome}</div>}
              </div>
              <div style={{ marginTop: 4, fontSize: 10, lineHeight: 1.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.nome}</div>
            </div>
          ))}
        </div>
      )}
      {resultados && resultados.length === 0 && <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--muted)', padding: '10px 0' }}>{pt ? 'nada encontrado' : 'nothing found'}</div>}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 6 }}>
        <button className="btn btn-sm" onClick={onCancelar}>{pt ? 'cancelar' : 'cancel'}</button>
        <button onClick={criar} disabled={candidatos.length < 2 || criando} style={{ padding: '9px 20px', borderRadius: 999, border: 'none', cursor: (candidatos.length < 2 || criando) ? 'default' : 'pointer', background: candidatos.length < 2 ? 'var(--cream-3)' : 'var(--accent)', color: candidatos.length < 2 ? 'var(--muted)' : '#fff', fontFamily: 'var(--f)', fontSize: 14, fontWeight: 600 }}>
          {criando ? (pt ? 'criando…' : 'creating…') : (pt ? 'Abrir votação' : 'Open poll')}
        </button>
      </div>
      {candidatos.length < 2 && <div style={{ fontFamily: 'var(--fm)', fontSize: 10, color: 'var(--muted)', textAlign: 'right', marginTop: 6 }}>{pt ? 'mínimo 2 filmes' : 'min 2 movies'}</div>}
    </div>
  );
};

const ClubeModal = ({ token, lang, canManage, onClose, onAbrirFilme }) => {
  const pt = lang === 'pt';
  const H = () => ({ 'Content-Type': 'application/json', Authorization: `Bearer ${token()}` });
  const [dados, setDados] = React.useState(null);
  const [estado, setEstado] = React.useState(null);
  const [carregando, setCarregando] = React.useState(true);
  const [modo, setModo] = React.useState('ver');
  const [votando, setVotando] = React.useState(false);

  const carregar = () => {
    Promise.all([
      fetch('/api/cinema/votacao', { headers: H() }).then(r => r.ok ? r.json() : {}),
      fetch('/api/cinema/clube/estado', { headers: H() }).then(r => r.ok ? r.json() : {}),
    ]).then(([v, e]) => {
      setDados(v); setEstado(e); setCarregando(false);
      if (e && e.ultimaFechada) { try { localStorage.setItem('genesis_clube_visto', String(e.ultimaFechada.id)); } catch (_) {} }
    }).catch(() => setCarregando(false));
  };
  React.useEffect(() => { carregar(); }, []);

  const votar = async (optionId) => {
    setVotando(true);
    try { await fetch('/api/cinema/votar', { method: 'POST', headers: H(), body: JSON.stringify({ option_id: optionId }) }); carregar(); } catch (e) {}
    setVotando(false);
  };
  const encerrar = async () => {
    if (!dados || !dados.poll) return;
    try { await fetch(`/api/cinema/votacao/${dados.poll.id}/fechar`, { method: 'POST', headers: H() }); carregar(); } catch (e) {}
  };

  const temAtiva = dados && dados.poll;
  const resultado = !temAtiva && estado && estado.ultimaFechada;

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 260, background: 'rgba(31,42,46,0.6)', backdropFilter: 'blur(5px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '6vh 16px', overflowY: 'auto' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: '100%', maxWidth: 640, background: 'var(--cream)', borderRadius: 22, padding: '22px 24px', boxShadow: 'var(--shadow-lg)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
          <div style={{ fontFamily: 'var(--fs)', fontSize: 22 }}>🍿 {pt ? 'Clube do Filme' : 'Film Club'}</div>
          <button className="btn btn-sm" onClick={onClose}>{pt ? 'fechar' : 'close'}</button>
        </div>

        {modo === 'montar' ? (
          <div style={{ marginTop: 14 }}>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--muted)', marginBottom: 14 }}>{pt ? 'Monte a votação escolhendo filmes da biblioteca.' : 'Build the poll picking movies from the library.'}</div>
            <ClubeMontar token={token} lang={lang} onCriar={() => { setModo('ver'); carregar(); }} onCancelar={() => setModo('ver')} />
          </div>
        ) : carregando ? (
          <div style={{ padding: 50, textAlign: 'center', fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--muted)' }}>{pt ? 'carregando…' : 'loading…'}</div>
        ) : temAtiva ? (
          <div style={{ marginTop: 10 }}>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--muted)', marginBottom: 14 }}>{dados.poll.titulo || (pt ? 'Vote no filme da próxima sessão' : 'Vote for the next session')} · {dados.total} {pt ? 'votos' : 'votes'}</div>
            <div className="cine-row" style={{ display: 'flex', gap: 14, overflowX: 'auto', paddingBottom: 6 }}>
              {dados.opcoes.map(op => <ClubeOpcao key={op.id} op={op} total={dados.total} meuVoto={dados.meuVoto} onVotar={votar} onAbrirFilme={onAbrirFilme} votando={votando} lang={lang} />)}
            </div>
            {canManage && <div style={{ marginTop: 18, display: 'flex', justifyContent: 'space-between' }}>
              <button className="btn btn-sm" onClick={() => setModo('montar')}>{pt ? '+ nova votação' : '+ new poll'}</button>
              <button className="btn btn-sm" onClick={encerrar} style={{ color: 'var(--rose)' }}>{pt ? 'encerrar votação' : 'close poll'}</button>
            </div>}
          </div>
        ) : resultado ? (
          <div style={{ marginTop: 10 }}>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 10 }}>{pt ? 'Resultado' : 'Result'}{estado.ultimaFechada.titulo ? ` · ${estado.ultimaFechada.titulo}` : ''}</div>
            {estado.ultimaFechada.vencedor ? (
              <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
                <div onClick={() => estado.ultimaFechada.vencedor.jellyfin_id && onAbrirFilme(estado.ultimaFechada.vencedor.jellyfin_id)} style={{ width: 110, height: 165, borderRadius: 10, overflow: 'hidden', background: 'var(--cream-3)', flexShrink: 0, cursor: estado.ultimaFechada.vencedor.jellyfin_id ? 'pointer' : 'default', border: '2px solid var(--sun)' }}>
                  {estado.ultimaFechada.vencedor.jellyfin_id && <img src={_cineImg(estado.ultimaFechada.vencedor.jellyfin_id, 300)} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />}
                </div>
                <div>
                  <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--sun)', marginBottom: 4 }}>🏆 {pt ? 'Vencedor' : 'Winner'}</div>
                  <div style={{ fontFamily: 'var(--fs)', fontSize: 24, lineHeight: 1.1 }}>{estado.ultimaFechada.vencedor.nome}{estado.ultimaFechada.vencedor.ano ? ` (${estado.ultimaFechada.vencedor.ano})` : ''}</div>
                  <div style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>{estado.ultimaFechada.vencedor.votos} {pt ? 'votos' : 'votes'}</div>
                </div>
              </div>
            ) : <div style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--muted)' }}>{pt ? 'Sem votos registrados.' : 'No votes.'}</div>}
            {canManage && <div style={{ marginTop: 20 }}><button className="btn btn-sm" onClick={() => setModo('montar')}>{pt ? '+ nova votação' : '+ new poll'}</button></div>}
          </div>
        ) : (
          <div style={{ padding: '40px 0', textAlign: 'center' }}>
            <div style={{ fontSize: 34, marginBottom: 10 }}>🎬</div>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--muted)' }}>{pt ? 'Nenhuma votação no momento.' : 'No poll right now.'}</div>
            {canManage && <div style={{ marginTop: 18 }}><button onClick={() => setModo('montar')} style={{ padding: '10px 22px', borderRadius: 999, border: 'none', background: 'var(--accent)', color: '#fff', fontFamily: 'var(--f)', fontSize: 14, fontWeight: 600, cursor: 'pointer' }}>{pt ? 'Criar votação' : 'Create poll'}</button></div>}
          </div>
        )}
      </div>
    </div>
  );
};

const Cinema = ({ state, setState, setPage }) => {
  const toast = useToast();
  const isMobile = useMobile();
  const token = () => localStorage.getItem('genesis_token');
  const lang = state.lang || 'pt';
  const me = state.currentUser || {};
  const canManage = me.role === 'admin' || me.is_staff === true;
  const [recentes, setRecentes] = React.useState(null);
  const [favoritos, setFavoritos] = React.useState(null);
  const [generos, setGeneros] = React.useState([]);
  const [erro, setErro] = React.useState(null);
  const [detalheId, setDetalheId] = React.useState(null);
  const [clubeAberto, setClubeAberto] = React.useState(false);
  const [clubeEstado, setClubeEstado] = React.useState(null);
  const [buscaAberta, setBuscaAberta] = React.useState(false);
  const [termo, setTermo] = React.useState('');
  const [resultados, setResultados] = React.useState(null);
  const [buscando, setBuscando] = React.useState(false);

  React.useEffect(() => {
    if (document.getElementById('cine-style')) return;
    const s = document.createElement('style');
    s.id = 'cine-style';
    s.textContent = '.cine-row::-webkit-scrollbar{height:6px}.cine-row::-webkit-scrollbar-track{background:transparent}.cine-row::-webkit-scrollbar-thumb{background:var(--line);border-radius:3px}.cine-card{transition:transform .15s ease}.cine-card:hover{transform:translateY(-3px)}';
    document.head.appendChild(s);
  }, []);

  React.useEffect(() => {
    fetch('/api/cinema/recentes', { headers: { Authorization: `Bearer ${token()}` } })
      .then(r => r.ok ? r.json() : Promise.reject(r.status)).then(d => setRecentes(d.itens || [])).catch(e => setErro(e));
    fetch('/api/cinema/generos', { headers: { Authorization: `Bearer ${token()}` } })
      .then(r => r.ok ? r.json() : { generos: [] }).then(d => setGeneros((d.generos || []).filter(g => g.total > 0).sort((a, b) => b.total - a.total).slice(0, 14))).catch(() => { });
    fetch('/api/cinema/favoritos', { headers: { Authorization: `Bearer ${token()}` } })
      .then(r => r.ok ? r.json() : { itens: [] }).then(d => setFavoritos(d.itens || [])).catch(() => setFavoritos([]));
    carregarClube();
  }, []);

  const carregarClube = () => {
    fetch('/api/cinema/clube/estado', { headers: { Authorization: `Bearer ${token()}` } })
      .then(r => r.ok ? r.json() : null).then(d => setClubeEstado(d)).catch(() => {});
  };

  // badge do botão: 'nova' (votação aberta que não votei) | 'resultado' (fechou e não vi) | null
  const clubeBadge = (() => {
    if (!clubeEstado) return null;
    if (clubeEstado.ativa && !clubeEstado.ativa.jaVotei) return 'nova';
    if (clubeEstado.ultimaFechada) {
      let visto = null;
      try { visto = localStorage.getItem('genesis_clube_visto'); } catch (_) {}
      if (String(clubeEstado.ultimaFechada.id) !== String(visto)) return 'resultado';
    }
    return null;
  })();

  React.useEffect(() => {
    if (!buscaAberta) return;
    const t = termo.trim();
    if (t.length < 2) { setResultados(null); return; }
    setBuscando(true);
    const timer = setTimeout(() => {
      fetch(`/api/cinema/biblioteca?q=${encodeURIComponent(t)}&limit=60`, { headers: { Authorization: `Bearer ${token()}` } })
        .then(r => r.ok ? r.json() : { itens: [] }).then(d => { setResultados(d.itens || []); setBuscando(false); }).catch(() => { setResultados([]); setBuscando(false); });
    }, 350);
    return () => clearTimeout(timer);
  }, [termo, buscaAberta]);

  const hero = recentes ? (recentes.find(x => x.temCapa) || recentes[0]) : null;
  const abrirItem = (it) => setDetalheId(it.id);

  if (erro) {
    return (
      <div style={{ maxWidth: 1100, margin: '0 auto', padding: isMobile ? '16px' : '24px 28px' }}>
        <div style={{ fontFamily: 'var(--fs)', fontSize: 30, marginBottom: 6 }}>{t('page_cinema_t1', lang)} <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>{t('page_cinema_t2', lang)}</em></div>
        <div style={{ marginTop: 30, background: 'var(--surface)', border: '1px solid var(--line-soft)', borderRadius: 16, padding: '40px 30px', textAlign: 'center' }}>
          <div style={{ fontSize: 34, marginBottom: 10 }}>📽️</div>
          <div style={{ fontFamily: 'var(--fs)', fontSize: 19, marginBottom: 8 }}>{lang === 'pt' ? 'Cinema fora do ar' : 'Cinema offline'}</div>
          <div style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--muted)', lineHeight: 1.6, maxWidth: 420, margin: '0 auto' }}>
            {lang === 'pt' ? 'Não consegui falar com o servidor de mídia (Jellyfin). Confere se ele está ligado e se a chave de API está certa.' : 'Could not reach the media server (Jellyfin). Check if it is running and the API key is correct.'}
          </div>
        </div>
      </div>
    );
  }

  const buscaAtiva = buscaAberta && termo.trim().length >= 2;

  return (
    <div style={{ maxWidth: 1100, margin: '0 auto', padding: isMobile ? '16px' : '24px 28px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 22 }}>
        <div>
          <div style={{ fontFamily: 'var(--fs)', fontSize: isMobile ? 26 : 32, lineHeight: 1.05 }}>{t('page_cinema_t1', lang)} <em style={{ fontStyle: 'italic', color: 'var(--accent)' }}>{t('page_cinema_t2', lang)}</em></div>
          <div style={{ fontFamily: 'var(--fm)', fontSize: 11, color: 'var(--muted)', marginTop: 4 }}>{t('page_cinema_sub', lang)}</div>
        </div>
        <div style={{ display: 'flex', gap: 10, flexShrink: 0 }}>
          <button onClick={() => setClubeAberto(true)} title={lang === 'pt' ? 'Clube do Filme' : 'Film Club'}
            style={{ position: 'relative', width: 42, height: 42, borderRadius: 12, cursor: 'pointer', display: 'grid', placeItems: 'center', border: 'none', background: 'var(--surface)', color: 'var(--ink)', boxShadow: 'var(--shadow-sm)' }}>
            <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8h18M3 8l2-4h14l2 4M3 8v12h18V8" /><path d="M8 4l1.5 4M13 4l1.5 4" /></svg>
            {clubeBadge && <span style={{ position: 'absolute', top: -3, right: -3, minWidth: 15, height: 15, padding: '0 3px', borderRadius: 8, background: clubeBadge === 'nova' ? 'var(--rose)' : 'var(--leaf)', color: '#fff', fontSize: 9, fontWeight: 700, display: 'grid', placeItems: 'center', border: '2px solid var(--cream)' }}>{clubeBadge === 'nova' ? '!' : '✓'}</span>}
          </button>
          <button onClick={() => { setBuscaAberta(v => !v); if (buscaAberta) { setTermo(''); setResultados(null); } }} title={lang === 'pt' ? 'buscar' : 'search'}
            style={{ flexShrink: 0, width: 42, height: 42, borderRadius: 12, cursor: 'pointer', display: 'grid', placeItems: 'center', border: 'none', background: buscaAberta ? 'var(--accent)' : 'var(--surface)', color: buscaAberta ? '#fff' : 'var(--ink)', boxShadow: 'var(--shadow-sm)' }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></svg>
          </button>
        </div>
      </div>

      {buscaAberta && (
        <input autoFocus className="input" value={termo} onChange={e => setTermo(e.target.value)} placeholder={lang === 'pt' ? 'buscar filme ou série…' : 'search movie or series…'} style={{ width: '100%', boxSizing: 'border-box', marginBottom: 24, fontSize: 15 }} />
      )}

      {buscaAtiva ? (
        <div>
          {buscando && <div style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'var(--muted)', marginBottom: 14 }}>{lang === 'pt' ? 'buscando…' : 'searching…'}</div>}
          {resultados && resultados.length === 0 && !buscando && <div style={{ fontFamily: 'var(--fm)', fontSize: 13, color: 'var(--muted)', padding: '30px 0', textAlign: 'center' }}>{lang === 'pt' ? 'nada encontrado' : 'nothing found'}</div>}
          {resultados && resultados.length > 0 && (
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(auto-fill, minmax(${isMobile ? 100 : 130}px, 1fr))`, gap: 16 }}>
              {resultados.map(it => <CinemaCard key={it.id} item={it} onClick={abrirItem} largura={isMobile ? 100 : 130} />)}
            </div>
          )}
        </div>
      ) : (
        <>
          <CinemaHero item={hero} onItem={abrirItem} lang={lang} />
          <CinemaFileira titulo={lang === 'pt' ? 'Adicionados recentemente' : 'Recently added'} itens={recentes} onItem={abrirItem} isMobile={isMobile} />
          {favoritos && favoritos.length > 0 && <CinemaFileira titulo={lang === 'pt' ? '❤ Meus favoritos' : '❤ My favorites'} itens={favoritos} onItem={abrirItem} isMobile={isMobile} />}
          {generos.map(g => <CinemaFileira key={g.nome} titulo={g.nome} genero={g.nome} token={token} onItem={abrirItem} isMobile={isMobile} />)}
        </>
      )}

      {clubeAberto && <ClubeModal token={token} lang={lang} canManage={canManage} onClose={() => { setClubeAberto(false); carregarClube(); }} onAbrirFilme={(jfId) => setDetalheId(jfId)} />}
      {detalheId && <CinemaDetalheModal id={detalheId} token={token} toast={toast} lang={lang} onClose={() => { setDetalheId(null); fetch('/api/cinema/favoritos', { headers: { Authorization: `Bearer ${token()}` } }).then(r => r.ok ? r.json() : { itens: [] }).then(d => setFavoritos(d.itens || [])).catch(() => {}); }} onTrocar={(novoId) => setDetalheId(novoId)} />}
    </div>
  );
};

Object.assign(window, { Cinema });
