// SATMELI — Chat simulado del bot de Telegram (canal estrella).

function TgTime({ children, light }) {
  return <span style={{ fontFamily: 'var(--mono)', fontSize: 9.5, color: light ? 'rgba(255,255,255,0.75)' : 'var(--tg-time)', marginLeft: 6, verticalAlign: 'bottom' }}>{children}</span>;
}

function BotBubble({ children, time, tail }) {
  return (
    <div style={{ alignSelf: 'flex-start', maxWidth: '85%', background: 'var(--tg-bot)', color: 'var(--tg-bot-text)',
      borderRadius: '14px 14px 14px 4px', padding: '8px 11px 7px', boxShadow: '0 1px 1px rgba(0,0,0,0.12)',
      fontFamily: 'var(--font)', fontSize: 14, lineHeight: 1.45, letterSpacing: '-0.01em', position: 'relative' }}>
      {children}
      {time && <div style={{ textAlign: 'right', marginTop: 2 }}><TgTime>{time}</TgTime></div>}
    </div>
  );
}

function UserBubble({ children, time }) {
  return (
    <div style={{ alignSelf: 'flex-end', maxWidth: '80%', background: 'var(--tg-user)', color: '#fff',
      borderRadius: '14px 14px 4px 14px', padding: '8px 11px 7px', fontFamily: 'var(--font)', fontSize: 14,
      lineHeight: 1.45, letterSpacing: '-0.01em', boxShadow: '0 1px 1px rgba(0,0,0,0.12)' }}>
      {children}
      {time && <div style={{ textAlign: 'right', marginTop: 2 }}><TgTime light>{time} ✓✓</TgTime></div>}
    </div>
  );
}

function BotAlertBubble({ n, search, onGoMeli, time }) {
  const cat = search ? search.cat : 'tech';
  const delta = deltaInfo(n.price, n.target);
  return (
    <div style={{ alignSelf: 'flex-start', maxWidth: '88%', width: 300, background: 'var(--tg-bot)', color: 'var(--tg-bot-text)',
      borderRadius: '14px 14px 14px 4px', overflow: 'hidden', boxShadow: '0 1px 2px rgba(0,0,0,0.18)' }}>
      {/* encabezado del bot card */}
      <div style={{ padding: '9px 11px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 7 }}>
          <span style={{ color: 'var(--tg-accent)', display: 'flex' }}><Icon name="zap" size={14} fill="var(--tg-accent)" stroke={0} /></span>
          <span style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 700, color: 'var(--tg-accent)' }}>Nuevo match</span>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--tg-time)', marginLeft: 'auto' }}>{search ? search.term : ''}</span>
        </div>
      </div>
      {/* "foto" del producto */}
      <div style={{ padding: '0 11px' }}>
        <div style={{ width: '100%', height: 150, borderRadius: 10, overflow: 'hidden', position: 'relative',
          background: `color-mix(in srgb, ${SAT_CATS[cat].tint} 20%, var(--tg-bot))`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ color: SAT_CATS[cat].tint, opacity: 0.9 }}><Icon name={SAT_CATS[cat].icon} size={48} stroke={1.5} /></div>
          <span style={{ position: 'absolute', left: 8, bottom: 8, fontFamily: 'var(--mono)', fontSize: 9, color: SAT_CATS[cat].tint,
            background: 'color-mix(in srgb, var(--tg-bot) 80%, transparent)', padding: '2px 6px', borderRadius: 5 }}>FOTO PUBLICACIÓN</span>
        </div>
      </div>
      <div style={{ padding: '9px 11px 11px' }}>
        <div style={{ fontFamily: 'var(--font)', fontSize: 13, fontWeight: 500, lineHeight: 1.35, marginBottom: 7,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{n.title}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 9 }}>
          <span style={{ fontFamily: 'var(--font)', fontSize: 19, fontWeight: 700, letterSpacing: '-0.02em' }}>{fmtARS(n.price)}</span>
          {delta && delta.under && <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, fontWeight: 700, color: 'var(--tg-accent)' }}>↓ {delta.pct}% bajo tu tope</span>}
        </div>
        <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--tg-time)', marginBottom: 10 }}>{condLabel(n.condition)} · {n.location}</div>
        {/* botones inline de Telegram */}
        <button type="button" onClick={() => onGoMeli(n)} style={{ width: '100%', padding: '9px', borderRadius: 8, border: 'none',
          background: 'var(--tg-btn)', color: 'var(--tg-accent)', fontFamily: 'var(--font)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
          <Icon name="upRight" size={15} /> Ver publicación en MELI
        </button>
        <div style={{ textAlign: 'right', marginTop: 3 }}><TgTime>{time}</TgTime></div>
      </div>
    </div>
  );
}

