import { useRef, useEffect } from "react";
import { NavArrowDown, Airplane, AppWindow } from "iconoir-react";
import { GridLines } from "./FloatingElements";
import { FlipWords } from "@/components/ui/flipwords";
import { useIsMobile } from "@/hooks/use-mobile";
import earthNight from "@/assets/earth-night.webp";
import earthNightMobile from "@/assets/earth-night-mobile.webp";
import brlFlag from "@/assets/flags/brl.svg";
import usdFlag from "@/assets/flags/usd.svg";
import eurFlag from "@/assets/flags/eur.svg";
import gbpFlag from "@/assets/flags/gbp.svg";
import audFlag from "@/assets/flags/aud.svg";
import chfFlag from "@/assets/flags/chf.svg";
import cadFlag from "@/assets/flags/cad.svg";

export const Hero = () => {
  const containerRef = useRef<HTMLDivElement>(null);
  const isMobile = useIsMobile();

  // Parallax scroll effect usando CSS variables
  useEffect(() => {
    let rafId = 0;
    const handleScroll = () => {
      cancelAnimationFrame(rafId);
      rafId = requestAnimationFrame(() => {
        if (!containerRef.current) return;
        
        const rect = containerRef.current.getBoundingClientRect();
        const windowHeight = window.innerHeight;
        const progress = Math.max(0, Math.min(1, -rect.top / windowHeight));
        
        const multiplier = isMobile ? 0.5 : 1;
        const style = document.documentElement.style;
        style.setProperty('--hero-scroll', `${progress}`);
        style.setProperty('--hero-globe-y', `${progress * 100 * multiplier}px`);
        style.setProperty('--hero-bg-y', `${-progress * 40 * multiplier}px`);
        style.setProperty('--hero-bg-opacity', `${progress * 0.8}`);
        style.setProperty('--hero-badge-y', `${progress * (isMobile ? 15 : 30)}px`);
        style.setProperty('--hero-text-scale', `${1 + progress * (isMobile ? 0.08 : 0.15)}`);
        style.setProperty('--hero-text-opacity', `${Math.max(0, 1 - progress * 2.5)}`);
        style.setProperty('--hero-subtitle-y', `${progress * (isMobile ? 60 : 120)}px`);
        style.setProperty('--hero-subtitle-opacity', `${Math.max(0, 1 - progress * 2.8)}`);
        style.setProperty('--hero-cta-y', `${progress * (isMobile ? 75 : 150)}px`);
        style.setProperty('--hero-cta-opacity', `${Math.max(0, 1 - progress * 2.5)}`);
        style.setProperty('--hero-indicators-y', `${progress * (isMobile ? 20 : 40)}px`);
        style.setProperty('--hero-word3-y', `${progress * (isMobile ? 30 : 60)}px`);
        style.setProperty('--hero-word3-x', `${progress * (isMobile ? -15 : -30)}px`);
        style.setProperty('--hero-word4-y', `${progress * (isMobile ? 50 : 100)}px`);
        style.setProperty('--hero-word4-x', `${progress * (isMobile ? 25 : 50)}px`);
      });
    };

    handleScroll();
    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => {
      cancelAnimationFrame(rafId);
      window.removeEventListener('scroll', handleScroll);
    };
  }, [isMobile]);

  const trustIndicators = [
    { text: "Autorizada pelo Banco Central" },
    { text: "+20 anos de Mercado de Câmbio" },
    { text: "+2 Bilhões de Dólares Operados" },
  ];

  return (
    <section
      ref={containerRef}
      id="hero"
      className="relative min-h-screen flex flex-col justify-start overflow-hidden gradient-hero pt-28 sm:pt-32 md:pt-0 md:justify-center pb-12 md:pb-0"
    >
      {/* Earth Night Background - Desktop Only (picture element prevents mobile download) */}
      <div className="absolute inset-0 overflow-hidden">
        <picture>
          <source media="(max-width: 768px)" srcSet="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" />
          <source media="(min-width: 769px)" srcSet={earthNight} />
          <img 
            src={earthNight}
            alt=""
            aria-hidden="true"
            className="absolute inset-0 w-full h-full object-cover object-center"
            loading="eager"
            fetchPriority="high"
            decoding="async"
          />
        </picture>
        {/* Dark overlay for better text contrast */}
        <div className="absolute inset-0 bg-gradient-to-b from-black/40 via-black/30 to-background" />
      </div>

      {/* Grid lines - subtle overlay (desktop only) */}
      {!isMobile && (
        <div className="absolute inset-0 opacity-30">
          <GridLines />
        </div>
      )}

      {/* Floating Flag Icons - Background Layer (Behind Text) - Desktop only */}
      {!isMobile && (
        <div className="absolute inset-0 overflow-hidden pointer-events-none z-0">
          <img src={brlFlag} alt="" className="currency-float currency-float-1 absolute w-12 h-12" style={{ top: '15%', left: '12%', opacity: 0.35 }} />
          <img src={gbpFlag} alt="" className="currency-float currency-float-4 absolute w-10 h-10" style={{ top: '35%', right: '15%', opacity: 0.4 }} />
          <img src={chfFlag} alt="" className="currency-float currency-float-6 absolute w-9 h-9" style={{ bottom: '30%', left: '45%', opacity: 0.38 }} />
        </div>
      )}
      
      {/* Floating Flag Icons - Foreground Layer - Desktop only */}
      {!isMobile && (
        <div className="absolute inset-0 overflow-hidden pointer-events-none z-20">
          <img src={usdFlag} alt="" className="currency-float currency-float-2 absolute w-14 h-14" style={{ top: '8%', right: '10%', opacity: 0.55 }} />
          <img src={cadFlag} alt="" className="currency-float currency-float-7 absolute w-11 h-11" style={{ top: '22%', right: '5%', opacity: 0.5 }} />
          <img src={eurFlag} alt="" className="currency-float currency-float-3 absolute w-14 h-14" style={{ top: '45%', left: '8%', opacity: 0.48 }} />
          <img src={audFlag} alt="" className="currency-float currency-float-5 absolute w-12 h-12" style={{ bottom: '20%', left: '12%', opacity: 0.48 }} />
        </div>
      )}

      {/* Content with multi-layer parallax */}
      <div className="container mx-auto px-4 sm:px-6 relative z-10" style={{ zIndex: 10 }}>
        <div className="max-w-4xl mx-auto text-center">
          {/* Badge */}
          <div className="hero-badge-parallax hero-fade-in mb-8 sm:mb-10 md:mb-8">
            <span className="inline-block px-3 py-1.5 sm:px-4 sm:py-2 rounded-full glass text-xs sm:text-sm font-medium text-primary">
              🚀 Câmbio sem burocracia
            </span>
          </div>

          {/* Headline with FlipWords animation */}
          <h1
            className="hero-text-scale hero-text-opacity hero-fade-in font-display text-3xl sm:text-4xl md:text-5xl lg:text-7xl font-bold leading-tight mb-6 sm:mb-8 md:mb-10 px-2 overflow-visible text-foreground text-center"
          >
            <span className="sr-only">Câmbio Hoje — Câmbio Turismo e Remessas Internacionais. </span>
            <div className="flex items-center justify-center mb-1 sm:mb-2">
              <div className="relative min-w-[200px] sm:min-w-[280px] md:min-w-[360px] lg:min-w-[450px]">
                <FlipWords
                  words={["Investindo", "Viajando", "Estudando"]}
                  duration={3000}
                  className="text-primary font-bold"
                />
              </div>
            </div>
            <span 
              className="hero-word3-parallax inline-block text-foreground"
            >
              câmbio é aqui,
            </span>{" "}
            <span 
              className="hero-word4-parallax inline-block gradient-text"
            >
              é hoje!
            </span>
          </h1>

          {/* Neon line divider */}
          <div className="hero-fade-in relative mx-auto mb-8 sm:mb-10 md:mb-10 max-w-md">
            <div className="h-[1px] w-full bg-gradient-to-r from-transparent via-primary to-transparent" />
            <div className="absolute inset-0 h-[1px] bg-gradient-to-r from-transparent via-primary to-transparent blur-[4px]" />
            <div className="absolute inset-0 h-[1px] bg-gradient-to-r from-transparent via-primary/80 to-transparent blur-[8px]" />
          </div>

          {/* Subheadline */}
          <p
            className="hero-subtitle-parallax hero-fade-in text-sm sm:text-base md:text-lg lg:text-xl text-muted-foreground max-w-2xl mx-auto mb-8 sm:mb-10 md:mb-10 px-2"
          >
            Esqueça a burocracia dos bancos tradicionais. Operações de câmbio 
            rápidas, seguras e com as melhores taxas do mercado. 
            <span className="text-foreground font-medium"> Atendimento humano de verdade.</span>
          </p>

          {/* CTA buttons */}
          <div
            className="hero-cta-parallax hero-fade-in flex flex-col sm:flex-row gap-4 sm:gap-4 justify-center items-center px-2"
          >
            {/* Cotações Turismo button */}
            <button 
              onClick={() => {
                const section = document.querySelector("#cambio-turismo");
                if (section) {
                  const sectionTop = section.getBoundingClientRect().top + window.scrollY;
                  const sectionHeight = section.scrollHeight;
                  const targetScroll = sectionTop + (sectionHeight * 0.75);
                  window.scrollTo({ top: targetScroll, behavior: "smooth" });
                }
              }}
              className="group relative inline-flex items-center justify-center gap-2.5 px-8 sm:px-10 py-4 sm:py-4.5 rounded-full
                         w-full sm:w-auto overflow-hidden
                         bg-gradient-to-br from-white/20 via-white/15 to-white/10
                         md:backdrop-blur-3xl
                         border border-white/60
                         shadow-[0_8px_32px_rgba(255,255,255,0.12),inset_0_2px_0_rgba(255,255,255,0.4)]
                         hover:from-white/30 hover:via-white/25 hover:to-white/20
                         hover:border-white/70
                         hover:shadow-[0_8px_40px_rgba(255,255,255,0.18),inset_0_2px_0_rgba(255,255,255,0.5)]
                         hover:scale-[1.02] active:scale-[0.98]
                         transition-all duration-300"
            >
              <div className="absolute inset-x-4 top-0 h-px bg-gradient-to-r from-transparent via-white/60 to-transparent" />
              <Airplane width={20} height={20} className="text-white opacity-90 group-hover:opacity-100 transition-opacity" />
              <span className="text-white font-semibold text-base sm:text-lg">Cotações Turismo</span>
              <NavArrowDown width={18} height={18} className="text-white opacity-70 group-hover:opacity-100 group-hover:translate-y-0.5 transition-all" />
            </button>
            
            {/* Nossas Soluções button */}
            <button 
              onClick={() => {
                const element = document.querySelector("#servicos");
                if (element) {
                  element.scrollIntoView({ behavior: "smooth" });
                }
              }}
              className="group relative inline-flex items-center justify-center gap-2.5 px-7 sm:px-8 py-3.5 sm:py-4 rounded-full
                         bg-transparent md:backdrop-blur-sm border border-white/40
                         text-white font-semibold text-base sm:text-lg
                         hover:bg-white/10 hover:border-white/30 hover:text-white hover:scale-[1.02]
                         active:scale-[0.98]
                         transition-all duration-300 ease-out
                         w-full sm:w-auto"
            >
              <AppWindow width={20} height={20} className="opacity-60 group-hover:opacity-100 transition-opacity" />
              Nossas Soluções
              <NavArrowDown width={18} height={18} className="opacity-40 group-hover:opacity-80 group-hover:translate-y-0.5 transition-all" />
            </button>
          </div>

          {/* Trust indicators */}
          <div
            className="hero-indicators-parallax hero-fade-in mt-10 sm:mt-14 md:mt-16 flex flex-col sm:flex-row flex-wrap justify-center items-center gap-4 sm:gap-6 md:gap-8 text-muted-foreground text-xs sm:text-sm px-4"
          >
            {trustIndicators.map((indicator) => (
              <div
                key={indicator.text}
                className="flex items-center gap-2"
              >
                <div className="w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full bg-green-500" />
                {indicator.text}
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};
