// Animated WhatsApp chat demo showing AI qualifying a lead
const ChatDemo = () => {
  const h = L('hero');
  const c = h.chat;
  const script = React.useMemo(() => ([
    { who:'lead',   text:c[0], delay: 900 },
    { who:'typing', delay: 800 },
    { who:'ai',     text:c[1], delay: 1400 },
    { who:'lead',   text:c[2], delay: 1100 },
    { who:'typing', delay: 1000 },
    { who:'ai',     text:c[3], delay: 1500 },
    { who:'lead',   text:c[4], delay: 1000 },
    { who:'system', text:c[5], delay: 900 },
  ]), []);

  const [step, setStep] = React.useState(0);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (step >= script.length) {
      const r = setTimeout(() => setStep(0), 4500);
      return () => clearTimeout(r);
    }
    const t = setTimeout(() => setStep(s => s + 1), script[step].delay);
    return () => clearTimeout(t);
  }, [step, script]);

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

  const visible = script.slice(0, step);

  return (
    <div style={{
      position:'relative',
      width:'100%', maxWidth:420,
      borderRadius:32,
      background:'linear-gradient(180deg, #0e1a14, #060a08)',
      border:'1px solid rgba(0,228,122,0.18)',
      boxShadow:
        '0 40px 100px -20px rgba(0,228,122,0.25), '+
        '0 0 0 1px rgba(0,228,122,0.05), '+
        'inset 0 1px 0 rgba(255,255,255,0.05)',
      overflow:'hidden',
    }}>
      {/* Phone status bar */}
      <div style={{
        display:'flex', alignItems:'center', justifyContent:'space-between',
        padding:'14px 22px 10px', fontSize:12, color:'var(--ink-3)', fontFamily:"'Geist Mono',monospace"
      }}>
        <span>9:41</span>
        <span style={{ display:'flex', gap:6, alignItems:'center' }}>
          <span style={{ width:14, height:8, borderRadius:2, background:'var(--green)' }} />
          5G
        </span>
      </div>
      {/* Header */}
      <div style={{
        display:'flex', alignItems:'center', gap:12, padding:'8px 18px 14px',
        borderBottom:'1px solid rgba(255,255,255,0.06)',
      }}>
        <div style={{
          width:42, height:42, borderRadius:'50%',
          background:'linear-gradient(135deg, #00ff88, #00a55a)',
          display:'grid', placeItems:'center', color:'#001509', fontWeight:700, fontSize:14
        }}>LU</div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:14, fontWeight:500, display:'flex', alignItems:'center', gap:6 }}>
            {h.chatHeaderName}
            <svg width="13" height="13" viewBox="0 0 24 24" fill="#00E47A"><path d="M12 2l2.5 2 3.5-.5L19 7l3 2-1.5 3 1 3.5-3 1.5-1.5 3.5L14 19l-2 3-2-3-3.5.5L5 17l-3-2 1.5-3-1-3.5 3-1.5L7 3.5 10 4z"/><path d="M9 12l2 2 4-4" stroke="#001509" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          <div style={{ fontSize:11.5, color:'var(--ink-3)', display:'flex', alignItems:'center', gap:6 }}>
            <span className="chip" style={{ padding:'2px 6px', fontSize:10, gap:5 }}>
              <span className="dot live" style={{ width:5, height:5 }}/>{h.chatOnline}
            </span>
            {h.chatReplying}
          </div>
        </div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{
        height:380, overflowY:'auto', padding:'18px 18px 22px',
        display:'flex', flexDirection:'column', gap:10,
        background:
          'radial-gradient(800px 400px at 50% 0%, rgba(0,228,122,0.04), transparent 70%)',
        scrollbarWidth:'none',
      }}>
        {visible.map((m, i) => {
          if (m.who === 'typing') return <TypingBubble key={i} />;
          if (m.who === 'system') return (
            <div key={i} style={{
              alignSelf:'center', textAlign:'center', marginTop:12,
              padding:'10px 14px', borderRadius:12,
              border:'1px dashed rgba(0,228,122,0.35)',
              background:'rgba(0,228,122,0.06)',
              fontSize:11, color:'var(--green)', fontFamily:"'Geist Mono',monospace",
              maxWidth:'85%',
              animation:'msgIn .35s ease both',
            }}>
              ✓ {m.text}
            </div>
          );
          const isAI = m.who === 'ai';
          return (
            <div key={i} style={{
              alignSelf: isAI ? 'flex-end' : 'flex-start',
              maxWidth:'82%',
              padding:'9px 13px',
              borderRadius: isAI ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
              background: isAI ? 'linear-gradient(180deg, #00b860, #009147)' : '#1a2520',
              color: isAI ? '#001509' : '#e6efea',
              fontSize:13.5, lineHeight:1.4,
              boxShadow: isAI ? '0 4px 16px rgba(0,228,122,0.18)' : '0 2px 8px rgba(0,0,0,0.3)',
              animation:'msgIn .35s ease both',
            }}>
              {m.text}
              <div style={{
                fontSize:10, marginTop:3,
                color: isAI ? 'rgba(0,21,9,0.55)' : 'var(--ink-4)',
                textAlign:'right'
              }}>
                {isAI ? '9:42 ✓✓' : '9:42'}
              </div>
            </div>
          );
        })}
      </div>

      {/* footer dock */}
      <div style={{
        padding:'10px 18px 18px', display:'flex', alignItems:'center', gap:10,
        borderTop:'1px solid rgba(255,255,255,0.05)'
      }}>
        <div style={{
          flex:1, height:38, borderRadius:999, border:'1px solid rgba(255,255,255,0.08)',
          background:'rgba(255,255,255,0.02)', display:'flex', alignItems:'center', padding:'0 14px',
          fontSize:12, color:'var(--ink-4)'
        }}>{h.chatInput}</div>
        <div style={{
          width:38, height:38, borderRadius:'50%',
          background:'var(--green)', display:'grid', placeItems:'center',
          boxShadow:'0 0 18px rgba(0,228,122,0.4)'
        }}>
          <Icon name="send" size={16} stroke="#001509" />
        </div>
      </div>

      <style>{`
        @keyframes msgIn { from { opacity:0; transform: translateY(8px); } to { opacity:1; transform:none; } }
        @keyframes tdot { 0%,80%,100%{ opacity:.3; transform:translateY(0);} 40%{ opacity:1; transform:translateY(-3px);} }
      `}</style>
    </div>
  );
};