function CmdChip({ children }) {
  return <span style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--tg-accent)', background: 'var(--tg-btn)',
    padding: '7px 12px', borderRadius: 999, whiteSpace: 'nowrap', cursor: 'pointer' }}>{children}</span>;
}

function TelegramChat({ dark, mode, onBack, notifs, searches }) {
  const byId = Object.fromEntries(searches.map((s) => [s.id, s]));
  const goMeli = (n) => window.open(n.permalink || 'https://www.mercadolibre.com.ar', '_blank');

  // Estado real del bot
  const [botStatus, setBotStatus] = React.useState(null);
  React.useEffect(() => {
    apiFetch('/telegram/status').then(setBotStatus).catch(() => setBotStatus(null));
  }, []);

  const botUsername = (botStatus && botStatus.username) || 'SatmeliBot';
  const botConnected = botStatus && botStatus.connected;
  const chatLinked = botStatus && botStatus.chatLinked;

  // Mostrar las 2 alertas no leídas más recientes en el chat simulado
  const recentAlerts = notifs.filter((n) => !n.read).slice(0, 2);
  const alert1 = recentAlerts[0] || null;
  const alert2 = recentAlerts[1] || null;
  const activeCount = searches.filter((s) => s.active).length;

  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', background: 'var(--tg-bg)' }}>
      {/* patrón de fondo sutil */}
      <div style={{ position: 'absolute', inset: 0, opacity: dark ? 0.5 : 0.45, pointerEvents: 'none',
        backgroundImage: 'radial-gradient(var(--tg-dot) 1px, transparent 1px)', backgroundSize: '22px 22px' }} />

      {/* header */}
      <div style={{ position: 'relative', zIndex: 2, display: 'flex', alignItems: 'center', gap: 11, padding: mode === 'mobile' ? '46px 14px 12px' : '12px 14px',
        background: 'var(--tg-header)', color: '#fff', boxShadow: '0 1px 6px rgba(0,0,0,0.18)', flexShrink: 0 }}>
        <button type="button" onClick={onBack} style={{ background: 'transparent', border: 'none', color: '#fff', cursor: 'pointer', display: 'flex', padding: 4, marginLeft: -4 }}>
          <Icon name="chevL" size={22} />
        </button>
        <div style={{ width: 40, height: 40, borderRadius: 999, background: 'rgba(255,255,255,0.2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="radar" size={22} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font)', fontSize: 15.5, fontWeight: 600, letterSpacing: '-0.01em' }}>@{botUsername}</div>
          <div style={{ fontFamily: 'var(--font)', fontSize: 12, color: 'rgba(255,255,255,0.8)' }}>
            {botConnected ? (chatLinked ? 'bot · alertas activas' : 'bot · enviá /start para vincular') : 'bot · no configurado'}
          </div>
        </div>
        {botConnected && (
          <a href={`https://t.me/${botUsername}`} target="_blank" rel="noopener noreferrer"
            style={{ color: '#fff', background: 'rgba(255,255,255,0.15)', borderRadius: 8, padding: '5px 10px',
              fontFamily: 'var(--font)', fontSize: 12, fontWeight: 600, textDecoration: 'none' }}>
            Abrir
          </a>
        )}
      </div>

      {/* mensajes */}
      <div className="sat-tg-scroll" style={{ position: 'relative', zIndex: 1, flex: 1, overflowY: 'auto', padding: '16px 14px 10px',
        display: 'flex', flexDirection: 'column', gap: 8 }}>
        <div style={{ alignSelf: 'center', fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--tg-bot-text)', background: 'var(--tg-stamp)',
          padding: '4px 12px', borderRadius: 999, marginBottom: 4 }}>HOY</div>

        <UserBubble time="9:32">/start</UserBubble>
        <BotBubble time="9:32">
          👋 ¡Hola! Soy el bot de <b>SATMELI</b>. Te aviso acá apenas aparezca en Mercado Libre algo que estás buscando.
        </BotBubble>
        <BotBubble time="9:32">
          Tu cuenta ya está vinculada con la web.<br />
          <span style={{ color: 'var(--tg-accent)', fontWeight: 600 }}>✓ {activeCount} centinela{activeCount !== 1 ? 's' : ''} activo{activeCount !== 1 ? 's' : ''}</span> monitoreando ahora mismo.
        </BotBubble>

        <div style={{ alignSelf: 'center', fontFamily: 'var(--mono)', fontSize: 10.5, color: 'var(--tg-bot-text)', background: 'var(--tg-stamp)',
          padding: '4px 12px', borderRadius: 999, margin: '8px 0 4px' }}>hace instantes</div>

        {alert1 && <BotAlertBubble n={alert1} search={byId[alert1.searchId]} onGoMeli={goMeli} time="recién" />}
        {alert1 && (
          <BotBubble time="recién">
            Apareció <b>1 publicación nueva</b> para <b>{byId[alert1.searchId] ? byId[alert1.searchId].term : 'tu búsqueda'}</b> 🎯
          </BotBubble>
        )}
        {alert2 && <BotAlertBubble n={alert2} search={byId[alert2.searchId]} onGoMeli={goMeli} time="recién" />}
        {!alert1 && !alert2 && (
          <BotBubble time="recién">
            Aún no hay coincidencias nuevas. ¡Te aviso cuando aparezca algo! 🔍
          </BotBubble>
        )}

        <UserBubble time="recién">/activas</UserBubble>
        <BotBubble time="recién">
          📡 <b>Tus centinelas</b><br />
          {searches.filter((s) => s.active).map((s) => (
            <span key={s.id}>• {s.term} — <span style={{ color: 'var(--tg-accent)' }}>{s.matches} hallazgos</span><br /></span>
          ))}
          {!searches.some((s) => s.active) && <span style={{ color: 'var(--tg-time)' }}>No tenés centinelas activos.</span>}
          <span style={{ color: 'var(--tg-time)' }}>Escribí /pausar &lt;id&gt; para silenciar una.</span>
        </BotBubble>
      </div>

      {/* comandos + input */}
      <div style={{ position: 'relative', zIndex: 2, flexShrink: 0 }}>
        <div className="sat-hscroll" style={{ display: 'flex', gap: 8, padding: '8px 14px', overflowX: 'auto' }}>
          <CmdChip>/activas</CmdChip><CmdChip>/pausar</CmdChip><CmdChip>/silenciar 1h</CmdChip><CmdChip>/nueva</CmdChip>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 14px 22px', background: 'var(--tg-header-soft)' }}>
          <div style={{ flex: 1, background: 'var(--tg-input)', borderRadius: 999, padding: '11px 16px', fontFamily: 'var(--font)', fontSize: 14, color: 'var(--tg-time)' }}>Mensaje</div>
          <div style={{ width: 42, height: 42, borderRadius: 999, background: 'var(--tg-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: '#fff' }}>
            <Icon name="send" size={20} />
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { TelegramChat });
