// Animated corporate chat between colaboradores.
// Reused on hero AND in section 6 (the full demo).

const COLABS = [
  { id: 'director', name: 'Director General', role: 'Coordina', color: '#1B3A6B', initial: 'D' },
  { id: 'mkt',      name: 'Marketing',        role: 'Contenido', color: '#7C3AED', initial: 'M' },
  { id: 'analitica',name: 'Analítica',        role: 'Métricas',  color: '#0EA5E9', initial: 'A' },
  { id: 'soporte',  name: 'Atención',         role: 'Soporte',   color: '#14B8A6', initial: 'S' },
  { id: 'logistica',name: 'Logística',        role: 'Reparto',   color: '#E8620A', initial: 'L' },
  { id: 'inventario',name:'Inventario',       role: 'Catálogo',  color: '#A16207', initial: 'I' },
];
const COLAB_BY = Object.fromEntries(COLABS.map(c => [c.id, c]));

// Script for the chat demo — designed to feel like the team is actually working
const CHAT_SCRIPT = [
  { who: 'mkt',       text: 'Listos los 3 posts para esta semana. Adjunto imágenes generadas.', attach: 'imagen', delay: 1100 },
  { who: 'analitica', text: 'El miércoles 7pm es el mejor horario según métricas de las últimas 4 semanas.', delay: 1400 },
  { who: 'logistica', text: 'Coordinando entrega #142 — cliente confirmó dirección.', delay: 1300 },
  { who: 'director',  text: 'Recibido. Programo publicación al miércoles 7pm y envío al dueño para aprobación.', tagOwner: true, delay: 1500 },
  { who: 'soporte',   text: 'Tres consultas resueltas en los últimos 20 min. CSAT 4.9.', delay: 1300 },
  { who: 'inventario',text: 'Detecté 2 productos sin descripción SEO. Redactando.', delay: 1300 },
];

function Avatar({ c, size = 28 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%',
      background: c.color, color:'#fff',
      display:'inline-flex', alignItems:'center', justifyContent:'center',
      fontWeight: 700, fontSize: size * 0.42, letterSpacing:'-0.02em',
      flexShrink: 0,
    }}>{c.initial}</div>
  );
}

function TypingDots({ color = '#94A3B8' }) {
  return (
    <span style={{ display:'inline-flex', gap: 3, alignItems:'center', paddingLeft: 2 }}>
      {[0,1,2].map(i => (
        <span key={i} style={{
          width: 5, height: 5, borderRadius: 999, background: color,
          animation: `td 1.1s ${i*0.15}s infinite ease-in-out`,
          display:'inline-block',
        }}/>
      ))}
      <style>{`@keyframes td{0%,80%,100%{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-2px)}}`}</style>
    </span>
  );
}

function ChatMessage({ msg, isLast, typing }) {
  const c = COLAB_BY[msg.who];
  return (
    <div style={{
      display:'flex', gap: 10, padding: '8px 14px 8px 12px',
      animation: 'fadeUp .42s ease both',
    }}>
      <Avatar c={c} />
      <div style={{ flex:1, minWidth: 0 }}>
        <div style={{ display:'flex', alignItems:'baseline', gap:8 }}>
          <span style={{ fontWeight: 600, fontSize: 13, color:'#0F172A' }}>{c.name}</span>
          <span style={{ fontSize: 11, color:'#94A3B8' }}>{c.role}</span>
          <span style={{ fontSize: 11, color:'#CBD5E1', marginLeft:'auto' }}>ahora</span>
        </div>
        <div style={{
          fontSize: 13.5, color: '#1F2937', marginTop: 3, lineHeight: 1.5,
        }}>
          {msg.text}
          {msg.tagOwner && (
            <span style={{
              display:'inline-flex', alignItems:'center', gap:4, marginLeft:8,
              background:'rgba(232,98,10,.08)', color:'var(--brand-accent)',
              padding:'1px 7px', borderRadius:999, fontSize:11, fontWeight:600,
            }}>@dueño</span>
          )}
        </div>
        {msg.attach === 'imagen' && (
          <div style={{
            marginTop: 8, display:'flex', gap: 6,
          }}>
            {[0,1,2].map(i => (
              <div key={i} style={{
                width: 56, height: 56, borderRadius: 8,
                background: `linear-gradient(135deg, ${['#FDE68A,#F59E0B','#A7F3D0,#10B981','#BFDBFE,#3B82F6'][i].split(',').join(' 0%,')} 100%)`,
                border:'1px solid rgba(0,0,0,.06)',
                display:'flex', alignItems:'center', justifyContent:'center',
                fontSize: 10, color:'rgba(0,0,0,.4)', fontWeight: 500,
              }}>IMG {i+1}</div>
            ))}
          </div>
        )}
        {isLast && typing && (
          <div style={{ marginTop: 6, display:'inline-flex', alignItems:'center', gap:6 }}>
            <TypingDots />
            <span style={{ fontSize: 11, color:'#94A3B8' }}>escribiendo…</span>
          </div>
        )}
      </div>
    </div>
  );
}

