---
/**
 * HeroSection - Pixel-perfect Hero component matching Webflow design
 * Supports video background with fallback image and gradient overlay
 */
import { Image } from 'astro:assets'
import type { HomeData } from '@/lib/api/home'

interface Props {
  homeData?: HomeData | null
  fallbackDesktopVideo?: string
  fallbackMobileVideo?: string
}

const {
  homeData,
  fallbackDesktopVideo = '/video/enchun-hero-background-video.mp4',
  fallbackMobileVideo = '/video/enchun-hero-background-video.webm',
} = Astro.props

// Extract hero content from CMS data or use defaults
const heroHeadline = homeData?.heroHeadline || '創造企業更多發展的可能性\n是我們的使命'
const heroSubheadline = homeData?.heroSubheadline || "It's our destiny to create possibilities for your business."

// Get video URLs from CMS or fallback
const desktopVideoUrl = homeData?.heroDesktopVideo?.url || fallbackDesktopVideo
const mobileVideoUrl = homeData?.heroMobileVideo?.url || fallbackMobileVideo

// Get fallback image
const fallbackImageUrl = homeData?.heroFallbackImage?.url

// Get logo
const logoUrl = homeData?.heroLogo?.url || '/enchun-logo-full.svg'

// Helper to get base path without extension
const getBasePath = (path: string) => path.replace(/\.(mp4|webm)$/i, '')

// Generate sources for video elements
const getSources = (inputPath: string) => {
  const basePath = getBasePath(inputPath)
  return [
    { src: `${basePath}.webm`, type: 'video/webm' },
    { src: `${basePath}.mp4`, type: 'video/mp4' },
  ]
}
---

<!-- Fallback Image (shown when video fails to load) -->
{
  fallbackImageUrl && (
    <div class="absolute top-0 left-0 w-full h-[100dvh] z-0">
      <img
        src={fallbackImageUrl}
        alt="Hero background"
        class="w-full h-full object-cover"
        loading="eager"
        decoding="sync"
      />
      <div class="absolute top-0 left-0 w-full h-full hero-overlay-home"></div>
    </div>
  )
}

<!-- Desktop Video -->
<video
  id="desktop-video"
  class="background-video hidden md:block absolute top-0 left-0 w-full h-[100dvh] object-cover z-0"
  autoplay
  muted
  loop
  playsinline
  preload="metadata"
>
  {
    getSources(desktopVideoUrl).map((source) => (
      <source src={source.src} type={source.type} />
    ))
  }
</video>

<!-- Mobile Video -->
<video
  id="mobile-video"
  class="background-video md:hidden block absolute top-0 left-0 w-full h-[100dvh] object-cover z-0"
  autoplay
  muted
  loop
  playsinline
  preload="metadata"
>
  {
    getSources(mobileVideoUrl).map((source) => (
      <source src={source.src} type={source.type} />
    ))
  }
</video>

<!-- Hero Content Overlay -->
<section class="hero-section -mt-[5rem] flex items-center justify-center relative z-10 overflow-hidden">
  <!-- Gradient Overlay -->
  <div class="absolute top-0 left-0 w-full h-full hero-overlay-home"></div>

  <div class="max-w-6xl mx-auto w-full px-8 relative z-10">
    <div class="flex items-center justify-start mb-6">
      <!-- Logo (135px width per spec) -->
      <Image
        height={201}
        width={135}
        src={logoUrl}
        alt="Enchun Logo"
        class="hidden md:block hero-logo mr-8"
      />

      <!-- Text Content -->
      <div class="flex flex-col items-start justify-start">
        <!-- Main Headline - 3.39em (64px at 19px base) -->
        <h1 class="hero-title-head whitespace-break-spaces">
          {heroHeadline}
        </h1>

        <!-- Subheadline - 1.56em (30px at 19px base) -->
        <p class="hero-sub-paragraph-home">
          {heroSubheadline}
        </p>
      </div>
    </div>
  </div>
</section>

<style>
  /* Hero Section Styles - Pixel-perfect from Webflow */
  .hero-section {
    height: 100vh;
    max-height: 88.5vh;
    padding-top: 110px;
    padding-bottom: 100px;
  }

  /* Gradient Overlay - left to right fade */
  .hero-overlay-home {
    background: linear-gradient(
      to right,
      rgba(0, 0, 0, 0.8) 0%,
      rgba(0, 0, 0, 0) 100%
    );
  }

  /* Background Video */
  .background-video {
    position: absolute;
    z-index: -1;
  }

  /* Logo */
  .hero-logo {
    width: 135px;
    padding-top: 33px;
  }

  /* Hero Title - 3.39em (64px at 19px base) */
  .hero-title-head {
    font-size: 3.39em;
    line-height: 1.2;
    text-align: left;
    color: #ffffff;
    font-family: "Noto Sans TC", sans-serif;
    font-weight: 700;
  }

  /* Hero Subtitle - 1.56em (30px at 19px base) */
  .hero-sub-paragraph-home {
    font-size: 1.56em;
    font-weight: 300;
    line-height: 1.2;
    text-align: left;
    color: #f2f2f2;
    font-family: "Quicksand", "Noto Sans TC", sans-serif;
  }

  /* Responsive Adjustments */
  @media (max-width: 991px) {
    .hero-section {
      height: 100vh;
      max-height: 100vh;
      padding-top: 0;
      padding-bottom: 0;
    }

    .hero-title-head {
      font-size: 2.45em; /* ~47px */
    }

    .hero-sub-paragraph-home {
      font-size: 1.15em; /* ~22px */
    }
  }

  @media (max-width: 767px) {
    .hero-title-head {
      font-size: 7vw;
    }

    .hero-sub-paragraph-home {
      font-size: 3.4vw;
    }
  }
</style>

<script>
  // Enhanced mobile/desktop detection and video loading
  function initVideoHero() {
    const desktopVideo = document.getElementById('desktop-video') as HTMLVideoElement
    const mobileVideo = document.getElementById('mobile-video') as HTMLVideoElement

    if (!desktopVideo || !mobileVideo) return

    // Function to check if we're on mobile
    const isMobile = () => window.innerWidth < 768

    // Function to switch videos based on device
    const switchVideos = () => {
      const mobile = isMobile()

      if (mobile) {
        desktopVideo.style.display = 'none'
        mobileVideo.style.display = 'block'
      } else {
        desktopVideo.style.display = 'block'
        mobileVideo.style.display = 'none'
      }
    }

    // Initial switch
    switchVideos()

    // Listen for resize events
    window.addEventListener('resize', () => {
      switchVideos()
    })

    // Handle video loading errors
    ;(desktopVideo as any).onerror = () => {
      console.warn('Desktop video failed to load')
    }

    ;(mobileVideo as any).onerror = () => {
      console.warn('Mobile video failed to load')
    }

    // Preload videos when they're hidden to improve switching
    const preloadVideos = () => {
      ;[desktopVideo, mobileVideo].forEach((video) => {
        if ((video as HTMLVideoElement).style.display === 'none') {
          video.load()
        }
      })
    }

    // Preload on load
    window.addEventListener('load', preloadVideos)
  }

  // Initialize when DOM is ready
  document.addEventListener('DOMContentLoaded', initVideoHero)
  if (document.readyState !== 'loading') {
    initVideoHero()
  }
</script>
