<template>
  <header>
    <div class="header--wrap" :class="{ white: isScrolled || isMobileMenuOpen }">
      <div class="header--container">
        <NuxtLink class="logo--wrap" to="/">그린웨일글로벌</NuxtLink>
        <ul class="menu--wrap">
          <li class="menu--item">
            <NuxtLink to="/company/intro">Company</NuxtLink>
            <ul class="gnb--wrap">
              <li><NuxtLink to="/company/intro">회사소개</NuxtLink></li>
              <li><NuxtLink to="/company/history">회사연혁</NuxtLink></li>
              <li><NuxtLink to="/company/partners">협력업체</NuxtLink></li>
              <li><NuxtLink to="/company/catalog">회사소개자료</NuxtLink></li>
            </ul>
          </li>
          <li class="menu--item">
            <NuxtLink to="/products/materials">Products</NuxtLink>
            <ul class="gnb--wrap">
              <li><NuxtLink to="/products/materials">Materials</NuxtLink></li>
              <li><NuxtLink to="/products/solutions">Solutions</NuxtLink></li>
            </ul>
          </li>
          <li class="menu--item">
            <NuxtLink to="/technology/facilities">Technology</NuxtLink>
            <ul class="gnb--wrap">
              <li><NuxtLink to="/technology/facilities">시설</NuxtLink></li>
              <li><NuxtLink to="/technology/patents">특허 / 인증</NuxtLink></li>
            </ul>
          </li>
          <li class="menu--item">
            <NuxtLink to="/media/news">Media</NuxtLink>
            <ul class="gnb--wrap">
              <li><NuxtLink to="/media/news">환경뉴스</NuxtLink></li>
              <li><NuxtLink to="/media/press">보도자료</NuxtLink></li>
            </ul>
          </li>
          <li class="menu--item">
            <NuxtLink to="/contact/notice">Contact</NuxtLink>
            <ul class="gnb--wrap">
              <li><NuxtLink to="/contact/notice">공지사항</NuxtLink></li>
              <li><NuxtLink to="/contact/faq">FAQ</NuxtLink></li>
              <li><NuxtLink to="/contact/support">고객센터</NuxtLink></li>
              <li><NuxtLink to="/contact/location">오시는길</NuxtLink></li>
            </ul>
          </li>
        </ul>
        <div class="lang--wrap" :class="{ active: isLangOpen }" ref="langWrap" @click="toggleLang">
          <div class="ico"></div>
          <p>{{ currentLang }}</p>
          <ul class="select--wrap" :class="{ active: isLangOpen }">
            <li @click.stop="changeLang('ko')">한국어</li>
            <li @click.stop="changeLang('en')">English</li>
            <li @click.stop="changeLang('zh-CN')">中文(简体)</li>
            <li @click.stop="changeLang('zh-TW')">中文(繁體)</li>
            <li @click.stop="changeLang('ja')">日本語</li>
            <li @click.stop="changeLang('es')">Español</li>
            <li @click.stop="changeLang('fr')">Français</li>
            <li @click.stop="changeLang('de')">Deutsch</li>
            <li @click.stop="changeLang('ru')">Русский</li>
            <li @click.stop="changeLang('ar')">العربية</li>
            <li @click.stop="changeLang('el')">Ελληνικά</li>
            <li @click.stop="changeLang('la')">Latina</li>
            <li @click.stop="changeLang('ms')">Bahasa Melayu</li>
            <li @click.stop="changeLang('vi')">Tiếng Việt</li>
            <li @click.stop="changeLang('eo')">Esperanto</li>
            <li @click.stop="changeLang('it')">Italiano</li>
            <li @click.stop="changeLang('id')">Bahasa Indonesia</li>
            <li @click.stop="changeLang('km')">ភាសាខ្មែរ</li>
            <li @click.stop="changeLang('th')">ไทย</li>
            <li @click.stop="changeLang('tr')">Türkçe</li>
            <li @click.stop="changeLang('pt')">Português (Brasil)</li>
            <li @click.stop="changeLang('hu')">Magyar</li>
            <li @click.stop="changeLang('el')">Ελληνικά</li>
            <li @click.stop="changeLang('la')">Latina</li>
            <li @click.stop="changeLang('ms')">Bahasa Melayu</li>
            <li @click.stop="changeLang('vi')">Tiếng Việt</li>
            <li @click.stop="changeLang('eo')">Esperanto</li>
            <li @click.stop="changeLang('it')">Italiano</li>
            <li @click.stop="changeLang('id')">Bahasa Indonesia</li>
            <li @click.stop="changeLang('km')">ភាសាខ្មែរ</li>
            <li @click.stop="changeLang('th')">ไทย</li>
            <li @click.stop="changeLang('tr')">Türkçe</li>
            <li @click.stop="changeLang('pt')">Português (Brasil)</li>
            <li @click.stop="changeLang('hu')">Magyar</li>
          </ul>
        </div>
        <div class="ham--wrap" :class="{ active: isMobileMenuOpen }">
          <UButton @click="toggleMobileMenu"></UButton>
        </div>
      </div>
    </div>
    <div class="mobile--header--wrap" :class="{ active: isMobileMenuOpen }">
      <div class="mobile--menu--wrap">
        <ul>
          <li>
            <div
              @click="toggleAccordion('company')"
              :class="{ active: activeAccordion === 'company' }"
            >
              Company<i class="ico"></i>
            </div>
            <ul :class="{ active: activeAccordion === 'company' }">
              <li>
                <NuxtLink @click="closeMobileMenu" to="/company/intro">회사소개</NuxtLink>
              </li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/company/history"
                  >회사연혁</NuxtLink
                >
              </li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/company/partners"
                  >협력업체</NuxtLink
                >
              </li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/company/catalog"
                  >회사소개자료</NuxtLink
                >
              </li>
            </ul>
          </li>
          <li>
            <div
              @click="toggleAccordion('products')"
              :class="{ active: activeAccordion === 'products' }"
            >
              Products<i class="ico"></i>
            </div>
            <ul :class="{ active: activeAccordion === 'products' }">
              <li>
                <NuxtLink @click="closeMobileMenu" to="/products/materials"
                  >Materials</NuxtLink
                >
              </li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/products/solutions"
                  >Solutions</NuxtLink
                >
              </li>
            </ul>
          </li>
          <li>
            <div
              @click="toggleAccordion('technology')"
              :class="{ active: activeAccordion === 'technology' }"
            >
              Technology<i class="ico"></i>
            </div>
            <ul :class="{ active: activeAccordion === 'technology' }">
              <li>
                <NuxtLink @click="closeMobileMenu" to="/technology/facilities"
                  >시설</NuxtLink
                >
              </li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/technology/patents"
                  >특허 / 인증</NuxtLink
                >
              </li>
            </ul>
          </li>
          <li>
            <div
              @click="toggleAccordion('media')"
              :class="{ active: activeAccordion === 'media' }"
            >
              Media<i class="ico"></i>
            </div>
            <ul :class="{ active: activeAccordion === 'media' }">
              <li>
                <NuxtLink @click="closeMobileMenu" to="/media/news">환경뉴스</NuxtLink>
              </li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/media/press">보도자료</NuxtLink>
              </li>
            </ul>
          </li>
          <li>
            <div
              @click="toggleAccordion('contact')"
              :class="{ active: activeAccordion === 'contact' }"
            >
              Contact<i class="ico"></i>
            </div>
            <ul :class="{ active: activeAccordion === 'contact' }">
              <li>
                <NuxtLink @click="closeMobileMenu" to="/contact/notice"
                  >공지사항</NuxtLink
                >
              </li>
              <li><NuxtLink @click="closeMobileMenu" to="/contact/faq">FAQ</NuxtLink></li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/contact/support"
                  >고객센터</NuxtLink
                >
              </li>
              <li>
                <NuxtLink @click="closeMobileMenu" to="/contact/location"
                  >오시는길</NuxtLink
                >
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <div class="mobile--lang--wrap">
        <div class="lang--wrap" :class="{ active: isLangOpen2 }" ref="langWrap2" @click="toggleLang2">
          <div class="ico"></div>
          <p>{{ currentLang }}</p>
          <ul class="select--wrap" :class="{ active: isLangOpen2 }">
            <li @click.stop="changeLang('ko')">한국어</li>
            <li @click.stop="changeLang('en')">English</li>
            <li @click.stop="changeLang('zh-CN')">中文(简体)</li>
            <li @click.stop="changeLang('zh-TW')">中文(繁體)</li>
            <li @click.stop="changeLang('ja')">日본語</li>
            <li @click.stop="changeLang('es')">Español</li>
            <li @click.stop="changeLang('fr')">Français</li>
            <li @click.stop="changeLang('de')">Deutsch</li>
            <li @click.stop="changeLang('ru')">Русский</li>
            <li @click.stop="changeLang('ar')">العربية</li>
            <li @click.stop="changeLang('el')">Ελληνικά</li>
            <li @click.stop="changeLang('la')">Latina</li>
            <li @click.stop="changeLang('ms')">Bahasa Melayu</li>
            <li @click.stop="changeLang('vi')">Tiếng Việt</li>
            <li @click.stop="changeLang('eo')">Esperanto</li>
            <li @click.stop="changeLang('it')">Italiano</li>
            <li @click.stop="changeLang('id')">Bahasa Indonesia</li>
            <li @click.stop="changeLang('km')">ភាសាខ្មែរ</li>
            <li @click.stop="changeLang('th')">ไทย</li>
            <li @click.stop="changeLang('tr')">Türkçe</li>
            <li @click.stop="changeLang('pt')">Português (Brasil)</li>
            <li @click.stop="changeLang('hu')">Magyar</li>
          </ul>
        </div>
      </div>
    </div>
    <!-- Hidden Google Translate component for functionality -->
    <ClientOnly>
      <GoogleTranslate />
    </ClientOnly>
  </header>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from "vue";
  import { useGoogleTranslate } from '#imports';

  const isScrolled = ref(false);
  const isMobileMenuOpen = ref(false);
  const activeAccordion = ref(null);
  const isLangOpen = ref(false);
  const isLangOpen2 = ref(false);
  const currentLang = ref('한국어');
  const langWrap = ref(null);
  const langWrap2 = ref(null);
  
  // Google Translate 기능 사용
  let setLanguage;
  try {
    const googleTranslate = useGoogleTranslate();
    setLanguage = googleTranslate.setLanguage;
  } catch (error) {
    console.warn('Google Translate not available:', error);
    setLanguage = (lang) => console.log('Would translate to:', lang);
  }
  
  // 언어 매핑
  const langMap = {
    'ko': '한국어',
    'en': 'English',
    'zh-CN': '中文(简体)',
    'zh-TW': '中文(繁體)',
    'ja': '日本語',
    'es': 'Español',
    'fr': 'Français',
    'de': 'Deutsch',
    'ru': 'Русский',
    'ar': 'العربية',
    'el': 'Ελληνικά',     // 그리스어
    'la': 'Latina',       // 라틴어
    'ms': 'Bahasa Melayu', // 말레이어
    'vi': 'Tiếng Việt',   // 베트남어
    'eo': 'Esperanto',    // 에스페란토어
    'it': 'Italiano',     // 이탈리아어
    'id': 'Bahasa Indonesia', // 인도네시아어
    'km': 'ភាសាខ្មែរ',      // 크메르어
    'th': 'ไทย',          // 태국어
    'tr': 'Türkçe',       // 튀르키예어
    'pt': 'Português (Brasil)', // 포르투갈어(브라질)
    'hu': 'Magyar'        // 헝가리어
  };

  const handleScroll = () => {
    // 모바일 메뉴가 열려있으면 스크롤 위치와 상관없이 white 클래스 유지
    if (isMobileMenuOpen.value) {
      isScrolled.value = true;
    } else {
      isScrolled.value = window.scrollY > 0;
    }
  };

  const toggleMobileMenu = () => {
    isMobileMenuOpen.value = !isMobileMenuOpen.value;
  };
  
  const toggleLang = () => {
    isLangOpen.value = !isLangOpen.value;
  };

  const toggleLang2 = () => {
    isLangOpen2.value = !isLangOpen2.value;
  };
  
  const changeLang = (langCode) => {
    // 먼저 드롭다운을 닫음
    isLangOpen.value = false;
    isLangOpen2.value = false;
    
    // UI 업데이트
    currentLang.value = langMap[langCode] || langCode.toUpperCase();
    
    // Google Translate 모듈 사용하여 언어 변경
    setLanguage(langCode);
    
    // localStorage에 선택된 언어 저장
    if (typeof window !== 'undefined') {
      localStorage.setItem('selectedLanguage', langCode);
    }
    
    console.log(`Language changed to: ${langCode}`);
  };
  
  // 페이지 로드 시 저장된 언어 복원
  const restoreLanguage = () => {
    if (typeof window !== 'undefined') {
      const savedLang = localStorage.getItem('selectedLanguage');
      if (savedLang && savedLang !== 'ko') {
        currentLang.value = langMap[savedLang] || savedLang.toUpperCase();
      }
    }
  };

  const toggleAccordion = (section) => {
    if (activeAccordion.value === section) {
      activeAccordion.value = null;
    } else {
      activeAccordion.value = section;
    }
  };

  const closeMobileMenu = () => {
    isMobileMenuOpen.value = false;
    activeAccordion.value = null;
  };
  
  const handleClickOutside = (event) => {
    if (langWrap.value && !langWrap.value.contains(event.target)) {
      isLangOpen.value = false;
    }
  };

  const handleClickOutside2 = (event) => {
    if (langWrap2.value && !langWrap2.value.contains(event.target)) {
      isLangOpen2.value = false;
    }
  };
  


  onMounted(() => {
    window.addEventListener("scroll", handleScroll);
    document.addEventListener('click', handleClickOutside);
    document.addEventListener('click', handleClickOutside2);
    
    // 저장된 언어 설정 복원
    restoreLanguage();
  });

  onUnmounted(() => {
    window.removeEventListener("scroll", handleScroll);
    document.removeEventListener('click', handleClickOutside);
    document.removeEventListener('click', handleClickOutside2);
  });
</script>

<style scoped>
/* 드롭다운 애니메이션 및 상태 관리 */
.lang--wrap .select--wrap {
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s ease;
}

.lang--wrap.active .select--wrap {
  opacity: 1;
  pointer-events: all;
}

/* 모바일 드롭다운 */
.mobile--lang--wrap .lang--wrap .select--wrap {
  opacity: 0;
  pointer-events: none;
  transition: all 0.3s ease;
  max-height: 300px; /* 높이 조정 */
}

.mobile--lang--wrap .lang--wrap.active .select--wrap {
  opacity: 1;
  pointer-events: all;
}

/* 데스크톱 드롭다운 높이 조정 */
.lang--wrap .select--wrap {
  max-height: 300px; /* 높이 조정 */
}
</style>
