'use client'

import * as React from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { Menu, Globe, ArrowRight } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
  Sheet,
  SheetContent,
  SheetTrigger,
} from '@/components/ui/sheet'
import { cn } from '@/lib/utils'

// 导航结构 - 中文
const navigationCN = [
  { name: '首页', href: '/' },
  { name: '产品矩阵', href: '/products' },
  { name: '关于我们', href: '/about' },
  { name: '合作加盟', href: '/contact' },
]

// 导航结构 - 英文
const navigationEN = [
  { name: 'Home', href: '/en' },
  { name: 'Products', href: '/products' },
  { name: 'About', href: '/about' },
  { name: 'Contact', href: '/contact' },
]

export function Navbar() {
  const [isScrolled, setIsScrolled] = React.useState(false)
  const [language, setLanguage] = React.useState<'zh' | 'en'>('zh')
  const [mounted, setMounted] = React.useState(false)
  const [currentPath, setCurrentPath] = React.useState('')

  // 初始化语言状态和当前路径
  React.useEffect(() => {
    setMounted(true)
    if (typeof window !== 'undefined') {
      const path = window.location.pathname
      setLanguage(path.startsWith('/en') ? 'en' : 'zh')
      setCurrentPath(path)
    }
  }, [])

  // 监听路由变化，更新当前路径
  React.useEffect(() => {
    if (typeof window !== 'undefined') {
      const handlePopState = () => {
        setCurrentPath(window.location.pathname)
      }

      // 监听浏览器前进后退
      window.addEventListener('popstate', handlePopState)

      // 保存原始的pushState和replaceState
      const originalPushState = window.history.pushState
      const originalReplaceState = window.history.replaceState

      // 重写pushState和replaceState
      window.history.pushState = function(...args) {
        originalPushState.apply(this, args)
        handlePopState()
      }

      window.history.replaceState = function(...args) {
        originalReplaceState.apply(this, args)
        handlePopState()
      }

      return () => {
        window.removeEventListener('popstate', handlePopState)
      }
    }
  }, [])

  React.useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 20)
    }
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  // 根据语言选择导航
  const navigation = language === 'zh' ? navigationCN : navigationEN
  const currentLanguage = language

  // 切换语言
  const toggleLanguage = () => {
    const newLang = currentLanguage === 'zh' ? 'en' : 'zh'
    setLanguage(newLang)
    
    // 跳转到对应语言版本
    if (typeof window !== 'undefined') {
      const path = window.location.pathname
      let newPath = path
      
      if (newLang === 'en') {
        // 转到英文版（首页）
        if (path === '/') {
          newPath = '/en'
        } else {
          // 其他页面保持原样（暂时只有首页有英文版）
          newPath = '/en'
        }
      } else {
        // 转到中文版
        if (path.startsWith('/en')) {
          newPath = '/'
        } else {
          newPath = path
        }
      }
      
      window.location.href = newPath
    }
  }

  return (
    <header
      className={cn(
        'fixed top-0 left-0 right-0 z-50 transition-all duration-300',
        isScrolled
          ? 'bg-white/98 backdrop-blur-md shadow-sm border-b border-gray-100 py-3'
          : 'bg-transparent py-5'
      )}
    >
      <div className="container mx-auto px-4 flex items-center justify-between">
        {/* Logo */}
        <Link href={currentLanguage === 'zh' ? '/' : '/en'} className="flex items-center gap-3">
          <div className="relative h-14 w-auto aspect-[2/1]">
            <Image
                src="/baima-logo.png"
                alt="Baima Home Logo"
                fill
                className="object-contain"
                priority
              />
          </div>
        </Link>

        {/* Desktop Navigation */}
        <nav className="hidden lg:flex items-center gap-8">
          {navigation.map((item) => {
            // 检测当前活跃链接
            const isActive = mounted && currentPath === item.href;
            // 检测是否为首页
            const isHomePage = item.href === '/' || item.href === '/en';
            // 检测当前是否在指定的页面（/about、/products、/contact）
            const isOnSpecificPage = currentPath.startsWith('/about') || 
                                   currentPath.startsWith('/products') || 
                                   currentPath.startsWith('/contact');
            return (
              <Link
                key={item.name}
                href={item.href}
                className={cn(
                  "text-sm font-medium transition-colors hover:text-[#FF6600]",
                  isActive 
                    ? "text-[#FF6600]" 
                    : isOnSpecificPage || isScrolled 
                      ? "text-black" 
                      : isHomePage ? "text-black" : "text-white"
                )}
              >
                {item.name}
              </Link>
            );
          })}
        </nav>

        {/* Right Side Actions */}
        <div className="hidden lg:flex items-center gap-4">
          {/* <button 
            onClick={toggleLanguage}
            className={cn(
              "flex items-center gap-1.5 text-sm font-medium transition-colors hover:text-[#FF6600]",
              isScrolled ? "text-[#555]" : "text-white/90 drop-shadow-md"
            )}
          >
            <Globe className="w-4 h-4" />
            <span>{currentLanguage === 'zh' ? 'English' : '中文'}</span>
          </button> */}
          
          <Button 
            size="sm"
            className={cn(
              "flex items-center gap-2 px-5 py-2.5 rounded-full text-sm font-bold transition-all shadow-md",
              isScrolled 
                ? "bg-[#FF6600] hover:bg-[#FF8C00] text-white"
                : "bg-white text-[#FF6600] hover:bg-white/90"
            )}
            asChild
          >
            <Link href="/contact#form">
              {currentLanguage === 'zh' ? '立即咨询' : 'Get Started'}
            </Link>
          </Button>
        </div>

        {/* Mobile Navigation */}
        <div className="lg:hidden">
          <Sheet>
            <SheetTrigger asChild>
              <Button 
                variant="ghost" 
                size="icon" 
                className={cn(!isScrolled && "text-white drop-shadow-md")}
              >
                <Menu className="h-6 w-6" />
                <span className="sr-only">Open menu</span>
              </Button>
            </SheetTrigger>
            <SheetContent side="right" className="w-[300px] sm:w-[400px]">
              <div className="flex flex-col gap-6 mt-8">
                <div className="flex items-center gap-3 pb-4 border-b">
                  <div className="relative h-8 w-auto aspect-[2/1]">
                    <Image
                    src="./logos.png"
                    alt="Baima Home Logo"
                    fill
                    className="object-contain"
                  />
                  </div>
                </div>
                
                {/* 语言切换 */}
                <button 
                  onClick={toggleLanguage}
                  className="flex items-center gap-2 text-sm font-medium text-[#FF6600] py-2 px-4 bg-orange-50 rounded-lg"
                >
                  <Globe className="w-4 h-4" />
                  {currentLanguage === 'zh' ? 'Switch to English' : '切换到中文'}
                </button>
                
                <div className="flex flex-col gap-2">
                  {navigation.map((item) => {
                    // 检测当前活跃链接
                    const isActive = mounted && currentPath === item.href;
                    return (
                      <Link
                        key={item.name}
                        href={item.href}
                        className={cn(
                          "text-lg font-medium py-3 px-4 rounded-lg hover:bg-gray-100 transition-colors",
                          isActive ? "text-[#FF6600] bg-orange-50" : "text-gray-800"
                        )}
                      >
                        {item.name}
                      </Link>
                    );
                  })}
                </div>
                
                <div className="pt-4 mt-auto">
                  <Button className="w-full bg-[#FF6600] hover:bg-[#FF8C00] rounded-full" size="lg" asChild>
                    <Link href="/contact#form">
                      {currentLanguage === 'zh' ? '立即咨询' : 'Get Started'} <ArrowRight className="ml-2 w-4 h-4" />
                    </Link>
                  </Button>
                </div>
              </div>
            </SheetContent>
          </Sheet>
        </div>
      </div>
    </header>
  )
}
