// cinematic-hero.jsx — Cinematic scroll hero (ported from 21st.dev, adapted for Jawwad Automation)
// Requires: gsap + ScrollTrigger loaded as globals before this script
// Requires: Tailwind CDN with preflight:false

// Register ScrollTrigger with GSAP global (CDN sets window.gsap + window.ScrollTrigger)
if (typeof gsap !== 'undefined' && typeof ScrollTrigger !== 'undefined') {
  gsap.registerPlugin(ScrollTrigger);
}

const CinematicHero = ({
  tagline1 = "Automate the work,",
  tagline2 = "own the results.",
  cardHeading = "Automation, delivered.",
  cardDescription = (
    <>
      <span className="text-white font-semibold">Jawwad</span>{" "}
      builds ready-to-use automation systems that save businesses hours every week — AI, no-code tools, APIs, and custom code.
    </>
  ),
  metricValue = 12,
  metricLabel = "Hrs / Wk Saved",
  ctaHeading = "Start automating.",
  ctaDescription = "Let's build your first working automation in 3–7 days. Free 30-min audit — no commitment.",
  className = "",
}) => {
  const containerRef = React.useRef(null);
  const mainCardRef  = React.useRef(null);
  const mockupRef    = React.useRef(null);
  const rafRef       = React.useRef(0);

  // ── Mouse parallax + card sheen ─────────────────────────────────────────
  React.useEffect(() => {
    const onMove = (e) => {
      if (window.scrollY > window.innerHeight * 2) return;
      cancelAnimationFrame(rafRef.current);
      rafRef.current = requestAnimationFrame(() => {
        if (!mainCardRef.current || !mockupRef.current) return;
        const rect = mainCardRef.current.getBoundingClientRect();
        mainCardRef.current.style.setProperty('--mouse-x', `${e.clientX - rect.left}px`);
        mainCardRef.current.style.setProperty('--mouse-y', `${e.clientY - rect.top}px`);
        const xVal = (e.clientX / window.innerWidth  - 0.5) * 2;
        const yVal = (e.clientY / window.innerHeight - 0.5) * 2;
        gsap.to(mockupRef.current, { rotationY: xVal * 12, rotationX: -yVal * 12, ease: 'power3.out', duration: 1.2 });
      });
    };
    window.addEventListener('mousemove', onMove);
    return () => { window.removeEventListener('mousemove', onMove); cancelAnimationFrame(rafRef.current); };
  }, []);

  // ── Cinematic scroll timeline ────────────────────────────────────────────
  React.useEffect(() => {
    if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') return;
    const mob = window.innerWidth < 768;

    const ctx = gsap.context(() => {
      // Initial states
      gsap.set('.ch-text-track',  { autoAlpha: 0, y: 60, scale: 0.85, filter: 'blur(20px)', rotationX: -20 });
      gsap.set('.ch-text-reveal', { autoAlpha: 1, clipPath: 'inset(0 100% 0 0)' });
      gsap.set('.ch-main-card',   { y: window.innerHeight + 200, autoAlpha: 1 });
      gsap.set(['.ch-card-left', '.ch-card-right', '.ch-mockup-wrap', '.ch-badge', '.ch-widget'], { autoAlpha: 0 });
      gsap.set('.ch-cta-wrap',    { autoAlpha: 0, scale: 0.8, filter: 'blur(30px)' });

      // Intro (runs immediately on load)
      gsap.timeline({ delay: 0.4 })
        .to('.ch-text-track',  { duration: 1.8, autoAlpha: 1, y: 0, scale: 1, filter: 'blur(0px)', rotationX: 0, ease: 'expo.out' })
        .to('.ch-text-reveal', { duration: 1.4, clipPath: 'inset(0 0% 0 0)', ease: 'power4.inOut' }, '-=1.0');

      // Scroll-pinned cinematic timeline
      gsap.timeline({
        scrollTrigger: {
          trigger: containerRef.current,
          start: 'top top',
          end:   '+=1400',
          pin:   true,
          scrub: 1,
          anticipatePin: 1,
        },
      })
      // ① Text + grid blur out, card flies in from below
      .to(['.ch-hero-text', '.ch-bg-grid'],
        { scale: 1.15, filter: 'blur(20px)', opacity: 0.2, ease: 'power2.inOut', duration: 2 }, 0)
      .to('.ch-main-card',
        { y: 0, ease: 'power3.inOut', duration: 2 }, 0)
      // ② Card expands full-screen
      .to('.ch-main-card',
        { width: '100%', height: '100%', borderRadius: '0px', ease: 'power3.inOut', duration: 1.5 })
      // ③ Mockup rises from depth
      .fromTo('.ch-mockup-wrap',
        { y: 300, z: -500, rotationX: 50, rotationY: -30, autoAlpha: 0, scale: 0.6 },
        { y: 0,   z: 0,    rotationX: 0,  rotationY: 0,   autoAlpha: 1, scale: 1,  ease: 'expo.out', duration: 2.5 }, '-=0.8')
      // ④ Widgets animate in
      .fromTo('.ch-widget',
        { y: 40, autoAlpha: 0, scale: 0.95 },
        { y: 0,  autoAlpha: 1, scale: 1, stagger: 0.15, ease: 'back.out(1.2)', duration: 1.5 }, '-=1.5')
      // ⑤ Progress ring fills, counter counts up
      .to('.ch-progress-ring', { strokeDashoffset: 80, duration: 2, ease: 'power3.inOut' }, '-=1.2')
      .to('.ch-counter', { innerHTML: metricValue, snap: { innerHTML: 1 }, duration: 2, ease: 'expo.out' }, '-=2.0')
      // ⑥ Floating badges pop in
      .fromTo('.ch-badge',
        { y: 100, autoAlpha: 0, scale: 0.7, rotationZ: -10 },
        { y: 0,   autoAlpha: 1, scale: 1,   rotationZ: 0,  ease: 'back.out(1.5)', duration: 1.5, stagger: 0.2 }, '-=2.0')
      // ⑦ Card copy slides in
      .fromTo('.ch-card-left',
        { x: -50, autoAlpha: 0 },
        { x: 0,   autoAlpha: 1, ease: 'power4.out', duration: 1.5 }, '-=1.5')
      .fromTo('.ch-card-right',
        { x: 50, autoAlpha: 0, scale: 0.8 },
        { x: 0,  autoAlpha: 1, scale: 1,   ease: 'expo.out', duration: 1.5 }, '<')
      // ⑧ Hold, then swap to CTA
      .to({}, { duration: 1 })
      .set('.ch-hero-text', { autoAlpha: 0 })
      .set('.ch-cta-wrap',  { autoAlpha: 1 })
      .to({}, { duration: 0.5 })
      // ⑨ Card content collapses
      .to(['.ch-mockup-wrap', '.ch-badge', '.ch-card-left', '.ch-card-right'],
        { scale: 0.9, y: -40, z: -200, autoAlpha: 0, ease: 'power3.in', duration: 1.2, stagger: 0.05 })
      // ⑩ Card pulls back, CTA blooms
      .to('.ch-main-card',
        { width: mob ? '92vw' : '85vw', height: mob ? '92vh' : '85vh',
          borderRadius: mob ? '32px' : '40px', ease: 'expo.inOut', duration: 1.8 }, 'pullback')
      .to('.ch-cta-wrap',
        { scale: 1, filter: 'blur(0px)', ease: 'expo.inOut', duration: 1.8 }, 'pullback')
      // ⑪ Card exits upward
      .to('.ch-main-card',
        { y: -(window.innerHeight + 300), ease: 'power3.in', duration: 1.5 });

    }, containerRef);

    return () => ctx.revert();
  }, [metricValue]);

  return (
    <div
      ref={containerRef}
      className={`relative w-screen h-screen overflow-hidden flex items-center justify-center bg-background text-foreground font-sans antialiased ${className}`}
      style={{ perspective: '1500px' }}
    >
      <div className="film-grain" aria-hidden="true" />
      <div className="ch-bg-grid bg-grid-theme absolute inset-0 z-0 pointer-events-none opacity-50" aria-hidden="true" />

      {/* ── Layer 1: Tagline text ────────────────────────────────────────── */}
      <div className="ch-hero-text absolute z-10 flex flex-col items-center justify-center text-center w-screen px-4"
           style={{ willChange: 'transform' }}>
        <h1 className="ch-text-track gsap-reveal text-3d-matte text-5xl md:text-7xl lg:text-[6rem] font-bold tracking-tight mb-2">
          {tagline1}
        </h1>
        <h1 className="ch-text-reveal gsap-reveal text-silver-matte text-5xl md:text-7xl lg:text-[6rem] font-extrabold tracking-tighter">
          {tagline2}
        </h1>
      </div>

      {/* ── Layer 2: CTA (shown after scroll completes) ──────────────────── */}
      <div className="ch-cta-wrap absolute z-10 flex flex-col items-center justify-center text-center w-screen px-4 pointer-events-auto"
           style={{ willChange: 'transform' }}>
        <h2 className="text-4xl md:text-6xl lg:text-7xl font-bold mb-6 tracking-tight text-silver-matte">
          {ctaHeading}
        </h2>
        <p className="text-muted-foreground text-lg md:text-xl mb-12 max-w-xl mx-auto font-light leading-relaxed">
          {ctaDescription}
        </p>
        <div className="flex flex-col sm:flex-row gap-6">
          <a href="#contact"
             className="btn-modern-light flex items-center justify-center gap-3 px-8 py-4 rounded-[1.25rem] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
            <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2"
                d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
            </svg>
            <div className="text-left">
              <div className="text-[10px] font-bold tracking-wider text-neutral-500 uppercase" style={{ marginBottom: '-2px' }}>Schedule a</div>
              <div className="text-xl font-bold leading-none tracking-tight">Free Audit</div>
            </div>
          </a>
          <a href="#systems"
             className="btn-modern-dark flex items-center justify-center gap-3 px-8 py-4 rounded-[1.25rem] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
            <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
            </svg>
            <div className="text-left">
              <div className="text-[10px] font-bold tracking-wider text-neutral-400 uppercase" style={{ marginBottom: '-2px' }}>Browse</div>
              <div className="text-xl font-bold leading-none tracking-tight">Systems</div>
            </div>
          </a>
        </div>
      </div>

      {/* ── Layer 3: The Deep Blue Card ─────────────────────────────────── */}
      <div className="absolute inset-0 z-20 flex items-center justify-center pointer-events-none"
           style={{ perspective: '1500px' }}>
        <div
          ref={mainCardRef}
          className="ch-main-card premium-depth-card relative overflow-hidden flex items-center justify-center pointer-events-auto w-[92vw] md:w-[85vw] h-[92vh] md:h-[85vh] rounded-[32px] md:rounded-[40px]"
        >
          <div className="card-sheen" aria-hidden="true" />

          {/* Responsive grid: col on mobile, 3-col on desktop */}
          <div className="relative w-full h-full max-w-7xl mx-auto px-4 lg:px-12 flex flex-col justify-evenly lg:grid lg:grid-cols-3 items-center lg:gap-8 z-10 py-6 lg:py-0">

            {/* Right col (desktop) / Top (mobile): Brand name */}
            <div className="ch-card-right gsap-reveal order-1 lg:order-3 flex justify-center lg:justify-end z-20 w-full">
              <h2 className="text-6xl md:text-[6rem] lg:text-[8rem] font-black uppercase tracking-tighter text-card-silver-matte">
                Jawwad
              </h2>
            </div>

            {/* Center col (desktop) / Middle (mobile): Phone mockup */}
            <div className="ch-mockup-wrap order-2 lg:order-2 relative w-full h-[380px] lg:h-[600px] flex items-center justify-center z-10"
                 style={{ perspective: '1000px' }}>
              <div className="relative w-full h-full flex items-center justify-center"
                   style={{ transform: 'scale(0.65)', transformOrigin: 'center' }}>

                {/* The iPhone chassis */}
                <div
                  ref={mockupRef}
                  className="relative w-[280px] h-[580px] rounded-[3rem] iphone-bezel flex flex-col"
                  style={{ willChange: 'transform', transformStyle: 'preserve-3d' }}
                >
                  {/* Physical side buttons */}
                  <div className="absolute top-[120px] -left-[3px] w-[3px] h-[25px] hardware-btn rounded-l-md" aria-hidden="true" />
                  <div className="absolute top-[160px] -left-[3px] w-[3px] h-[45px] hardware-btn rounded-l-md" aria-hidden="true" />
                  <div className="absolute top-[220px] -left-[3px] w-[3px] h-[45px] hardware-btn rounded-l-md" aria-hidden="true" />
                  <div className="absolute top-[170px] -right-[3px] w-[3px] h-[70px] hardware-btn rounded-r-md"
                       style={{ transform: 'scaleX(-1)' }} aria-hidden="true" />

                  {/* Screen */}
                  <div className="absolute inset-[7px] rounded-[2.5rem] overflow-hidden text-white z-10"
                       style={{ backgroundColor: '#050914', boxShadow: 'inset 0 0 15px rgba(0,0,0,1)' }}>
                    <div className="absolute inset-0 screen-glare z-40 pointer-events-none" aria-hidden="true" />

                    {/* Dynamic Island */}
                    <div className="absolute top-[5px] left-1/2 -translate-x-1/2 w-[100px] h-[28px] bg-black rounded-full z-50 flex items-center justify-end px-3"
                         style={{ boxShadow: 'inset 0 -1px 2px rgba(255,255,255,0.1)' }}>
                      <div className="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse"
                           style={{ boxShadow: '0 0 8px rgba(34,197,94,0.8)' }} />
                    </div>

                    {/* App Interface */}
                    <div className="relative w-full h-full pt-12 px-5 pb-8 flex flex-col">

                      {/* App header */}
                      <div className="ch-widget flex justify-between items-center mb-8">
                        <div className="flex flex-col">
                          <span className="text-[10px] text-neutral-400 uppercase tracking-widest font-bold mb-1">Live</span>
                          <span className="text-xl font-bold tracking-tight text-white"
                                style={{ textShadow: '0 2px 8px rgba(0,0,0,0.8)' }}>Automation</span>
                        </div>
                        <div className="w-9 h-9 rounded-full text-neutral-200 flex items-center justify-center font-bold text-sm border border-white/10"
                             style={{ background: 'rgba(255,255,255,0.05)', boxShadow: '0 4px 12px rgba(0,0,0,0.5)' }}>JA</div>
                      </div>

                      {/* Progress ring + counter */}
                      <div className="ch-widget relative w-44 h-44 mx-auto flex items-center justify-center mb-8"
                           style={{ filter: 'drop-shadow(0 15px 25px rgba(0,0,0,0.8))' }}>
                        <svg className="absolute inset-0 w-full h-full" viewBox="0 0 176 176" aria-hidden="true">
                          <circle cx="88" cy="88" r="64" fill="none" stroke="rgba(255,255,255,0.03)" strokeWidth="12" />
                          <circle className="ch-progress-ring"
                            cx="88" cy="88" r="64"
                            fill="none" stroke="#3B82F6" strokeWidth="12" />
                        </svg>
                        <div className="text-center z-10 flex flex-col items-center">
                          <span className="ch-counter text-4xl font-extrabold tracking-tighter text-white">0</span>
                          <span className="text-[8px] uppercase font-bold mt-0.5"
                                style={{ color: 'rgba(147,197,253,0.5)', letterSpacing: '0.1em' }}>{metricLabel}</span>
                        </div>
                      </div>

                      {/* Workflow step widgets */}
                      <div className="space-y-3">
                        <div className="ch-widget widget-depth rounded-2xl p-3 flex items-center">
                          <div className="w-10 h-10 rounded-xl flex items-center justify-center mr-3 border border-blue-400/20"
                               style={{ background: 'linear-gradient(135deg, rgba(59,130,246,0.2), rgba(37,99,235,0.05))', boxShadow: 'inset 0 1px 1px rgba(255,255,255,0.05)' }}>
                            <svg className="w-4 h-4 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                            </svg>
                          </div>
                          <div className="flex-1">
                            <div className="h-2 w-20 bg-neutral-300 rounded-full mb-2" />
                            <div className="h-1.5 w-12 bg-neutral-600 rounded-full" />
                          </div>
                        </div>
                        <div className="ch-widget widget-depth rounded-2xl p-3 flex items-center">
                          <div className="w-10 h-10 rounded-xl flex items-center justify-center mr-3 border border-emerald-400/20"
                               style={{ background: 'linear-gradient(135deg, rgba(16,185,129,0.2), rgba(5,150,105,0.05))', boxShadow: 'inset 0 1px 1px rgba(255,255,255,0.05)' }}>
                            <svg className="w-4 h-4 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                          </div>
                          <div className="flex-1">
                            <div className="h-2 w-16 bg-neutral-300 rounded-full mb-2" />
                            <div className="h-1.5 w-24 bg-neutral-600 rounded-full" />
                          </div>
                        </div>
                      </div>

                      {/* Home indicator */}
                      <div className="absolute bottom-2 left-1/2 -translate-x-1/2 w-[120px] h-[4px] rounded-full"
                           style={{ background: 'rgba(255,255,255,0.2)' }} />
                    </div>
                  </div>
                </div>

                {/* Floating badge — top left */}
                <div className="ch-badge absolute flex top-6 lg:top-12 floating-ui-badge rounded-xl lg:rounded-2xl p-3 lg:p-4 items-center gap-3 lg:gap-4 z-30"
                     style={{ left: '-15px' }}>
                  <div className="w-8 h-8 lg:w-10 lg:h-10 rounded-full flex items-center justify-center border border-blue-400/30"
                       style={{ background: 'linear-gradient(to bottom, rgba(59,130,246,0.2), rgba(30,58,138,0.1))' }}>
                    <span className="text-base lg:text-xl" aria-hidden="true">🚀</span>
                  </div>
                  <div>
                    <p className="text-white text-xs lg:text-sm font-bold tracking-tight">System Live</p>
                    <p className="text-[10px] lg:text-xs font-medium" style={{ color: 'rgba(147,197,253,0.5)' }}>Deployed in 5 days</p>
                  </div>
                </div>

                {/* Floating badge — bottom right */}
                <div className="ch-badge absolute flex bottom-12 lg:bottom-20 floating-ui-badge rounded-xl lg:rounded-2xl p-3 lg:p-4 items-center gap-3 lg:gap-4 z-30"
                     style={{ right: '-15px' }}>
                  <div className="w-8 h-8 lg:w-10 lg:h-10 rounded-full flex items-center justify-center border border-indigo-400/30"
                       style={{ background: 'linear-gradient(to bottom, rgba(99,102,241,0.2), rgba(55,48,163,0.1))' }}>
                    <span className="text-base lg:text-lg" aria-hidden="true">⚡</span>
                  </div>
                  <div>
                    <p className="text-white text-xs lg:text-sm font-bold tracking-tight">12h Saved</p>
                    <p className="text-[10px] lg:text-xs font-medium" style={{ color: 'rgba(147,197,253,0.5)' }}>This week, zero effort</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Left col (desktop) / Bottom (mobile): Accountability copy */}
            <div className="ch-card-left gsap-reveal order-3 lg:order-1 flex flex-col justify-center text-center lg:text-left z-20 w-full px-4 lg:px-0">
              <h3 className="text-white text-2xl md:text-3xl lg:text-4xl font-bold mb-0 lg:mb-5 tracking-tight">
                {cardHeading}
              </h3>
              <p className="hidden md:block text-sm md:text-base lg:text-lg font-normal leading-relaxed mx-auto lg:mx-0 max-w-sm lg:max-w-none"
                 style={{ color: 'rgba(147,197,253,0.7)' }}>
                {cardDescription}
              </p>
            </div>

          </div>
        </div>
      </div>
    </div>
  );
};

window.CinematicHero = CinematicHero;
