/* Layvtime — Match Center (resumen/stats/alineación/chat), Chat en vivo, Noticias, Artículo */

// ── Chat en vivo ──────────────────────────────────────────────
function LiveChat({ matchId }) {
  const CF = window.CF;
  const [msgs, setMsgs] = React.useState(CF.chatSeed.map((m, i) => ({ ...m, id: 'c' + i })));
  const [floats, setFloats] = React.useState([]);
  const [draft, setDraft] = React.useState('');
  const scrollRef = React.useRef(null);
  const extra = ['¡Eso! 🔥', 'No puede ser 😩', 'Golazoooo ⚽', 'Arbitro vendido 🤬', 'Mi fantasy va volando 🚀', 'Qué nivel 👏', 'Cámbienlo ya', 'Defiendan!! 🧤'];

  // mensajes entrando solos (simulación de comunidad)
  React.useEffect(() => {
    const users = ['Tigre_UANL', 'PumaDorado', 'CruzAzulino', 'FanLayv', 'Quiniela_Pro', 'Mexa10'];
    const id = setInterval(() => {
      setMsgs((m) => [...m.slice(-40), { id: 'r' + Date.now(), u: users[Math.floor(Math.random() * users.length)], msg: extra[Math.floor(Math.random() * extra.length)] }]);
    }, 2600);
    return () => clearInterval(id);
  }, []);

  React.useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [msgs]);

  const send = () => { if (!draft.trim()) return; setMsgs((m) => [...m, { id: 'me' + Date.now(), u: 'Tú', me: true, msg: draft.trim() }]); setDraft(''); };
  const react = (emoji) => {
    const fid = 'f' + Date.now() + Math.random();
    setFloats((f) => [...f, { id: fid, emoji, x: 10 + Math.random() * 70 }]);
    setTimeout(() => setFloats((f) => f.filter((x) => x.id !== fid)), 1800);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: 420, position: 'relative' }}>
      {/* floating reactions */}
      <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden', zIndex: 3 }}>
        {floats.map((f) => (
          <span key={f.id} style={{ position: 'absolute', bottom: 60, left: f.x + '%', fontSize: 26, animation: 'floatUp 1.8s ease-out forwards' }}>{f.emoji}</span>
        ))}
      </div>
      <div ref={scrollRef} className="noscroll" style={{ flex: 1, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 10, padding: '4px 2px' }}>
        {msgs.map((m) => (
          <div key={m.id} style={{ display: 'flex', gap: 9, flexDirection: m.me ? 'row-reverse' : 'row' }}>
            {!m.me && <div style={{ flexShrink: 0 }}>{m.team ? <Crest team={m.team} size={26} /> : <Avatar name={m.u} size={26} />}</div>}
            <div style={{ maxWidth: '74%' }}>
              {!m.me && <div style={{ fontSize: 11, fontWeight: 700, color: m.team ? C.fg : C.accent2 || C.primary, marginBottom: 2, color: C.mut }}>{m.u}</div>}
              <div style={{ display: 'inline-block', background: m.me ? C.primary : C.card, color: m.me ? '#fff' : C.fg, border: m.me ? 'none' : `1px solid ${C.cardBorder}`, borderRadius: 13, padding: '7px 11px', fontSize: 13.5, lineHeight: 1.35 }}>{m.msg}</div>
            </div>
          </div>
        ))}
      </div>
      {/* reaction bar */}
      <div className="noscroll" style={{ display: 'flex', gap: 7, padding: '8px 0', overflowX: 'auto' }}>
        {CF.chatReactions.map((e) => (
          <button key={e} onClick={() => react(e)} style={{ flexShrink: 0, width: 40, height: 40, borderRadius: 999, border: `1px solid ${C.border}`, background: C.secondary, fontSize: 19, cursor: 'pointer' }}>{e}</button>
        ))}
      </div>
      {/* input */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
        <input value={draft} onChange={(e) => setDraft(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') send(); }} placeholder="Escribe en el chat…" style={{ flex: 1, background: C.secondary, border: `1px solid ${C.border}`, borderRadius: 999, padding: '11px 16px', color: C.fg, fontFamily: 'inherit', fontSize: 14, outline: 'none' }} />
        <button onClick={send} style={{ width: 42, height: 42, borderRadius: 999, background: C.primary, border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}><Icon name="arrowR" size={18} color="#fff" /></button>
      </div>
    </div>
  );
}

// ── Momios (Caliente.mx · links de apuesta) ───────────────────
const CALIENTE_URL = 'https://www.caliente.mx/apuestas-deportivas/futbol/mexico-liga-mx';
const CAL_RED = '#e10915';

// Logo de Caliente (wordmark de marca: rojo + .mx)
function CalienteLogo({ h = 18 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: CAL_RED, borderRadius: 6, padding: `${h * 0.28}px ${h * 0.5}px`, lineHeight: 1 }}>
      <span style={{ fontWeight: 900, fontSize: h, color: '#fff', letterSpacing: -0.3, fontStyle: 'italic' }}>caliente</span>
      <span style={{ fontWeight: 800, fontSize: h * 0.7, color: '#ffd400' }}>.mx</span>
    </span>
  );
}

