/* Pinned section: text on left, animated terminal on right that types as you scroll */
function PinnedTerminal() {
  const ref = React.useRef(null);
  const [progress, setProgress] = React.useState(0);
  const isMobile = useIsMobile();

  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        if (!ref.current) return;
        const rect = ref.current.getBoundingClientRect();
        const total = ref.current.offsetHeight - window.innerHeight;
        const scrolled = clamp(-rect.top, 0, total);
        setProgress(total > 0 ? scrolled / total : 0);
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);

  const lines = [
    { t: '$ claude code', c: '#7A7773' },
    { t: '> תבנה לי CRM עם Supabase, דף לוגין, וניהול לקוחות', c: '#F5F2ED' },
    { t: '⏺ קורא את הפרויקט הקיים…', c: '#EEB332' },
    { t: '⏺ יוצר חיבור ל-Supabase', c: '#EEB332' },
    { t: '⏺ בונה דף לקוחות מלא + לוגין', c: '#EEB332' },
    { t: '✓ סיים תוך 1:23 · 12 קבצים · CRM מוכן', c: '#4F8A5C' },
    { t: '> deploy', c: '#F5F2ED' },
    { t: '✓ עולה לאוויר ב-Vercel · ה-CRM שלך חי', c: '#4F8A5C' },
  ];

  const totalChars = lines.reduce((s,l)=>s+l.t.length,0);
  const shown = Math.floor(progress * totalChars * 1.4);
  let consumed = 0;
  const renderLines = lines.map(l => {
    const start = consumed;
    consumed += l.t.length;
    const end = consumed;
    if (shown < start) return { ...l, visible: '' };
    if (shown >= end) return { ...l, visible: l.t };
    return { ...l, visible: l.t.slice(0, shown - start) };
  });

  return (
    <section ref={ref} style={{position:'relative',height: isMobile ? '360vh' : '250vh',background:'#0A0907'}}>
      <div style={{position:'sticky',top:0,height:'100vh',display:'flex',alignItems:'center',padding: isMobile ? '0 14px' : '0 24px'}}>
        <div style={{maxWidth:1280,margin:'0 auto',width:'100%',display:'grid',gridTemplateColumns: isMobile ? '1fr' : '1fr 1.2fr',gap: isMobile ? 28 : 80,alignItems:'center'}}>
          {/* Right side in RTL = first column */}
          <div>
            <h2 style={{fontFamily:'Open Sans',fontWeight:900,fontSize:'clamp(44px,5.5vw,84px)',lineHeight:1.0,letterSpacing:'-0.02em',margin:0,color:'#F5F2ED'}}>
              אתה אומר.<br/>
              <span style={{color:'#EEB332'}}>קלוד מבצע.</span>
            </h2>
            <p style={{marginTop: isMobile ? 18 : 28,fontSize: isMobile ? 15 : 20,lineHeight:1.6,color:'rgba(245,242,237,0.7)',maxWidth:520}}>
              לא צריך להיות מהנדס. צריך לדעת לתאר את התוצאה. קלוד קורא את הפרויקט, מתכנן, בונה, בודק, מתקן ומעלה לאוויר. אתה רק מאשר את הצעד הבא.
            </p>
            <div style={{marginTop: isMobile ? 24 : 36,display:'flex',gap: isMobile ? 16 : 32,flexWrap:'wrap'}}>
              {[['10×','מהיר יותר'],['0','שורות קוד שאתה כותב'],['7','ימים מהרעיון לאוויר']].map(([n,l])=>(
                <div key={l}>
                  <div style={{fontFamily:'Open Sans',fontWeight:900,fontSize: isMobile ? 32 : 48,color:'#EEB332',lineHeight:1}}>{n}</div>
                  <div style={{fontSize: isMobile ? 11 : 13,color:'#7A7773',marginTop:4}}>{l}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Terminal mock */}
          <div style={{position:'relative',transform: isMobile ? 'none' : `perspective(1400px) rotateY(${lerp(8,-2,progress)}deg) rotateX(${lerp(4,-1,progress)}deg)`,transition:'transform 0.1s linear'}}>
            <div style={{background:'#13110F',border:'1px solid rgba(238,179,50,0.25)',borderRadius:8,boxShadow:'0 40px 80px -20px rgba(0,0,0,0.6), 0 0 60px -10px rgba(238,179,50,0.25)',overflow:'hidden',direction:'ltr'}}>
              <div style={{display:'flex',alignItems:'center',gap:6,padding:'12px 16px',background:'#0E0C0A',borderBottom:'1px solid rgba(245,242,237,0.06)'}}>
                <span style={{width:11,height:11,background:'#3a3633',borderRadius:'50%'}} />
                <span style={{width:11,height:11,background:'#3a3633',borderRadius:'50%'}} />
                <span style={{width:11,height:11,background:'#3a3633',borderRadius:'50%'}} />
                <div style={{flex:1,textAlign:'center',fontSize:11,color:'#7A7773',fontFamily:'monospace',letterSpacing:'0.05em'}}>~/my-crm - claude</div>
              </div>
              <div style={{padding: isMobile ? '14px 12px' : '24px 22px',fontFamily:'ui-monospace, SF Mono, Menlo, monospace',fontSize: isMobile ? 11 : 14,lineHeight:1.65, minHeight: isMobile ? 260 : 380}}>
                {renderLines.map((l,i)=>(
                  <div key={i} style={{color:l.c,whiteSpace:'pre-wrap',direction:l.t.match(/[\u0590-\u05FF]/) ? 'rtl':'ltr',textAlign:l.t.match(/[\u0590-\u05FF]/) ? 'right':'left'}}>
                    {l.visible}{l.visible.length < l.t.length && l.visible.length > 0 && <span style={{display:'inline-block',width:8,height:16,background:'#EEB332',verticalAlign:'middle',animation:'blink 0.8s steps(1) infinite'}} />}
                  </div>
                ))}
              </div>
            </div>
            <style>{`@keyframes blink { 50% { opacity: 0 } }`}</style>
          </div>
        </div>
      </div>
    </section>
  );
}
window.PinnedTerminal = PinnedTerminal;
