/*
|--------------------------------------------------------------------------
| Runtime page translation (Google Cloud Translation, via /api/translate)
|--------------------------------------------------------------------------
|
| There are no message files. When the UI language isn't English, this
| engine walks the live DOM, sends the English text it finds to
| /api/translate (which holds the API key), and swaps the answers in.
| A MutationObserver keeps doing that for everything React renders later
| (route changes, polling, modals), and switching back to English
| restores the original text exactly.
|
| What it touches: visible text nodes plus the placeholder / title / alt /
| aria-label attributes (and the value of submit/button inputs).
|
| What it never touches:
|   - anything inside an element with translate="no" or class "notranslate"
|     (user-written chat messages, names the user typed, etc.)
|   - script/style/code/pre/textarea contents
|   - strings that are already Devanagari, or have no letters at all
|     (prices, numbers, times, symbols), or look like an email / URL
|
| Translations are cached in memory and localStorage, so a string is
| only ever fetched once per browser.
|
*/

type Target = "hi";

const SKIP_TAGS = new Set([
  "SCRIPT",
  "STYLE",
  "NOSCRIPT",
  "CODE",
  "PRE",
  "TEXTAREA",
  "SVG",
  "CANVAS",
  "IFRAME",
  "TEMPLATE",
]);

const TRANSLATABLE_ATTRS = ["placeholder", "title", "alt", "aria-label"];
const NO_TRANSLATE_SELECTOR = '[translate="no"], .notranslate';

const BATCH_MAX_TEXTS = 80;
const BATCH_MAX_CHARS = 9000;
const CACHE_STORAGE_PREFIX = "astro_tr_v1_";
const CACHE_MAX_ENTRIES = 6000;
const RETRY_AFTER_MS = 30000;

const DEVANAGARI = /[ऀ-ॿ]/;
const HAS_LATIN_LETTER = /[A-Za-z]/;
const LOOKS_LIKE_EMAIL_OR_URL = /^(https?:\/\/|www\.)\S+$|^[\w.+-]+@[\w-]+(\.[\w-]+)+$/i;

// Whole-string overrides for terms generic machine translation gets wrong
// (confirmed live: it leaves "TAURUS" untouched and transliterates
// "ARIES"/"CANCER"/"LEO" phonetically instead of using the rashi names),
// plus the brand, which stays Latin. Matched case-insensitively against
// the entire text of a node.
const GLOSSARY: Record<string, string> = {
  aries: "मेष",
  taurus: "वृषभ",
  gemini: "मिथुन",
  cancer: "कर्क",
  leo: "सिंह",
  virgo: "कन्या",
  libra: "तुला",
  scorpio: "वृश्चिक",
  sagittarius: "धनु",
  capricorn: "मकर",
  aquarius: "कुंभ",
  pisces: "मीन",
  astroeye: "AstroEye",
  // Short UI words machine translation reads as the wrong part of speech
  // out of context (confirmed live: "Call" -> "पुकारना", i.e. "to shout").
  chat: "चैट",
  call: "कॉल",
  "chat now": "अभी चैट करें",
  "call now": "अभी कॉल करें",
  video: "वीडियो",
  online: "ऑनलाइन",
  offline: "ऑफ़लाइन",
  busy: "व्यस्त",
  home: "होम",
  wallet: "वॉलेट",
  orders: "ऑर्डर",
  kundli: "कुंडली",
  panchang: "पंचांग",
  horoscope: "राशिफल",
  tarot: "टैरो",
  consultation: "परामर्श",
  consultations: "परामर्श",
};

// "10M+", "5K", "1,200+" — a figure with an optional unit letter.
const FIGURE_WITH_UNIT = /^[\d.,]+\s?[kmbKMB]?\+?$|^[\d.,]+\s?[kmbKMB]?\+?\s*[★⭐%]$/;

function isTranslatable(core: string): boolean {
  if (FIGURE_WITH_UNIT.test(core)) return false;

  return (
    core.length > 0 &&
    core.length <= 1500 &&
    HAS_LATIN_LETTER.test(core) &&
    !DEVANAGARI.test(core) &&
    !LOOKS_LIKE_EMAIL_OR_URL.test(core)
  );
}

function splitWhitespace(value: string) {
  const lead = value.match(/^\s*/)?.[0] ?? "";
  const trail = value.length > lead.length ? (value.match(/\s*$/)?.[0] ?? "") : "";
  const core = value.slice(lead.length, value.length - trail.length);
  return { lead, core, trail };
}

function isExcluded(el: Element | null): boolean {
  if (!el) return true;
  if (SKIP_TAGS.has(el.tagName.toUpperCase())) return true;
  return !!el.closest(NO_TRANSLATE_SELECTOR);
}

interface PendingText {
  kind: "text";
  node: Text;
  original: string;
  lead: string;
  core: string;
  trail: string;
}

interface PendingAttr {
  kind: "attr";
  el: Element;
  attr: string;
  original: string;
  lead: string;
  core: string;
  trail: string;
}

type Pending = PendingText | PendingAttr;