function OddsBtn({ label, val }) {
  return (
    <a href={CALIENTE_URL} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()} style={{ flex: 1, cursor: 'pointer', textDecoration: 'none', border: `1px solid ${CAL_RED}55`, background: `${CAL_RED}14`, borderRadius: 10, padding: '8px 4px 7px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 1, transition: 'all .15s' }}>
      <span style={{ fontSize: 11, color: C.mut, fontWeight: 600 }}>{label}</span>
      <span className="num" style={{ fontWeight: 800, fontSize: 16, color: '#fff' }}>{val.toFixed(2)}</span>
      <span style={{ fontSize: 8.5, color: CAL_RED, fontWeight: 800, letterSpacing: 0.4, display: 'flex', alignItems: 'center', gap: 2, marginTop: 1 }}>APOSTAR <Icon name="share" size={8} color={CAL_RED} /></span>
    </a>
  );
}

function MomiosCard({ matchId }) {
  const mk = window.CF.momios[matchId] || window.CF.momios.m1;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 14, background: `${CAL_RED}14`, border: `1px solid ${CAL_RED}40`, borderRadius: 10, padding: '10px 12px', flexWrap: 'wrap' }}>
        <CalienteLogo h={15} />
        <span style={{ fontSize: 12, color: C.fg, fontWeight: 600 }}>Apuesta con momios oficiales</span>
        <span style={{ marginLeft: 'auto', fontSize: 9.5, color: C.mut, fontWeight: 700, whiteSpace: 'nowrap' }}>+18</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {Object.entries(mk).map(([market, opts]) => (
          <div key={market}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: C.mut, marginBottom: 7 }}>{market}</div>
            <div style={{ display: 'flex', gap: 7 }}>
              {opts.map(([l, v]) => <OddsBtn key={l} label={l} val={v} />)}
            </div>
          </div>
        ))}
      </div>
      <a href={CALIENTE_URL} target="_blank" rel="noopener" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9, textDecoration: 'none', marginTop: 16, background: CAL_RED, color: '#fff', borderRadius: 12, padding: '14px', fontWeight: 800, fontSize: 15 }}>
        Apostar en <CalienteLogo h={15} /> <Icon name="share" size={16} color="#fff" />
      </a>
      <div style={{ fontSize: 10.5, color: C.mut, textAlign: 'center', marginTop: 11, lineHeight: 1.5 }}>Al tocar un momio sales a Caliente.mx para completar tu apuesta · momios de muestra · juega responsable</div>
    </div>
  );
}

