// discord-section.jsx — Centerpiece: interactive Discord bot demo
const { useState: useStateD, useEffect: useEffectD, useRef: useRefD } = React;

/* Bot commands the user can click through */
const COMMANDS = [
  {
    id: 'leaderboard',
    cmd: '.leaderboard',
    args: 'game:tsb',
    desc: 'Top global en vivo. Filtros por juego, región y phase.',
    response: 'rank',
  },
  {
    id: 'clan',
    cmd: '.clan',
    args: 'tag:ONW',
    desc: 'Información y roster del clan, sincronizado entre servers.',
    response: 'clan',
  },
  {
    id: 'tournament',
    cmd: '.tournament',
    args: 'create open-mayo',
    desc: 'Brackets, llaves y reportes automáticos.',
    response: 'torneo',
  },
  {
    id: 'verify',
    cmd: '.verify',
    args: 'cross-server',
    desc: 'Verificación por bot. Válida en 30+ servers de la red.',
    response: 'verify',
  },
  {
    id: 'jarvis',
    cmd: '.jarvis',
    args: '¿quién está cerca de Phase 1?',
    desc: 'Asistente IA con contexto del servidor y del juego.',
    response: 'jarvis',
  },
  {
    id: 'antiraid',
    cmd: '.antiraid',
    args: 'panel',
    desc: 'Anti-raid v2 con whitelist visual y alertas DM al staff.',
    response: 'antiraid',
  },
];