// Full chat window (used in section 6)
function ChatWindow({ compact = false, brandName = 'AI Company' }) {
  const printing = typeof document !== 'undefined' && document.body.classList.contains('printing');
  const [visible, setVisible] = React.useState(printing ? CHAT_SCRIPT.length : 1);
  const [typing, setTyping] = React.useState(!printing);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (printing) return; // no animation in print
    let stopped = false;
    let to;
    const step = () => {
      setTyping(true);
      to = setTimeout(() => {
        if (stopped) return;
        setTyping(false);
        setVisible(v => {
          const next = v >= CHAT_SCRIPT.length ? 1 : v + 1;
          return next;
        });
        to = setTimeout(step, 450);
      }, CHAT_SCRIPT[visible % CHAT_SCRIPT.length]?.delay || 1200);
    };
    step();
    return () => { stopped = true; clearTimeout(to); };
  }, [visible]);

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

  return (
    <div style={{
      background:'#fff',
      borderRadius: 18,
      overflow:'hidden',
      boxShadow:'0 30px 80px -20px rgba(8,20,40,.5), 0 8px 24px rgba(8,20,40,.18)',
      border: '1px solid rgba(255,255,255,.4)',
      width:'100%', maxWidth: compact ? 380 : 460,
    }}>
      {/* Window chrome */}
      <div style={{
        display:'flex', alignItems:'center', gap: 10,
        padding:'10px 14px', borderBottom:'1px solid #E5E7EB', background:'#F8FAFC',
      }}>
        <div style={{ display:'flex', gap: 5 }}>
          <span style={{ width:9, height:9, borderRadius:999, background:'#F87171' }}/>
          <span style={{ width:9, height:9, borderRadius:999, background:'#FBBF24' }}/>
          <span style={{ width:9, height:9, borderRadius:999, background:'#34D399' }}/>
        </div>
        <div style={{
          marginLeft: 8, fontSize: 12, fontWeight: 600, color:'#334155',
          display:'flex', alignItems:'center', gap: 6,
        }}>
          # general — {brandName}
          <span className="pulse-dot" style={{ marginLeft: 4 }}/>
        </div>
        <div style={{ marginLeft:'auto', fontSize: 11, color:'#94A3B8' }}>6 en línea</div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{
        background: 'linear-gradient(180deg, #FAFBFD 0%, #F4F6FA 100%)',
        height: compact ? 320 : 380,
        overflow: 'hidden',
        paddingBlock: 6,
      }}>
        {CHAT_SCRIPT.slice(0, visible).map((m, i) => (
          <ChatMessage key={i+'-'+m.who+m.text.slice(0,8)} msg={m} isLast={i === visible-1} typing={typing && i === visible-1 && visible < CHAT_SCRIPT.length} />
        ))}
        <style>{`@keyframes fadeUp{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}`}</style>
      </div>

      {/* Composer (decorative) */}
      <div style={{
        display:'flex', alignItems:'center', gap: 8,
        padding:'10px 12px', borderTop:'1px solid #E5E7EB', background:'#fff',
      }}>
        <div style={{
          flex:1, height: 32, borderRadius: 8, border:'1px solid #E5E7EB',
          padding:'0 12px', display:'flex', alignItems:'center',
          fontSize: 12, color:'#94A3B8',
        }}>Escribe a tu equipo…</div>
        <button style={{
          width: 32, height: 32, borderRadius: 8, background: 'var(--brand-primary)',
          color:'#fff', display:'inline-flex', alignItems:'center', justifyContent:'center',
        }}><Icon.arrow/></button>
      </div>
    </div>
  );
}

// Compact "activity dock" used inside hero (sleeker than full chat)
function ActivityDock({ brandName = 'AI Company' }) {
  const items = [
    { c: COLAB_BY.mkt,       text: 'Redactando post para Instagram', progress: 64 },
    { c: COLAB_BY.logistica, text: 'Coordinando entrega #142',        progress: 88 },
    { c: COLAB_BY.analitica, text: 'Optimizando campaña Meta Ads',    progress: 42 },
    { c: COLAB_BY.soporte,   text: 'Resolviendo 3 tickets',            progress: 71 },
  ];
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const i = setInterval(() => setTick(t => t + 1), 1400);
    return () => clearInterval(i);
  }, []);
  return (
    <div style={{
      background:'rgba(255,255,255,.06)',
      backdropFilter:'blur(16px)',
      border:'1px solid rgba(255,255,255,.12)',
      borderRadius: 18, padding: 16,
      color:'#fff', width:'100%', maxWidth: 380,
      boxShadow:'0 24px 60px -16px rgba(0,0,0,.5)',
    }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 14 }}>
        <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
          <span className="pulse-dot"/>
          <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '.02em' }}>Equipo activo · {brandName}</span>
        </div>
        <span style={{ fontSize: 11, opacity:.6 }}>en vivo</span>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap: 10 }}>
        {items.map((it, i) => {
          const prog = Math.min(100, (it.progress + tick * 3) % 110);
          return (
            <div key={i} style={{ display:'flex', alignItems:'center', gap: 12 }}>
              <Avatar c={it.c} size={32} />
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
                  <span style={{ fontSize: 12, fontWeight: 600 }}>{it.c.name}</span>
                  <span style={{ fontSize: 10, opacity:.6, fontVariantNumeric: 'tabular-nums' }}>{Math.round(prog)}%</span>
                </div>
                <div style={{ fontSize: 11.5, opacity:.75, marginTop: 1 }}>{it.text}</div>
                <div style={{
                  marginTop: 5, height: 3, background:'rgba(255,255,255,.08)', borderRadius: 999, overflow:'hidden',
                }}>
                  <div style={{
                    width: prog + '%', height:'100%',
                    background: `linear-gradient(90deg, ${it.c.color}, color-mix(in oklab, ${it.c.color}, white 25%))`,
                    transition: 'width 1s ease',
                  }}/>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { ChatWindow, ActivityDock, Avatar, COLABS, COLAB_BY });