export class AutoTranslator {
  private target: Target;
  private cache = new Map<string, string>();
  private failedUntil = new Map<string, number>();
  private inflight = new Set<string>();

  // English original of every node we've translated, and exactly what we wrote.
  private textOriginal = new WeakMap<Text, string>();
  private textApplied = new WeakMap<Text, string>();
  private attrOriginal = new WeakMap<Element, Map<string, string>>();
  private attrApplied = new WeakMap<Element, Map<string, string>>();

  private observer: MutationObserver | null = null;
  private dirtyRoots = new Set<Node>();
  private flushTimer: ReturnType<typeof setTimeout> | null = null;
  private saveTimer: ReturnType<typeof setTimeout> | null = null;
  private running = false;

  constructor(target: Target) {
    this.target = target;
    this.loadCache();
  }

  // ---- lifecycle ---------------------------------------------------------

  start() {
    if (this.running || typeof document === "undefined") return;
    this.running = true;

    this.markDirty(document.documentElement);

    this.observer = new MutationObserver((mutations) => {
      for (const m of mutations) {
        if (m.type === "characterData") {
          this.markDirty(m.target);
        } else if (m.type === "attributes") {
          this.markDirty(m.target);
        } else {
          m.addedNodes.forEach((n) => this.markDirty(n));
        }
      }
    });

    this.observer.observe(document.documentElement, {
      subtree: true,
      childList: true,
      characterData: true,
      attributes: true,
      attributeFilter: [...TRANSLATABLE_ATTRS, "value"],
    });
  }

  // Stops translating and puts every English original back.
  stop() {
    if (!this.running) return;
    this.running = false;

    this.observer?.disconnect();
    this.observer = null;
    this.dirtyRoots.clear();
    if (this.flushTimer) clearTimeout(this.flushTimer);
    this.flushTimer = null;

    this.restore(document.documentElement);
  }

  // ---- scheduling ----------------------------------------------------------

  private markDirty(node: Node) {
    this.dirtyRoots.add(node);

    if (this.flushTimer) return;

    this.flushTimer = setTimeout(() => {
      this.flushTimer = null;
      const roots = Array.from(this.dirtyRoots);
      this.dirtyRoots.clear();
      this.process(roots);
    }, 150);
  }

  // ---- collecting ------------------------------------------------------------

  private collectFrom(root: Node, out: Pending[]) {
    if (root.nodeType === Node.TEXT_NODE) {
      this.collectText(root as Text, out);
      return;
    }

    if (root.nodeType !== Node.ELEMENT_NODE) return;

    const rootEl = root as Element;
    if (isExcluded(rootEl)) return;

    this.collectAttrs(rootEl, out);

    const walker = document.createTreeWalker(rootEl, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
      acceptNode: (n) => {
        if (n.nodeType === Node.ELEMENT_NODE) {
          return isExcluded(n as Element) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_SKIP;
        }
        return NodeFilter.FILTER_ACCEPT;
      },
    });

    // FILTER_SKIP on elements would hide their attributes from us, so
    // collect those separately.
    rootEl.querySelectorAll("*").forEach((el) => {
      if (!isExcluded(el)) this.collectAttrs(el, out);
    });