function DiscordSection() {
  const ref = useReveal();
  const [active, setActive] = useStateD('leaderboard');
  const [typedArgs, setTypedArgs] = useStateD('');
  const [showResponse, setShowResponse] = useStateD(true);
  const cmd = COMMANDS.find(c => c.id === active);

  // Type-out animation for args
  useEffectD(() => {
    setShowResponse(false);
    setTypedArgs('');
    const full = cmd.args;
    let i = 0;
    const t = setInterval(() => {
      i++;
      setTypedArgs(full.slice(0, i));
      if (i >= full.length) {
        clearInterval(t);
        setTimeout(() => setShowResponse(true), 400);
      }
    }, 25);
    return () => clearInterval(t);
  }, [active]);

  return (
    <section id="discord" style={{
      padding: '120px 0',
      position: 'relative',
      background: 'var(--surface)',
      borderTop: '1px solid var(--border)',
      borderBottom: '1px solid var(--border)',
    }}>
      <div className="container">
        <SectionHeader
          eyebrow="02 · Discord bot · pieza central"
          title={<>Un bot que <span className="emph">opera la plataforma.</span></>}
          subtitle="No es un wrapper. Es el sistema operativo de la comunidad: rankings, torneos, verificación, sanciones y coaching, todo desde slash commands."
          action={
            <a href={(typeof window !== 'undefined' && window.OW_INVITE_BOT) || 'https://discord.com/api/oauth2/authorize?client_id=1469356955108901129&permissions=8&scope=bot%20applications.commands'} target="_blank" rel="noopener noreferrer" className="btn btn-discord" style={{ fontSize: 13 }}>
              <Icon.Discord size={15}/> Invitar bot
            </a>
          }
        />

        <div ref={ref} className="reveal" style={{
          marginTop: 56,
          display: 'grid',
          gridTemplateColumns: '320px 1fr',
          gap: 20,
        }} id="discord-grid">
          {/* Left: command palette */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Comandos</div>
            {COMMANDS.map(c => {
              const isActive = c.id === active;
              return (
                <button key={c.id} onClick={() => setActive(c.id)}
                  style={{
                    display: 'block', textAlign: 'left',
                    padding: '14px 16px',
                    background: isActive ? 'var(--surface-2)' : 'transparent',
                    border: `1px solid ${isActive ? 'var(--border-strong)' : 'var(--border)'}`,
                    borderLeft: `2px solid ${isActive ? 'var(--accent)' : 'var(--border)'}`,
                    borderRadius: 10,
                    cursor: 'pointer',
                    color: 'var(--text)',
                    fontFamily: 'inherit',
                    transition: 'all .2s',
                  }}>
                  <div className="mono" style={{ fontSize: 13, color: isActive ? 'var(--accent)' : 'var(--text-dim)', fontWeight: 500 }}>
                    {c.cmd}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 4, lineHeight: 1.4 }}>
                    {c.desc}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Right: Discord mock */}
          <DiscordMock command={cmd} typedArgs={typedArgs} showResponse={showResponse}/>
        </div>

        {/* Feature row */}
        <div style={{
          marginTop: 56,
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16,
        }} id="bot-features">
          {[
            { icon: Icon.Globe, title: 'Multi-guild', desc: 'Un bot, muchos servers. Config aislada por server, rankings unificados.' },
            { icon: Icon.Shield, title: 'Verificación cross-server', desc: 'Una verificación vale en toda la red. 30+ servers conectados.' },
            { icon: Icon.Bolt, title: '14 módulos prendibles', desc: 'Cada server activa lo que usa: moderation, tournaments, music, dev, IA.' },
            { icon: Icon.Sparkle, title: 'JARVIS IA integrado', desc: 'Asistente con contexto del servidor: queries, análisis y resumen.' },
          ].map(f => (
            <div key={f.title} style={{ padding: '24px 4px 0', borderTop: '1px solid var(--border)' }}>
              <f.icon size={20} style={{ color: 'var(--accent)', marginBottom: 14 }}/>
              <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6, letterSpacing: '-0.01em' }}>{f.title}</div>
              <div style={{ fontSize: 13, color: 'var(--text-dim)', lineHeight: 1.5 }}>{f.desc}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`
        @media (max-width: 980px) { #discord-grid { grid-template-columns: 1fr !important; } }
        @media (max-width: 900px) { #bot-features { grid-template-columns: repeat(2, 1fr) !important; } }
        @media (max-width: 540px) { #bot-features { grid-template-columns: 1fr !important; } }
      `}</style>
    </section>
  );
}

/* Discord-styled chat mock */
function DiscordMock({ command, typedArgs, showResponse }) {
  return (
    <div className="dm-mock" style={{
      background: '#1E1F22',
      borderRadius: 14,
      overflow: 'hidden',
      border: '1px solid rgba(255,255,255,0.06)',
      boxShadow: 'var(--shadow-lg)',
      display: 'grid',
      gridTemplateColumns: '64px 200px 1fr',
      minHeight: 540,
      color: '#DBDEE1',
    }}>
      {/* Server rail */}
      <div className="dm-rail-servers" style={{ background: '#1A1B1E', padding: '12px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 14,
          background: 'linear-gradient(135deg, var(--accent), var(--accent-2))',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 700, color: 'white', fontSize: 13, fontFamily: 'Geist Mono',
        }}>OW</div>
      </div>

      {/* Channel rail */}
      <div className="dm-rail-channels" style={{ background: '#2B2D31', padding: '12px 0' }}>
        <div style={{ padding: '8px 14px 16px', borderBottom: '1px solid rgba(0,0,0,0.2)', boxShadow: '0 1px 0 rgba(255,255,255,0.04)' }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#F2F3F5', letterSpacing: '-0.01em' }}>Servidor OneWay</div>
          <div style={{ fontSize: 11, color: '#949BA4', marginTop: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--live)' }}/>
            sede principal
          </div>
        </div>
        <div style={{ padding: '12px 8px' }}>
          <div style={{ fontSize: 11, color: '#949BA4', padding: '4px 8px', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Competitivo</div>
          {[
            { name: 'rankings', active: false },
            { name: 'comandos-bot', active: true },
            { name: 'torneos', active: false },
            { name: 'reportes', active: false },
            { name: 'directorio', active: false },
          ].map(c => (
            <div key={c.name} style={{
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '6px 8px', margin: '1px 0',
              borderRadius: 4,
              background: c.active ? 'rgba(255,255,255,0.06)' : 'transparent',
              color: c.active ? '#F2F3F5' : '#949BA4',
              fontSize: 14, fontWeight: c.active ? 500 : 400,
              cursor: 'default',
            }}>
              <Icon.Hash size={16}/>
              {c.name}
            </div>
          ))}
        </div>
      </div>

      {/* Main chat */}
      <div style={{ display: 'flex', flexDirection: 'column', minWidth: 0 }}>
        {/* Header */}
        <div style={{
          padding: '12px 18px',
          borderBottom: '1px solid rgba(0,0,0,0.2)',
          boxShadow: '0 1px 0 rgba(255,255,255,0.04)',
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <Icon.Hash size={20} style={{ color: '#80848E' }}/>
          <span style={{ fontSize: 15, fontWeight: 600, color: '#F2F3F5' }}>comandos-bot</span>
        </div>

        {/* Messages */}
        <div style={{ flex: 1, padding: '20px 18px', display: 'flex', flexDirection: 'column', gap: 18, overflowY: 'auto' }}>
          {/* User command */}
          <Message
            user="usuario"
            color="#5B8CFF"
            time="—"
            content={
              <span>
                <span style={{ color: '#00A8FC' }}>{command.cmd}</span>
                {' '}
                <span style={{ color: '#DBDEE1' }}>{typedArgs}</span>
                <span style={{ display: 'inline-block', width: 7, height: 16, background: '#00A8FC', verticalAlign: 'text-bottom', marginLeft: 1, animation: 'caret 1s steps(2) infinite' }}/>
              </span>
            }
          />

          {/* Bot response */}
          {showResponse && (
            <div style={{ animation: 'fadeUp .35s cubic-bezier(.2,.7,.2,1)' }}>
              <BotResponse type={command.response}/>
            </div>
          )}
        </div>

        {/* Input bar */}
        <div style={{ padding: '0 16px 18px' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            background: '#383A40',
            borderRadius: 8, padding: '10px 14px',
          }}>
            <Icon.Slash size={18} style={{ color: '#B5BAC1' }}/>
            <span style={{ color: '#80848E', fontSize: 14 }}>Enviar mensaje a #comandos-bot</span>
            <div style={{ flex: 1 }}/>
            <Icon.Send size={18} style={{ color: '#80848E' }}/>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes caret { 50% { opacity: 0; } }
        @keyframes fadeUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
        @media (max-width: 760px) {
          .dm-mock { grid-template-columns: 1fr !important; min-height: 0 !important; }
          .dm-mock .dm-rail-servers, .dm-mock .dm-rail-channels { display: none !important; }
        }
      `}</style>
    </div>
  );
}

function Message({ user, color, time, content }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 14 }}>
      <div style={{
        width: 40, height: 40, borderRadius: '50%',
        background: color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: 'white', fontWeight: 600, fontSize: 14,
      }}>{user[0]}</div>
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 15, fontWeight: 500, color: '#F2F3F5' }}>{user}</span>
          <span style={{ fontSize: 11, color: '#949BA4' }}>hoy a las {time}</span>
        </div>
        <div style={{ fontSize: 14, fontFamily: 'Geist Mono', marginTop: 2, color: '#DBDEE1' }}>
          {content}
        </div>
      </div>
    </div>
  );
}

function BotResponse({ type }) {
  if (type === 'rank') {
    return (
      <BotMessage>
        <Embed color="var(--accent)">
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: 'linear-gradient(135deg, #5B8CFF, #1A1E5C)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontWeight: 700, fontFamily: 'Geist Mono' }}>?</div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: '#F2F3F5' }}>@usuario</div>
              <div style={{ fontSize: 12, color: '#949BA4', fontFamily: 'Geist Mono' }}>ejemplo · región · juego</div>
            </div>
          </div>
          <EmbedGrid>
            <EmbedField label="ELO" value="—"/>
            <EmbedField label="Phase" value="—"/>
            <EmbedField label="Rank global" value="—"/>
            <EmbedField label="Win rate" value="—"/>
            <EmbedField label="Matches" value="—"/>
            <EmbedField label="Tendencia" value="—"/>
          </EmbedGrid>
          <div style={{ marginTop: 14, padding: '10px 12px', background: 'rgba(255,255,255,0.04)', borderRadius: 6, fontSize: 12, color: '#B5BAC1' }}>
            Ejemplo de salida del comando · datos reales tras vincular tu cuenta.
          </div>
        </Embed>
      </BotMessage>
    );
  }
  if (type === 'clan') {
    return (
      <BotMessage>
        <Embed color="var(--accent-2)">
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
            <div style={{ width: 44, height: 44, borderRadius: 10, background: 'linear-gradient(135deg, #5B8CFF, #6FE0FF)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontWeight: 700, fontSize: 13, fontFamily: 'Geist Mono' }}>—</div>
            <div>
              <div style={{ fontSize: 15, fontWeight: 600, color: '#F2F3F5' }}>Clan ejemplo <span style={{ fontSize: 11, padding: '2px 7px', borderRadius: 999, background: 'rgba(34,197,94,0.18)', color: '#22C55E', marginLeft: 6, verticalAlign: 'middle' }}>verificado</span></div>
              <div style={{ fontSize: 12, color: '#949BA4', fontFamily: 'Geist Mono' }}>Líder @leader · región</div>
            </div>
          </div>
          <EmbedGrid>
            <EmbedField label="Miembros" value="—"/>
            <EmbedField label="ELO promedio" value="—"/>
            <EmbedField label="Ranking clanes" value="—"/>
            <EmbedField label="Win rate" value="—"/>
            <EmbedField label="Fundado" value="—"/>
            <EmbedField label="Torneos ganados" value="—"/>
          </EmbedGrid>
        </Embed>
      </BotMessage>
    );
  }
  if (type === 'torneo') {
    return (
      <BotMessage>
        <Embed color="var(--warn)">
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 13, color: '#949BA4', fontFamily: 'Geist Mono', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Torneo · ejemplo</div>
            <div style={{ fontSize: 18, fontWeight: 600, color: '#F2F3F5', marginTop: 4 }}>Estructura de torneo</div>
          </div>
          <EmbedGrid>
            <EmbedField label="Inscritos" value="—"/>
            <EmbedField label="Inicia" value="—"/>
            <EmbedField label="Formato" value="—"/>
            <EmbedField label="Premio" value="—"/>
          </EmbedGrid>
          <div style={{ marginTop: 14, display: 'flex', gap: 8 }}>
            <span style={{ padding: '7px 12px', background: 'var(--live)', color: 'white', borderRadius: 6, fontSize: 13, fontWeight: 500 }}>✓ Inscribirme</span>
            <span style={{ padding: '7px 12px', background: 'rgba(255,255,255,0.06)', color: '#DBDEE1', borderRadius: 6, fontSize: 13 }}>Ver bracket</span>
          </div>
        </Embed>
      </BotMessage>
    );
  }
  if (type === 'verify') {
    return (
      <BotMessage>
        <Embed color="var(--danger)">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <Icon.Warn size={20} style={{ color: 'var(--danger)' }}/>
            <div style={{ fontSize: 15, fontWeight: 600, color: '#F2F3F5' }}>Usuario con antecedentes</div>
          </div>
          <div style={{ fontSize: 13, color: '#DBDEE1', marginBottom: 14 }}>
            Ejemplo: el bot detecta antecedentes en el sistema antes de admitir a un usuario.
          </div>
          <EmbedGrid>
            <EmbedField label="Caso" value="—" color="var(--warn)"/>
            <EmbedField label="Tipo" value="—" color="var(--warn)"/>
            <EmbedField label="Estado" value="—"/>
            <EmbedField label="Última sanción" value="—"/>
          </EmbedGrid>
        </Embed>
      </BotMessage>
    );
  }
  if (type === 'jarvis') {
    return (
      <BotMessage>
        <Embed color="var(--accent-2)">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
            <Icon.Sparkle size={16} style={{ color: 'var(--accent-2)' }}/>
            <div style={{ fontSize: 13, fontWeight: 600, color: '#F2F3F5' }}>JARVIS</div>
            <span style={{ fontSize: 10, padding: '2px 6px', background: 'rgba(111,224,255,0.15)', color: 'var(--accent-2)', borderRadius: 4, fontFamily: 'Geist Mono' }}>AI</span>
          </div>
          <div style={{ fontSize: 13, color: '#DBDEE1', lineHeight: 1.55, marginBottom: 12 }}>
            JARVIS detecta automáticamente miembros cerca de la próxima Phase y los lista priorizados.
          </div>
          <div style={{ padding: '14px 12px', fontSize: 12, color: '#949BA4', textAlign: 'center', fontFamily: 'Geist Mono' }}>
            Sin datos en este server · ejecutá <span style={{ color: 'var(--accent-2)' }}>.jarvis check</span> con miembros vinculados.
          </div>
        </Embed>
      </BotMessage>
    );
  }
  if (type === 'antiraid') {
    return (
      <BotMessage>
        <Embed color="var(--live)">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <Icon.Shield size={18} style={{ color: 'var(--live)' }}/>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#F2F3F5' }}>Anti-raid v2 · panel</div>
            <span style={{ fontSize: 10, padding: '2px 6px', background: 'rgba(34,197,94,0.15)', color: 'var(--live)', borderRadius: 4, marginLeft: 'auto' }}>ARMADO</span>
          </div>
          <EmbedGrid>
            <EmbedField label="Modo" value="—"/>
            <EmbedField label="Whitelist bots" value="—"/>
            <EmbedField label="Alertas DM" value="—" color="var(--live)"/>
            <EmbedField label="Eventos 24h" value="—"/>
          </EmbedGrid>
          <div style={{ marginTop: 12, padding: '8px 10px', background: 'rgba(255,255,255,0.04)', borderRadius: 6, fontSize: 11, color: '#B5BAC1', fontFamily: 'Geist Mono' }}>
            log · esperando eventos del anti-raid en tu server
          </div>
        </Embed>
      </BotMessage>
    );
  }
  if (type === 'coach') {
    return (
      <BotMessage>
        <Embed color="var(--live)">
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 13, color: '#949BA4', fontFamily: 'Geist Mono', letterSpacing: '0.08em', textTransform: 'uppercase' }}>Coaches disponibles</div>
          </div>
          <div style={{ padding: '14px 12px', fontSize: 12, color: '#949BA4', textAlign: 'center', fontFamily: 'Geist Mono' }}>
            Cargando coaches del directorio · datos reales tras vincular.
          </div>
        </Embed>
      </BotMessage>
    );
  }
  return null;
}

function BotMessage({ children }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 14 }}>
      <div style={{
        width: 40, height: 40, borderRadius: '50%',
        background: 'linear-gradient(135deg, var(--accent), var(--accent-2))',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: 'white', fontWeight: 700, fontSize: 13, fontFamily: 'Geist Mono',
      }}>0H</div>
      <div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
          <span style={{ fontSize: 15, fontWeight: 500, color: '#F2F3F5' }}>OneWay</span>
          <span style={{ fontSize: 10, padding: '2px 5px', background: 'var(--accent)', color: 'white', borderRadius: 3, fontWeight: 600, letterSpacing: '0.04em' }}>BOT</span>
          <span style={{ fontSize: 11, color: '#949BA4' }}>hoy a las 14:58</span>
        </div>
        <div style={{ marginTop: 6 }}>
          {children}
        </div>
      </div>
    </div>
  );
}

function Embed({ children, color }) {
  return (
    <div style={{
      background: '#2B2D31',
      borderLeft: `4px solid ${color}`,
      borderRadius: 4,
      padding: '14px 16px',
      maxWidth: 480,
    }}>{children}</div>
  );
}

function EmbedGrid({ children }) {
  return <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px 24px' }}>{children}</div>;
}

function EmbedField({ label, value, color }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 600, color: '#F2F3F5', marginBottom: 2 }}>{label}</div>
      <div className="mono" style={{ fontSize: 13, color: color || '#DBDEE1' }}>{value}</div>
    </div>
  );
}

window.DiscordSection = DiscordSection;