// ── Momios compactos para listas ──────────────────────────────
function OddsBarCompact({ odds }) {
  if (!odds) return null;
  return (
    <div style={{ marginTop: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
        <CalienteLogo h={11} />
        <span style={{ fontSize: 10, color: C.mut, fontWeight: 700, letterSpacing: 0.2 }}>APOSTAR · MOMIOS</span>
      </div>
      <div style={{ display: 'flex', gap: 5 }}>
        {[['L', odds[0]], ['E', odds[1]], ['V', odds[2]]].map(([l, v]) => (
          <a key={l} href={CALIENTE_URL} target="_blank" rel="noopener" onClick={(e) => e.stopPropagation()} style={{ flex: 1, textDecoration: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, background: `${CAL_RED}14`, border: `1px solid ${CAL_RED}45`, borderRadius: 8, padding: '6px 4px' }}>
            <span style={{ fontSize: 10, color: C.mut, fontWeight: 700 }}>{l}</span>
            <span className="num" style={{ fontSize: 12.5, fontWeight: 800, color: '#fff' }}>{v.toFixed(2)}</span>
          </a>
        ))}
      </div>
    </div>
  );
}

// ── MATCH CENTER ──────────────────────────────────────────────
function MatchCenter({ matchId, onBack, go }) {
  const CF = window.CF, T = CF.teams;
  const m = CF.liveMatches.find((x) => x.id === matchId) || CF.liveMatches[0];
  const d = CF.matchDetail[m.id] || CF.matchDetail.m1;
  const [tab, setTab] = React.useState('resumen');
  const live = m.status === 'live';
  const evIcon = { goal: '⚽', yellow: '🟨', red: '🟥', sub: '🔁' };

  return (
    <div className="animate-slide-up">
      <StackHeader title={`${T[m.home].short} vs ${T[m.away].short}`} onBack={onBack} right={live ? <LiveBadge minute={m.minute} /> : null} />
      <div style={{ padding: '0 18px 24px' }}>
        {/* marcador */}
        <Card pad={16} style={{ marginBottom: 14 }}>
          <div style={{ fontSize: 11, color: C.mut, fontWeight: 600, textAlign: 'center', marginBottom: 12, textTransform: 'uppercase', letterSpacing: 0.4 }}>{d.comp} · {d.venue}</div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16 }}>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}><Crest team={m.home} size={50} /><span style={{ fontWeight: 700, fontSize: 13, textAlign: 'center' }}>{T[m.home].name}</span></div>
            <div style={{ textAlign: 'center' }}>
              <div className="num" style={{ fontWeight: 900, fontSize: 38, lineHeight: 1 }}>{m.hs ?? 0} <span style={{ color: C.mut }}>-</span> {m.as ?? 0}</div>
              {live && <span className="num" style={{ color: C.destructive, fontWeight: 700, fontSize: 13 }}>{m.minute}'</span>}
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}><Crest team={m.away} size={50} /><span style={{ fontWeight: 700, fontSize: 13, textAlign: 'center' }}>{T[m.away].name}</span></div>
          </div>
          <button onClick={() => go('channel')} style={{ width: '100%', marginTop: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: C.primary, color: '#fff', border: 'none', borderRadius: 10, padding: '11px', fontFamily: 'inherit', fontWeight: 700, fontSize: 13.5, cursor: 'pointer' }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="#fff"><path d="M8 5.5v13l11-6.5z" /></svg> Ver transmisión en vivo
          </button>
        </Card>

        {/* tabs */}
        <div className="noscroll" style={{ display: 'flex', gap: 7, overflowX: 'auto', marginBottom: 16 }}>
          {[['resumen', 'Resumen'], ['stats', 'Estadísticas'], ['momios', 'Momios'], ['chat', 'Chat en vivo'], ['fantasy', 'Mi fantasy']].map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{ flexShrink: 0, padding: '8px 14px', borderRadius: 999, fontFamily: 'inherit', fontWeight: 700, fontSize: 13, cursor: 'pointer', border: `1px solid ${tab === k ? C.primary : C.border}`, background: tab === k ? C.primary : C.secondary, color: tab === k ? '#fff' : C.mut, display: 'flex', alignItems: 'center', gap: 6 }}>
              {k === 'chat' && <LiveDot size={5} color={tab === k ? '#fff' : C.destructive} />}{l}
            </button>
          ))}
        </div>

        {tab === 'resumen' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {d.events.slice().reverse().map((e, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, flexDirection: e.team === 'away' ? 'row-reverse' : 'row', textAlign: e.team === 'away' ? 'right' : 'left' }}>
                <span className="num" style={{ width: 32, color: C.mut, fontWeight: 700, fontSize: 13 }}>{e.min}'</span>
                <span style={{ fontSize: 18 }}>{evIcon[e.type]}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 700, fontSize: 14 }}>{e.player}</div>
                  {e.note && <div style={{ fontSize: 11.5, color: e.note.includes('pts') ? C.gold : C.mut, fontWeight: 600 }}>{e.note}</div>}
                </div>
              </div>
            ))}
          </div>
        )}

        {tab === 'stats' && (
          <div>
            {Object.entries(d.stats).map(([label, [a, b]]) => {
              const tot = a + b || 1, pa = label === 'Posesión' ? a : Math.round(a / tot * 100);
              return (
                <div key={label} style={{ marginBottom: 16 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, fontWeight: 700, marginBottom: 6 }}>
                    <span className="num">{label === 'Posesión' ? a + '%' : a}</span>
                    <span style={{ color: C.mut, fontSize: 12, textTransform: 'uppercase', letterSpacing: 0.4 }}>{label}</span>
                    <span className="num">{label === 'Posesión' ? b + '%' : b}</span>
                  </div>
                  <div style={{ display: 'flex', gap: 4, height: 6 }}>
                    <div style={{ flex: pa, background: C.primary, borderRadius: 9 }} /><div style={{ flex: 100 - pa, background: C.secondary, borderRadius: 9 }} />
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {tab === 'chat' && <LiveChat matchId={m.id} />}

        {tab === 'momios' && <MomiosCard matchId={m.id} />}

        {tab === 'fantasy' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Card pad={14} style={{ background: 'linear-gradient(135deg, hsl(var(--primary) / 0.14), hsl(var(--surface)))', border: '1px solid hsl(var(--primary) / 0.3)' }}>
              <div style={{ fontSize: 11.5, color: C.mut, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.4 }}>Tus jugadores en este partido</div>
              <div className="num text-gradient-primary" style={{ fontWeight: 900, fontSize: 28 }}>+23 pts</div>
            </Card>
            {['p1', 'p5', 'p14', 'p22'].map((id) => {
              const p = CF.pById(id); if (!p) return null;
              const pts = p.form[4];
              return (
                <Card key={id} pad={12} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <PlayerAvatar player={p} size={36} />
                  <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14 }}>{p.name}</div><div style={{ fontSize: 11.5, color: C.mut }}><PosPill pos={p.pos} /> {T[p.team].name}</div></div>
                  <span className="num" style={{ fontWeight: 900, fontSize: 17, color: C.primary }}>+{pts}</span>
                </Card>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

// ── NOTICIAS ──────────────────────────────────────────────────
function NewsScreen({ onBack, go }) {
  const CF = window.CF;
  const big = CF.news.find((n) => n.big);
  const rest = CF.news.filter((n) => !n.big);
  return (
    <div className="animate-slide-up">
      <StackHeader title="Noticias" onBack={onBack} />
      <div style={{ padding: '0 18px 24px' }}>
        {big && (
          <Card pad={0} onClick={() => go('article', big.id)} style={{ overflow: 'hidden', marginBottom: 16 }}>
            <Poster h={170} r={0} kind="stadium" />
            <div style={{ padding: 15 }}>
              <span style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: 0.5, color: C.primary }}>{big.tag}</span>
              <div style={{ fontWeight: 800, fontSize: 17, lineHeight: 1.25, margin: '7px 0 9px', textWrap: 'pretty' }}>{big.title}</div>
              <div style={{ fontSize: 12, color: C.mut, display: 'flex', gap: 10 }}><span>{big.time}</span><span>· {big.read} de lectura</span></div>
            </div>
          </Card>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {rest.map((n) => (
            <div key={n.id} onClick={() => go('article', n.id)} style={{ display: 'flex', gap: 13, cursor: 'pointer', alignItems: 'center' }}>
              <Poster h={72} r={11} kind={n.tag === 'LAYV10' ? 'hero' : 'plain'} style={{ width: 96, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: 0.5, color: C.primary }}>{n.tag}</span>
                <div style={{ fontWeight: 600, fontSize: 14, lineHeight: 1.3, margin: '3px 0 5px', textWrap: 'pretty' }}>{n.title}</div>
                <div style={{ fontSize: 11, color: C.mut }}>{n.time} · {n.read}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ArticleScreen({ articleId, onBack }) {
  const CF = window.CF;
  const n = CF.news.find((x) => x.id === articleId) || CF.news[0];
  const paras = [
    'La Jornada 14 dejó más preguntas que respuestas, y aquí te las desmenuzamos sin filtros — como solo en Layvtime.',
    'El golazo de Veiga no solo le dio los tres puntos al América: también movió el tablero del fantasy, donde miles de mánagers lo tenían como capitán y se llevaron 12 puntos dobles.',
    'En la otra cancha, Cruz Azul sorprendió en CU con una versión sólida de C. Rodríguez, autor de un doblete que ya lo coloca entre los más valiosos de la jornada.',
    'La pregunta para la próxima fecha: ¿es momento de soltar a tus defensas caros y apostar por el ataque? Nuestro panel debate y tú decides en los comentarios.',
  ];
  return (
    <div className="animate-slide-up">
      <StackHeader title="Noticia" onBack={onBack} right={<button style={{ width: 36, height: 36, borderRadius: 999, background: C.secondary, border: `1px solid ${C.border}`, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}><Icon name="share" size={16} color={C.mut} /></button>} />
      <div style={{ padding: '0 18px 30px' }}>
        <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: 0.5, color: C.primary }}>{n.tag}</span>
        <h1 style={{ fontSize: 24, fontWeight: 900, lineHeight: 1.15, margin: '8px 0 10px', textWrap: 'pretty' }}>{n.title}</h1>
        <div style={{ fontSize: 12.5, color: C.mut, marginBottom: 16, display: 'flex', gap: 10 }}><span>{n.time}</span><span>· {n.read} de lectura</span></div>
        <Poster h={196} r={14} kind="stadium" style={{ marginBottom: 16 }} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {paras.map((p, i) => <p key={i} style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: i === 0 ? C.fg : 'hsl(var(--foreground) / 0.82)' }}>{p}</p>)}
        </div>
      </div>
    </div>
  );
}

// ── TOASTS de fantasy en vivo ─────────────────────────────────
function FantasyToasts({ active }) {
  const CF = window.CF;
  const [toasts, setToasts] = React.useState([]);
  React.useEffect(() => {
    if (!active) return;
    let i = 0;
    const push = () => {
      const a = CF.liveAlerts[i % CF.liveAlerts.length]; i++;
      const id = 't' + Date.now();
      setToasts((t) => [...t, { ...a, id }]);
      setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 4200);
    };
    const first = setTimeout(push, 3500);
    const iv = setInterval(push, 9000);
    return () => { clearTimeout(first); clearInterval(iv); };
  }, [active]);

  return (
    <div style={{ position: 'absolute', top: 46, left: 12, right: 12, zIndex: 60, display: 'flex', flexDirection: 'column', gap: 8, pointerEvents: 'none' }}>
      {toasts.map((t) => (
        <div key={t.id} style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'hsl(var(--popover))', border: '1px solid hsl(var(--primary) / 0.4)', borderRadius: 13, padding: '10px 13px', boxShadow: '0 12px 32px rgba(0,0,0,0.5)', animation: 'toastIn .35s cubic-bezier(.2,.9,.3,1.2)' }}>
          <div style={{ position: 'relative', flexShrink: 0 }}><Crest team={t.team} size={30} /><span style={{ position: 'absolute', bottom: -4, right: -5, fontSize: 13 }}>⚽</span></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 13 }}>{t.msg}</div>
            <div style={{ fontSize: 11.5, color: C.mut, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.player} · {T_name(t.team)}</div>
          </div>
          <span className="num" style={{ fontWeight: 900, fontSize: 15, color: C.gold, flexShrink: 0 }}>{t.pts}</span>
        </div>
      ))}
    </div>
  );
}
function T_name(k) { const t = window.CF.teams[k]; return t ? t.name : ''; }

Object.assign(window, { LiveChat, MatchCenter, NewsScreen, ArticleScreen, FantasyToasts, MomiosCard, OddsBarCompact });