const TypingBubble = () => (
  <div style={{
    alignSelf:'flex-end',
    padding:'10px 14px', borderRadius:'16px 16px 4px 16px',
    background:'linear-gradient(180deg, #00b860, #009147)',
    display:'flex', gap:4, animation:'msgIn .3s ease both'
  }}>
    {[0,1,2].map(i => (
      <span key={i} style={{
        width:6, height:6, borderRadius:'50%', background:'#001509',
        animation:`tdot 1.2s ${i*0.15}s infinite ease-in-out`
      }}/>
    ))}
  </div>
);


// Renders text with |...| segments as italic serif accents in green
const RichLine = ({ parts }) => (
  <>
    {parts.map((p, i) => {
      if (typeof p === 'string' && p.startsWith('|') && p.endsWith('|')) {
        const inner = p.slice(1, -1);
        if (inner === '—') return <span key={i} style={{ color:'var(--ink-3)' }}> — </span>;
        return <span key={i} className="serif" style={{ color:'var(--green)' }}>{inner}</span>;
      }
      return <span key={i}>{p}</span>;
    })}
  </>
);

const parseInline = (s) => {
  // splits "abc |X| def |Y|" into ['abc ','|X|',' def ','|Y|']
  const out = [];
  let buf = '', i = 0;
  while (i < s.length) {
    if (s[i] === '|') {
      if (buf) { out.push(buf); buf = ''; }
      const end = s.indexOf('|', i + 1);
      if (end === -1) { buf += s[i]; i++; continue; }
      out.push(s.slice(i, end + 1));
      i = end + 1;
    } else { buf += s[i]; i++; }
  }
  if (buf) out.push(buf);
  return out;
};