    let n: Node | null = walker.nextNode();
    while (n) {
      this.collectText(n as Text, out);
      n = walker.nextNode();
    }
  }

  private collectText(node: Text, out: Pending[]) {
    const value = node.nodeValue ?? "";
    if (!value.trim()) return;

    // Already translated by us and unchanged since.
    if (this.textApplied.get(node) === value) return;

    if (isExcluded(node.parentElement)) return;

    const { lead, core, trail } = splitWhitespace(value);
    if (!isTranslatable(core)) return;

    out.push({ kind: "text", node, original: value, lead, core, trail });
  }

  private collectAttrs(el: Element, out: Pending[]) {
    const attrs = [...TRANSLATABLE_ATTRS];

    if (el.tagName === "INPUT") {
      const type = (el.getAttribute("type") || "").toLowerCase();
      if (type === "submit" || type === "button" || type === "reset") attrs.push("value");
    }

    for (const attr of attrs) {
      const value = el.getAttribute(attr);
      if (!value || !value.trim()) continue;

      if (this.attrApplied.get(el)?.get(attr) === value) continue;

      const { lead, core, trail } = splitWhitespace(value);
      if (!isTranslatable(core)) continue;

      out.push({ kind: "attr", el, attr, original: value, lead, core, trail });
    }
  }

  // ---- translating --------------------------------------------------------------

  private async process(roots: Node[]) {
    if (!this.running) return;

    const pending: Pending[] = [];
    const seen = new Set<Node>();

    for (const root of roots) {
      if (!root.isConnected || seen.has(root)) continue;
      seen.add(root);
      this.collectFrom(root, pending);
    }

    if (pending.length === 0) return;

    // Cached strings apply immediately; the rest are fetched.
    const missing = new Set<string>();

    for (const item of pending) {
      const hit = GLOSSARY[item.core.toLowerCase()] ?? this.cache.get(item.core);
      if (hit !== undefined) this.apply(item, hit);
      else if (!this.isBackedOff(item.core)) missing.add(item.core);
    }

    if (missing.size === 0) return;

    await this.fetchAndApply(Array.from(missing), pending);
  }

  private isBackedOff(core: string) {
    const until = this.failedUntil.get(core);
    return until !== undefined && until > Date.now();
  }

  private async fetchAndApply(strings: string[], pending: Pending[]) {
    const fresh = strings.filter((s) => !this.inflight.has(s));
    fresh.forEach((s) => this.inflight.add(s));

    const batches: string[][] = [];
    let current: string[] = [];
    let chars = 0;

    for (const s of fresh) {
      if (current.length >= BATCH_MAX_TEXTS || chars + s.length > BATCH_MAX_CHARS) {
        batches.push(current);
        current = [];
        chars = 0;
      }
      current.push(s);
      chars += s.length;
    }
    if (current.length) batches.push(current);

    for (const batch of batches) {
      try {
        const response = await fetch("/api/translate", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ texts: batch, target: this.target }),
        });

        if (!response.ok) throw new Error(`translate ${response.status}`);

        const data = await response.json();
        const translations: string[] = data?.translations ?? [];

        batch.forEach((source, i) => {
          if (translations[i]) this.remember(source, translations[i]);
          else this.failedUntil.set(source, Date.now() + RETRY_AFTER_MS);
        });
      } catch {
        // Leave the English on screen; try again later, not in a tight loop.
        batch.forEach((source) => this.failedUntil.set(source, Date.now() + RETRY_AFTER_MS));
      } finally {
        batch.forEach((s) => this.inflight.delete(s));
      }

      if (!this.running) return;

      for (const item of pending) {
        const hit = this.cache.get(item.core);
        if (hit !== undefined) this.apply(item, hit);
      }
    }

    // Anything we backed off on is retried on a later mutation or after a delay.
    const retry = fresh.filter((s) => !this.cache.has(s));
    if (retry.length) {
      setTimeout(() => {
        if (this.running) this.markDirty(document.documentElement);
      }, RETRY_AFTER_MS + 500);
    }
  }

  // ---- applying -------------------------------------------------------------------

  private apply(item: Pending, translated: string) {
    if (!this.running) return;

    const next = item.lead + translated + item.trail;

    if (item.kind === "text") {
      // React may have changed or removed the node while we waited.
      if (!item.node.isConnected || item.node.nodeValue !== item.original) return;

      if (!this.textOriginal.has(item.node) || this.textApplied.get(item.node) !== item.original) {
        this.textOriginal.set(item.node, item.original);
      }
      this.textApplied.set(item.node, next);
      item.node.nodeValue = next;
      return;
    }

    if (!item.el.isConnected || item.el.getAttribute(item.attr) !== item.original) return;

    let originals = this.attrOriginal.get(item.el);
    if (!originals) this.attrOriginal.set(item.el, (originals = new Map()));
    originals.set(item.attr, item.original);

    let applied = this.attrApplied.get(item.el);
    if (!applied) this.attrApplied.set(item.el, (applied = new Map()));
    applied.set(item.attr, next);

    item.el.setAttribute(item.attr, next);
  }

  // ---- restoring English ------------------------------------------------------------

  private restore(root: Element) {
    const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
    let n: Node | null = walker.nextNode();

    while (n) {
      const text = n as Text;
      const original = this.textOriginal.get(text);

      if (original !== undefined && this.textApplied.get(text) === text.nodeValue) {
        text.nodeValue = original;
      }

      this.textOriginal.delete(text);
      this.textApplied.delete(text);

      n = walker.nextNode();
    }

    root.querySelectorAll("*").forEach((el) => {
      const originals = this.attrOriginal.get(el);
      const applied = this.attrApplied.get(el);

      if (originals && applied) {
        originals.forEach((original, attr) => {
          if (el.getAttribute(attr) === applied.get(attr)) el.setAttribute(attr, original);
        });
      }

      this.attrOriginal.delete(el);
      this.attrApplied.delete(el);
    });
  }

  // ---- cache --------------------------------------------------------------------------

  private remember(source: string, translated: string) {
    if (this.cache.size >= CACHE_MAX_ENTRIES) {
      this.cache.delete(this.cache.keys().next().value as string);
    }
    this.cache.set(source, translated);
    this.scheduleSave();
  }

  private storageKey() {
    return `${CACHE_STORAGE_PREFIX}${this.target}`;
  }

  private loadCache() {
    try {
      const raw = localStorage.getItem(this.storageKey());
      if (!raw) return;
      const entries: [string, string][] = JSON.parse(raw);
      entries.forEach(([k, v]) => this.cache.set(k, v));
    } catch {
      // A corrupt/unavailable cache just means we refetch.
    }
  }

  private scheduleSave() {
    if (this.saveTimer) return;

    this.saveTimer = setTimeout(() => {
      this.saveTimer = null;
      try {
        localStorage.setItem(this.storageKey(), JSON.stringify(Array.from(this.cache.entries())));
      } catch {
        // Quota or private mode — the in-memory cache still works.
      }
    }, 1000);
  }
}
