const Hero = ({ onNavigate }) => {
  const videoRef = React.useRef(null);
  const overlayTopRef = React.useRef(null);
  const overlayLeftRef = React.useRef(null);
  const overlayBottomRef = React.useRef(null);
  const ctaBtnRef = React.useRef(null);
  const [videoLoaded, setVideoLoaded] = React.useState(false);
  const [headlineVisible, setHeadlineVisible] = React.useState(false);
  const [statsVisible, setStatsVisible] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);

  React.useEffect(() => {
    const onResize = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);

  React.useEffect(() => {
    const t1 = setTimeout(() => setHeadlineVisible(true), 200);
    const t2 = setTimeout(() => setStatsVisible(true), 900);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);

  React.useEffect(() => {
    const vid = videoRef.current;
    if (!vid) return;
    vid.muted = true;
    vid.playsInline = true;
    const tryPlay = () => vid.play().catch(() => {});
    vid.addEventListener('canplay', tryPlay);
    vid.addEventListener('loadeddata', () => setVideoLoaded(true));
    tryPlay();
    return () => vid.removeEventListener('canplay', tryPlay);
  }, []);

  // Mouse parallax on overlay divs + idle CTA pulse
  React.useEffect(() => {
    if (isMobile) return;
    let cx = 0, cy = 0; // current lerped position
    let tx = 0, ty = 0; // target position
    let rafId = null;
    let idleTimer = null;

    const lerp = (a, b, f) => a + (b - a) * f;
    const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

    const tick = () => {
      cx = lerp(cx, tx, 0.08);
      cy = lerp(cy, ty, 0.08);
      if (overlayTopRef.current)
        overlayTopRef.current.style.transform = `translateX(${clamp(cx * 0.012, -14, 14)}px) translateY(${clamp(cy * 0.012, -14, 14)}px)`;
      if (overlayLeftRef.current)
        overlayLeftRef.current.style.transform = `translateX(${clamp(cx * 0.008, -14, 14)}px) translateY(${clamp(cy * 0.008, -14, 14)}px)`;
      if (overlayBottomRef.current)
        overlayBottomRef.current.style.transform = `translateX(${clamp(cx * 0.006, -14, 14)}px) translateY(${clamp(cy * 0.006, -14, 14)}px)`;
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);

    const onMove = (e) => {
      tx = e.clientX - window.innerWidth / 2;
      ty = e.clientY - window.innerHeight / 2;
      if (ctaBtnRef.current) ctaBtnRef.current.classList.remove('pulse-idle');
      clearTimeout(idleTimer);
      idleTimer = setTimeout(() => {
        if (ctaBtnRef.current) ctaBtnRef.current.classList.add('pulse-idle');
      }, 3000);
    };
    window.addEventListener('mousemove', onMove);

    return () => {
      cancelAnimationFrame(rafId);
      window.removeEventListener('mousemove', onMove);
      clearTimeout(idleTimer);
    };
  }, [isMobile]);

  const words = ['Property', 'systems', 'that', 'turn', 'interest', 'into', 'booked', 'viewings.'];

  const stats = [
    { value: 68, suffix: '%', label: 'Leads Booked Into Viewings' },
    { value: 2, prefix: '< ', suffix: 'm', label: 'Avg Lead Response Time' },
    { value: 3, suffix: '×', label: 'More Qualified Viewings' },
  ];

  return (
    <section id="hero" style={{
      position: 'relative', width: '100%',
      height: isMobile ? 'auto' : '100vh', minHeight: isMobile ? 'auto' : 700,
      display: 'flex', flexDirection: 'column',
      background: '#0D0D0D',
    }}>
      <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', zIndex: 0, pointerEvents: 'none' }}>
        <video ref={videoRef} muted loop playsInline autoPlay
          onLoadedData={() => setVideoLoaded(true)}
          style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover', objectPosition: 'center',
            opacity: videoLoaded ? 1 : 0, transition: 'opacity 1.8s ease',
          }}
          src="uploads/Binaan Co Website Hero Video.mp4"
        />
      </div>

      <div style={{ position:'absolute', inset:0, zIndex:1, opacity:0.035,
        backgroundImage:`url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noise'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noise)'/%3E%3C/svg%3E")`,
        backgroundSize:'180px 180px', pointerEvents:'none' }} />

      <div style={{ position:'absolute', inset:0, zIndex:2, background:'rgba(12,12,12,0.52)' }} />

      {/* Top vignette — parallax ref */}
      <div ref={overlayTopRef} style={{ position:'absolute', top:0, left:0, right:0, height:200, zIndex:3,
        background:'linear-gradient(to bottom, rgba(10,10,10,0.95) 0%, rgba(10,10,10,0.4) 60%, transparent 100%)',
        pointerEvents:'none' }} />

      {/* Left vignette — parallax ref */}
      <div ref={overlayLeftRef} style={{ position:'absolute', inset:0, zIndex:3,
        background:'linear-gradient(105deg, rgba(10,10,10,0.88) 0%, rgba(10,10,10,0.65) 38%, rgba(10,10,10,0.2) 62%, transparent 100%)',
        pointerEvents:'none' }} />

      {/* Bottom vignette — parallax ref */}
      <div ref={overlayBottomRef} style={{ position:'absolute', bottom:0, left:0, right:0, height:180, zIndex:3,
        background:'linear-gradient(to top, rgba(10,10,10,0.85) 0%, rgba(10,10,10,0.5) 45%, transparent 100%)',
        pointerEvents:'none' }} />

      {!isMobile && (
        <div style={{ position:'absolute', left:0, top:0, bottom:0, width:2, zIndex:10,
          background:'linear-gradient(to bottom, transparent 0%, #1F3D2B 30%, #1F3D2B 70%, transparent 100%)',
          opacity: headlineVisible ? 0.7 : 0, transition:'opacity 1s ease 0.5s' }} />
      )}

      <div style={{
        position:'relative', zIndex:10,
        flex:1, display:'flex',
        flexDirection: isMobile ? 'column' : 'row',
        alignItems: isMobile ? 'flex-start' : 'center',
        justifyContent:'space-between',
        maxWidth:1280, margin:'0 auto', width:'100%',
        padding: isMobile ? '72px 22px 28px' : '88px 64px 32px',
        minHeight:0,
        gap: isMobile ? 28 : 40,
      }}>
        <div style={{ maxWidth: isMobile ? '100%' : 520, width: isMobile ? '100%' : 'auto', flexShrink: 0 }}>

          <div style={{
            display:'flex', alignItems:'center', gap:10, marginBottom: isMobile ? 20 : 28,
            opacity: headlineVisible ? 1 : 0,
            transform: headlineVisible ? 'none' : 'translateY(12px)',
            transition:'all 0.7s cubic-bezier(0.4,0,0.2,1) 0.1s',
          }}>
            <span style={{ display:'inline-block', width:24, height:1, background:'#8C7A5B' }} />
            <span style={{ fontFamily:"'Inter', sans-serif", fontSize:10, fontWeight:600,
              letterSpacing:'0.14em', textTransform:'uppercase', color:'#8C7A5B' }}>Property Conversion Systems</span>
            <span style={{ width:5, height:5, borderRadius:'50%', background:'#1F3D2B',
              boxShadow:'0 0 8px rgba(31,61,43,0.8)', animation:'pulse 2s ease-in-out infinite' }} />
          </div>

          <h1 style={{
            fontFamily:"'Space Grotesk', sans-serif", fontWeight:600,
            fontSize: isMobile ? 28 : 'clamp(26px, 2.8vw, 44px)',
            color:'#F4F4F2', letterSpacing:'-0.025em', lineHeight:1.1,
            marginBottom: isMobile ? 14 : 18,
            display:'flex', flexWrap:'wrap', gap:'0.2em',
          }}>
            {words.map((word, i) => (
              <span key={i} style={{
                display:'inline-block',
                opacity: headlineVisible ? 1 : 0,
                transform: headlineVisible ? 'none' : 'translateY(20px)',
                transition:`opacity 0.6s cubic-bezier(0.4,0,0.2,1) ${0.2+i*0.07}s, transform 0.6s cubic-bezier(0.4,0,0.2,1) ${0.2+i*0.07}s`,
              }}>{word}</span>
            ))}
          </h1>

          <p style={{
            fontFamily:"'Inter', sans-serif",
            fontSize: isMobile ? 14 : 'clamp(13px, 0.9vw, 15px)',
            fontWeight:400, color:'rgba(244,244,242,0.65)', lineHeight:1.7,
            maxWidth: isMobile ? '100%' : 460, marginBottom: isMobile ? 24 : 28,
            opacity: headlineVisible ? 1 : 0,
            transform: headlineVisible ? 'none' : 'translateY(16px)',
            transition:'all 0.7s cubic-bezier(0.4,0,0.2,1) 0.75s',
          }}>
            We build the website and the system behind it. Designed to move property traffic into actual viewing appointments.
          </p>

          <div style={{
            display:'flex', gap:10, alignItems:'center', flexWrap:'wrap',
            marginBottom:8,
            opacity: headlineVisible ? 1 : 0,
            transform: headlineVisible ? 'none' : 'translateY(16px)',
            transition:'all 0.7s cubic-bezier(0.4,0,0.2,1) 0.88s',
          }}>
            <button ref={ctaBtnRef} onClick={() => onNavigate('contact')} style={{
              background:'#1F3D2B', color:'#F4F4F2', border:'none',
              fontFamily:"'Space Grotesk', sans-serif", fontWeight:600,
              fontSize:11, letterSpacing:'0.07em', textTransform:'uppercase',
              padding: isMobile ? '13px 24px' : '14px 32px', borderRadius:3, cursor:'pointer',
              boxShadow:'0 0 20px rgba(31,61,43,0.5)',
              transition:'all 180ms cubic-bezier(0.4,0,0.2,1)',
            }}
            onMouseEnter={e => { e.currentTarget.style.background='#244A34'; }}
            onMouseLeave={e => { e.currentTarget.style.background='#1F3D2B'; }}
            >Get Started</button>

            <button onClick={() => onNavigate('demo')} style={{
              background:'transparent', color:'#F4F4F2',
              border:'1px solid rgba(244,244,242,0.25)',
              fontFamily:"'Space Grotesk', sans-serif", fontWeight:600,
              fontSize:11, letterSpacing:'0.07em', textTransform:'uppercase',
              padding: isMobile ? '13px 24px' : '14px 32px', borderRadius:3, cursor:'pointer',
              transition:'all 180ms cubic-bezier(0.4,0,0.2,1)',
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor='rgba(244,244,242,0.7)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor='rgba(244,244,242,0.25)'; }}
            >View Demo</button>
          </div>

          {!isMobile && (
            <p style={{
              fontFamily:"'Inter', sans-serif", fontSize:11,
              color:'rgba(168,168,168,0.5)', letterSpacing:'0.04em',
              opacity: headlineVisible ? 1 : 0, transition:'opacity 0.7s ease 1.1s',
            }}>Built for property agents in Malaysia &amp; Singapore.</p>
          )}
        </div>

        {/* Floating automation card */}
        <AutomationCard isMobile={isMobile} visible={headlineVisible} />
      </div>

      <div style={{ position:'relative', zIndex:10, width:'100%', padding: isMobile ? '0 22px' : '0 64px' }}>
        <div style={{
          maxWidth:1280, margin:'0 auto',
          borderTop:'1px solid rgba(244,244,242,0.08)',
          display:'grid',
          gridTemplateColumns: 'repeat(3, 1fr)',
          gap: isMobile ? '16px 12px' : 0,
          paddingTop:20, paddingBottom: isMobile ? 24 : 28,
        }}>
          {stats.map((stat, i) => (
            <AnimatedStat key={i} stat={stat} index={i} visible={statsVisible} isMobile={isMobile} />
          ))}
        </div>
      </div>

      <style>{`
        @keyframes pulse {
          0%, 100% { opacity:1; box-shadow:0 0 8px rgba(31,61,43,0.8); }
          50% { opacity:0.5; box-shadow:0 0 16px rgba(31,61,43,0.4); }
        }
        @keyframes ctaPulse {
          0%, 100% { box-shadow: 0 0 20px rgba(31,61,43,0.5); }
          50% { box-shadow: 0 0 38px rgba(31,61,43,0.9), 0 0 64px rgba(31,61,43,0.3); }
        }
        @keyframes heroFloat {
          0%, 100% { transform: translateY(-4px); }
          50% { transform: translateY(4px); }
        }
        .pulse-idle { animation: ctaPulse 2.5s ease-in-out infinite; }
      `}</style>
    </section>
  );
};

const AnimatedStat = ({ stat, index, visible, isMobile }) => {
  const [count, setCount] = React.useState(0);
  const started = React.useRef(false);

  React.useEffect(() => {
    if (!visible || started.current) return;
    started.current = true;
    const delay = index * 120;
    const duration = 1400;
    const startTime = performance.now() + delay;
    const target = stat.value;
    const tick = (now) => {
      if (now < startTime) { requestAnimationFrame(tick); return; }
      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setCount(Math.round(eased * target));
      if (progress < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  }, [visible]);

  const isFirstInRow = (index === 0);

  return (
    <div style={{
      paddingLeft: isFirstInRow ? 0 : (isMobile ? 12 : 28),
      borderLeft: isFirstInRow ? 'none' : '1px solid rgba(244,244,242,0.07)',
      opacity: visible ? 1 : 0,
      transform: visible ? 'none' : 'translateY(12px)',
      transition:`opacity 0.6s ease ${0.1+index*0.1}s, transform 0.6s ease ${0.1+index*0.1}s`,
    }}>
      <div style={{
        fontFamily:"'Space Grotesk', sans-serif", fontWeight:700,
        fontSize: isMobile ? 22 : 'clamp(18px, 1.8vw, 26px)',
        color:'#F4F4F2', letterSpacing:'-0.02em', lineHeight:1, marginBottom:5,
      }}>
        {stat.prefix||''}{count}{stat.suffix}
      </div>
      <div style={{
        fontFamily:"'Inter', sans-serif", fontSize:10, fontWeight:500,
        color:'#A8A8A8', letterSpacing:'0.07em', textTransform:'uppercase',
      }}>{stat.label}</div>
    </div>
  );
};


const AutomationCard = ({ isMobile, visible }) => {
  const steps = [
    { label: 'New lead captured', sub: 'Website enquiry received', time: '10:24 AM' },
    { label: 'WhatsApp follow-up sent', sub: 'Automated reply sent in 42s', time: '10:25 AM' },
    { label: 'Viewing booked', sub: 'Saturday, 11:00 AM', time: '10:28 AM' },
  ];
  const icons = ['↗', '⚡', '✓'];
  return (
    <div style={{
      opacity: visible ? 1 : 0,
      transition: 'opacity 0.9s ease 1s',
      animation: 'heroFloat 5.5s ease-in-out infinite',
      flexShrink: 0,
      width: isMobile ? '100%' : 290,
      maxWidth: isMobile ? 400 : 290,
    }}>
      <div style={{
        background: 'rgba(18,18,18,0.85)',
        backdropFilter: 'blur(24px)',
        WebkitBackdropFilter: 'blur(24px)',
        border: '1px solid rgba(255,255,255,0.08)',
        borderRadius: 16,
        padding: '22px 22px 18px',
        boxShadow: '0 24px 64px rgba(0,0,0,0.45)',
        position: 'relative',
        overflow: 'hidden',
      }}>
        <div style={{ position:'absolute', top:0, left:0, right:0, height:1,
          background:'linear-gradient(90deg, transparent, rgba(31,61,43,0.6), transparent)' }} />
        <div style={{ position:'relative' }}>
          <div style={{ position:'absolute', left:10, top:22, height:'calc(100% - 22px)', width:1,
            background:'linear-gradient(to bottom, rgba(31,61,43,0.8), rgba(31,61,43,0.1))', pointerEvents:'none' }} />
          {steps.map((step, i) => (
            <div key={i} style={{ display:'flex', alignItems:'flex-start', gap:12,
              marginBottom: i < steps.length - 1 ? 18 : 0, position:'relative' }}>
              <div style={{ width:21, height:21, borderRadius:'50%',
                background: i === 0 ? '#1F3D2B' : 'rgba(31,61,43,0.2)',
                border: i === 0 ? '1px solid rgba(31,61,43,0.9)' : '1px solid rgba(31,61,43,0.35)',
                display:'flex', alignItems:'center', justifyContent:'center',
                flexShrink:0, marginTop:1, zIndex:1 }}>
                <span style={{ fontSize:8, color:'#F4F4F2', fontFamily:"'Inter', sans-serif", lineHeight:1 }}>
                  {icons[i]}
                </span>
              </div>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontFamily:"'Space Grotesk', sans-serif", fontSize:12, fontWeight:600,
                  color:'#F4F4F2', letterSpacing:'-0.01em', lineHeight:1.3, marginBottom:2 }}>{step.label}</div>
                <div style={{ fontFamily:"'Inter', sans-serif", fontSize:10,
                  color:'rgba(168,168,168,0.75)', lineHeight:1.4 }}>{step.sub}</div>
              </div>
              <div style={{ fontFamily:"'Inter', sans-serif", fontSize:9,
                color:'rgba(168,168,168,0.45)', letterSpacing:'0.03em', flexShrink:0, marginTop:2 }}>{step.time}</div>
            </div>
          ))}
        </div>
        <div style={{ marginTop:18, paddingTop:14, borderTop:'1px solid rgba(255,255,255,0.05)',
          display:'flex', alignItems:'center', gap:8 }}>
          <div style={{ width:6, height:6, borderRadius:'50%', background:'#1F3D2B',
            boxShadow:'0 0 8px rgba(31,61,43,0.9)', animation:'pulse 2s ease-in-out infinite', flexShrink:0 }} />
          <span style={{ fontFamily:"'Inter', sans-serif", fontSize:10,
            color:'rgba(168,168,168,0.65)', letterSpacing:'0.04em' }}>System working for you 24/7</span>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Hero, AnimatedStat, AutomationCard });