const Hero = () => {
  const h = L('hero');
  const v = { h1: h.h1, sub: h.sub };

  return (
    <section style={{ position:'relative', paddingTop:188, paddingBottom:64, overflow:'hidden' }}>
      <div className="grid-bg"/>
      {/* glow blob */}
      <div style={{
        position:'absolute', top:-160, left:'50%', transform:'translateX(-50%)',
        width:900, height:900, borderRadius:'50%',
        background:'radial-gradient(circle, rgba(0,228,122,0.18) 0%, transparent 55%)',
        pointerEvents:'none', filter:'blur(20px)'
      }}/>
      <div className="container" style={{ position:'relative' }}>
        <div style={{
          display:'grid', gridTemplateColumns:'1.15fr 0.85fr', gap:60, alignItems:'center'
        }} className="hero-grid">

          <div className="fade-up in">
            <h1 className="display" style={{ fontSize:'clamp(52px, 6vw, 74px)', lineHeight:1.04, margin:0 }}>
              {v.h1.map((line, i) => (
                <React.Fragment key={i}>
                  <RichLine parts={parseInline(line)}/>
                  {i < v.h1.length - 1 && <br/>}
                </React.Fragment>
              ))}
            </h1>

            <p style={{
              fontSize:'clamp(16px, 1.4vw, 19px)', color:'var(--ink-2)', lineHeight:1.55,
              maxWidth:540, marginTop:28
            }}>
              {parseInline(v.sub).map((p, i) => {
                if (typeof p === 'string' && p.startsWith('|') && p.endsWith('|')) {
                  return <strong key={i} style={{ color:'var(--ink)' }}>{p.slice(1,-1)}</strong>;
                }
                return <span key={i}>{p}</span>;
              })}
            </p>

            <div style={{ display:'flex', gap:12, marginTop:36, flexWrap:'wrap' }}>
              <a href="/signup" className="btn btn-primary btn-lg">
                {h.ctaPrimary} <Icon name="arrow" size={16}/>
              </a>
              <a href="#pricing" className="btn btn-ghost btn-lg">
                {h.ctaSecondary} <Icon name="arrow" size={16}/>
              </a>
            </div>

            <div style={{
              display:'flex', alignItems:'center', gap:18, marginTop:30,
              color:'var(--ink-3)', fontSize:13
            }}>
              <div style={{ display:'flex' }}>
                {['#0ea3ff','#ff7a3d','#b56dff','#00e47a','#ffb547'].map((c,i) => (
                  <div key={i} style={{
                    width:28, height:28, borderRadius:'50%', border:'2px solid var(--bg)',
                    marginLeft: i===0 ? 0 : -8, background:c,
                    backgroundImage:`linear-gradient(135deg, ${c}, rgba(0,0,0,0.3))`
                  }}/>
                ))}
              </div>
              <div>
                <div style={{ display:'flex', gap:2, color:'#FFD66B' }}>
                  {[1,2,3,4,5].map(i => <Icon key={i} name="star" size={13}/>)}
                </div>
                <div style={{ marginTop:2 }}>
                  <strong style={{ color:'var(--ink)' }}>4.9/5</strong> {h.rating}
                </div>
              </div>
            </div>
          </div>

          <div style={{ display:'flex', justifyContent:'center', position:'relative' }} className="hero-demo">
            <ChatDemo />
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .hero-grid { grid-template-columns: 1fr !important; gap: 60px !important; }
        }
        @media (max-width: 560px) {
          .hero-demo > div:not(:last-child) { display: none !important; }
        }
        @keyframes floaty { 0%,100%{transform:translateY(0)} 50%{transform:translateY(-8px)} }
      `}</style>
    </section>
  );
};

window.Hero = Hero;
