(function () {
  'use strict';

  var config = window.PPQ_TRANSLATE_CONFIG || {};
  if (!config.enabled || window.top !== window.self) return;

  var languages = {
    'zh-CN': { api: 'chinese_simplified', label: '简体中文' },
    'zh-TW': { api: 'chinese_traditional', label: '繁體中文' },
    en: { api: 'english', label: 'English' },
    ja: { api: 'japanese', label: '日本語' },
    ko: { api: 'korean', label: '한국어' },
    vi: { api: 'vietnamese', label: 'Tiếng Việt' },
    id: { api: 'indonesian', label: 'Bahasa Indonesia' },
    ms: { api: 'malay', label: 'Bahasa Melayu' },
    th: { api: 'thai', label: 'ไทย' },
    fil: { api: 'filipino', label: 'Filipino' },
    hi: { api: 'hindi', label: 'हिन्दी' },
    fr: { api: 'french', label: 'Français' }
  };
  var storageKey = 'ppq_translate_language';
  var available = (config.languages || []).filter(function (key) { return languages[key]; });
  if (!available.length) available = ['zh-CN'];

  function detectLanguage() {
    var value = String(navigator.language || navigator.userLanguage || 'zh-CN').toLowerCase();
    if (value.indexOf('zh-tw') === 0 || value.indexOf('zh-hk') === 0 || value.indexOf('zh-mo') === 0) return 'zh-TW';
    if (value.indexOf('ja') === 0) return 'ja';
    if (value.indexOf('ko') === 0) return 'ko';
    if (value.indexOf('vi') === 0) return 'vi';
    if (value.indexOf('id') === 0) return 'id';
    if (value.indexOf('ms') === 0) return 'ms';
    if (value.indexOf('th') === 0) return 'th';
    if (value.indexOf('fil') === 0 || value.indexOf('tl') === 0) return 'fil';
    if (value.indexOf('hi') === 0) return 'hi';
    if (value.indexOf('fr') === 0) return 'fr';
    if (value.indexOf('en') === 0) return 'en';
    return 'zh-CN';
  }

  function requestedLanguage() {
    var saved = '';
    try { saved = window.localStorage.getItem(storageKey) || ''; } catch (error) {}
    if (available.indexOf(saved) !== -1) return saved;
    var auto = config.auto ? detectLanguage() : 'zh-CN';
    return available.indexOf(auto) !== -1 ? auto : 'zh-CN';
  }

  function clampTranslatedText() {
    var twoLine = [
      '.ppq-home-title', '.ppq-home-more', '.cats a', 'nav a', '.menu a',
      '.category a', '.categories a', '.type a', '.btn', 'button',
      '[class*="video-title"]', '[class*="vod-title"]', '[class*="card-title"]',
      '[class*="video-name"]', '[class*="vod-name"]', '.name'
    ];
    var threeLine = ['.video-desc', '.vod-desc', '.detail-desc', '.description', '.summary', '.intro'];
    function addClass(selector, className) {
      var nodes = document.querySelectorAll(selector);
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (!node.closest('.ppq-translate-ui, video, audio, script, style')) node.classList.add(className);
      }
    }
    addClass(twoLine.join(','), 'ppq-i18n-clamp-2');
    addClass(threeLine.join(','), 'ppq-i18n-clamp-3');
  }

  function setTranslateIgnore() {
    if (!window.translate) return false;
    try {
      if (window.translate.service && window.translate.service.use) window.translate.service.use('client.edge');
      if (window.translate.ignore && window.translate.ignore.class && window.translate.ignore.class.push) {
        window.translate.ignore.class.push('ppq-translate-ui');
      }
      return true;
    } catch (error) {
      return false;
    }
  }

  function applyLanguage(language) {
    if (language === 'zh-CN') return;
    if (!setTranslateIgnore()) return;
    try {
      if (window.translate.language && window.translate.language.setLocal) {
        window.translate.language.setLocal('zh-CN');
      }
      // Use the v2 execution path. changeLanguage() treats standard codes as
      // the legacy v1 API and forces a page reload, which is not suitable for
      // an automatic visitor-language translation layer.
      if (window.translate.language && window.translate.language.setDefaultTo) {
        if (window.translate.language.clearCacheLanguage) window.translate.language.clearCacheLanguage();
        window.translate.language.setDefaultTo(languages[language].api);
      }
      if (window.translate.execute) window.translate.execute();
      document.documentElement.classList.add('ppq-i18n-active');
    } catch (error) {}
  }

  function renderSelector(current) {
    var root = document.createElement('div');
    root.id = 'ppq-language-switcher';
    root.className = 'ppq-translate-ui ppq-translate--' + (config.position === 'bottom-left' ? 'bottom-left' : 'bottom-right');
    root.setAttribute('translate', 'no');
    var label = languages[current] ? languages[current].label : '语言';
    var html = '<button type="button" class="ppq-language-trigger" aria-expanded="false" aria-controls="ppq-language-menu" aria-label="选择语言 / Language" title="选择语言 / Language"><span class="ppq-language-mark" aria-hidden="true"><b>A</b><i>文</i></span><span class="ppq-language-current">' + label + '</span></button><div id="ppq-language-menu" class="ppq-language-menu" role="menu">';
    for (var i = 0; i < available.length; i++) {
      var code = available[i];
      html += '<button type="button" role="menuitem" data-language="' + code + '"' + (code === current ? ' aria-current="true"' : '') + '>' + languages[code].label + '</button>';
    }
    root.innerHTML = html + '</div>';
    document.body.appendChild(root);

    var trigger = root.querySelector('.ppq-language-trigger');
    trigger.addEventListener('click', function () {
      var opened = root.classList.toggle('is-open');
      trigger.setAttribute('aria-expanded', opened ? 'true' : 'false');
    });
    root.addEventListener('click', function (event) {
      var button = event.target.closest('[data-language]');
      if (!button) return;
      var next = button.getAttribute('data-language');
      if (next === current) { root.classList.remove('is-open'); return; }
      try { window.localStorage.setItem(storageKey, next); } catch (error) {}
      window.location.reload();
    });
    document.addEventListener('click', function (event) {
      if (!root.contains(event.target)) { root.classList.remove('is-open'); trigger.setAttribute('aria-expanded', 'false'); }
    });
  }

  function start() {
    var current = requestedLanguage();
    clampTranslatedText();
    renderSelector(current);
    applyLanguage(current);
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start);
  else start();
}());
