/**
 * Google Translate for the "More languages" part of the language menu (components/LangSwitch.astro).
 *
 *  - Nothing from Google loads with the page. The Google script is added only when a visitor picks a language,
 *    or on later pages when they already picked one (Google keeps the choice in the "googtrans" cookie).
 *  - Google's own top bar and pop-ups are hidden (styles/global.css); the globe button shows the chosen language,
 *    and English / Español in the menu go back to the original page.
 *  - Elements with translate="no" (brand name, the language menu) are never translated.
 */
declare global {
  interface Window { googleTranslateElementInit?: () => void; google?: any }
}

const COOKIE = 'googtrans';
const pageLang = () => document.documentElement.lang || 'en';

/** chosen Google language ('' = none): cookie value is "/<from>/<to>" */
export function currentTarget(): string {
  const m = document.cookie.match(/(?:^|;\s*)googtrans=([^;]*)/);
  const to = m ? decodeURIComponent(m[1]).split('/')[2] || '' : '';
  return to && to !== pageLang() ? to : '';
}

/** every domain Google may have set the cookie on (host, .host, parent domain) */
function domains() {
  const h = location.hostname;
  const parts = h.split('.');
  const list = ['', h, `.${h}`];
  if (parts.length > 2) list.push(`.${parts.slice(-2).join('.')}`);
  return list;
}

function setCookie(value: string, maxAge: number) {
  for (const d of domains()) document.cookie = `${COOKIE}=${value}; path=/; max-age=${maxAge}; SameSite=Lax${d ? `; domain=${d}` : ''}`;
}

/** stop translating (used before going to the original or the Spanish page) */
export function clearTranslation() {
  setCookie('', 0);
  document.documentElement.removeAttribute('data-gt');
}

let loading: Promise<void> | null = null;
function loadGoogle(): Promise<void> {
  if (loading) return loading;
  loading = new Promise((resolve, reject) => {
    const box = document.createElement('div');
    box.id = 'google_translate_element';
    box.className = 'gt-hidden';
    box.setAttribute('aria-hidden', 'true');
    document.body.append(box);
    window.googleTranslateElementInit = () => {
      new window.google.translate.TranslateElement({ pageLanguage: pageLang(), autoDisplay: false }, 'google_translate_element');
      resolve();
    };
    const s = document.createElement('script');
    s.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
    s.async = true;
    s.onerror = () => { loading = null; box.remove(); reject(new Error('Google Translate could not be loaded')); };
    document.head.append(s);
  });
  return loading;
}

/** Google's hidden language <select>; it appears a moment after the script starts */
async function combo(): Promise<HTMLSelectElement | null> {
  for (let i = 0; i < 60; i++) {
    const el = document.querySelector<HTMLSelectElement>('select.goog-te-combo');
    if (el && el.options.length > 1) return el;
    await new Promise((r) => setTimeout(r, 100));
  }
  return null;
}

function mark(code: string, rtl: boolean) {
  document.documentElement.setAttribute('data-gt', code);
  document.querySelectorAll<HTMLElement>('[data-gt-current]').forEach((el) => { el.textContent = code.split('-')[0].toUpperCase(); });
  document.querySelectorAll<HTMLElement>('[data-gt-lang]').forEach((b) => b.setAttribute('aria-current', String(b.dataset.gtLang === code)));
  document.documentElement.classList.toggle('gt-rtl', rtl);
}

/** translate the page into a Google language */
export async function translateTo(code: string, rtl = false) {
  setCookie(`/${pageLang()}/${code}`, 60 * 60 * 24 * 365);
  mark(code, rtl);
  await loadGoogle();
  const sel = await combo();
  if (sel && sel.value !== code) {
    sel.value = code;
    sel.dispatchEvent(new Event('change'));
  }
}

/** on every page: keep translating if the visitor chose a Google language before */
export function resumeTranslation(rtlCodes: string[]) {
  const to = currentTarget();
  if (!to) return;
  mark(to, rtlCodes.includes(to));
  loadGoogle().catch(() => { /* offline or blocked: the original page stays */ });
}
