Nessun oggetto della modifica
Nessun oggetto della modifica
Etichetta: Ripristino manuale
 
(9 versioni intermedie di uno stesso utente non sono mostrate)
Riga 1: Riga 1:
/* ======================= CommonTranslate.js ======================= */
/* ======================= CommonTranslate.js (versione con proxy, stesso flusso) ======================= */
console.log("🔄 Caricamento CommonTranslate.js...");
console.log("🔄 Caricamento CommonTranslate.js...");


Riga 8: Riga 8:
     window.CommonTranslateLoaded = true;
     window.CommonTranslateLoaded = true;


     // ✅ Imposta lingua di origine (fallback su HTML lang o en)
     // ✅ Lingua origine (fallback su html lang o en)
     window.linguaOrigine = document.documentElement.lang || "en";
     window.linguaOrigine = document.documentElement.lang || "en";


     // ✅ Imposta API key se non esiste
     // ❌ Niente API key nel browser
     if (!window.apiKey) {
     // ✅ Definisci solo il modello (verrà usato dal proxy; se vuoto userà il default server)
        window.apiKey = "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"; // <--- Inserisci la tua API Key qui
    window.openaiModel = window.openaiModel || "gpt-4o";
    }


     // ✅ Definizione modello OpenAI
     // ✅ Endpoint proxy sul server (cameriere)
     window.openaiModel = "gpt-4o-2024-05-13";
     window.OPENAI_PROXY_URL = "/dashboard/api/openai_project_gpt.php";


     console.log("✅ CommonTranslate.js caricato correttamente!");
     console.log("✅ CommonTranslate.js caricato correttamente (via proxy).");
}
}


/* ======================= Funzione principale ======================= */
/* ======================= Funzione principale ======================= */
async function traduciTesto() {
async function traduciTesto() {
   const area = document.getElementById("wpTextbox1");
   const area = document.getElementById("wpTextbox1");
  if (!area) { alert("❌ Editor non trovato."); return; }
   const start = area.selectionStart;
   const start = area.selectionStart;
   const end = area.selectionEnd;
   const end   = area.selectionEnd;
   const testoSelezionato = area.value.slice(start, end).trim();
   const testoSelezionato = area.value.slice(start, end).trim();
   const tutto = !testoSelezionato;
   const tutto = !testoSelezionato;
Riga 39: Riga 39:


   const testo = tutto ? area.value : testoSelezionato;
   const testo = tutto ? area.value : testoSelezionato;
  if (!testo.trim()) { alert("⚠️ Niente da tradurre."); return; }


   // ✅ STEP 1: Lingua
   // ✅ STEP 1: Lingua
Riga 51: Riga 52:
   }
   }


  // ✅ STEP 2: Segmentazione
  const blocchi = segmentaTesto(testo);
  console.log(`🧩 Segmentazione: ${blocchi.length} blocchi trovati`);


// ✅ STEP 2: Segmentazione
  if (tutto) {
const blocchi = segmentaTesto(testo);
    // 🔍 STEP 3: Analisi segmentazione + popup
console.log(`🧩 Segmentazione: ${blocchi.length} blocchi trovati`);
    const errori = analizzaErroriSegmentazione(blocchi);
 
    sostituisciTestoSegmentato(blocchi, errori);
if (tutto) {
    mostraPopupConferma(blocchi, errori, [linguaScelta], tutto);
  // 🔍 STEP 3: Analisi segmentazione + popup
    return; // ⛔️ blocco qui: la traduzione partirà dal popup
  const errori = analizzaErroriSegmentazione(blocchi);
  }
  sostituisciTestoSegmentato(blocchi, errori);
  mostraPopupConferma(blocchi, errori, [linguaScelta], tutto);
  return; // ⛔️ blocco qui: la traduzione partirà dal popup
}


   // ✅ STEP 3: Traduzione (passa il parametro `tutto`)
   // ✅ STEP 3: Traduzione (passa il parametro `tutto`)
Riga 72: Riga 72:
   } else {
   } else {
     const prima = area.value.slice(0, start);
     const prima = area.value.slice(0, start);
     const dopo = area.value.slice(end);
     const dopo = area.value.slice(end);
     area.value = prima + tradotto + dopo;
     area.value = prima + tradotto + dopo;
     area.selectionStart = start;
     area.selectionStart = start;
     area.selectionEnd = start + tradotto.length;
     area.selectionEnd   = start + tradotto.length;
   }
   }


Riga 84: Riga 84:
   console.log("✅ Traduzione completata e inserita correttamente.");
   console.log("✅ Traduzione completata e inserita correttamente.");
}
}


/* ======================= Funzioni di supporto ======================= */
/* ======================= Funzioni di supporto ======================= */
function ottieniTestoDaEditor() {
function ottieniTestoDaEditor() {
    const area = document.getElementById("wpTextbox1");
  const area = document.getElementById("wpTextbox1");
    return area ? area.value.trim() : null;
  return area ? area.value.trim() : null;
}
}


function ottieniTestoSelezionato() {
function ottieniTestoSelezionato() {
    const area = document.getElementById("wpTextbox1");
  const area = document.getElementById("wpTextbox1");
    if (!area) return null;
  if (!area) return null;
    return area.value.substring(area.selectionStart, area.selectionEnd).trim() || null;
  return area.value.substring(area.selectionStart, area.selectionEnd).trim() || null;
}
}


function segmentaTesto(testo, maxToken = 3000) {
function segmentaTesto(testo, maxToken = 3000) {
    console.log("📌 Segmentazione in corso con max", maxToken, "tokens...");
  console.log("📌 Segmentazione in corso con max", maxToken, "tokens...");
    const blocchi = testo.match(new RegExp(`.{1,${maxToken}}(?=\\s|$)`, "gs")) || [];
  const blocchi = testo.match(new RegExp(`.{1,${maxToken}}(?=\\s|$)`, "gs")) || [];
    return blocchi;
  return blocchi;
}
}


function analizzaErroriSegmentazione(blocchi) {
function analizzaErroriSegmentazione(blocchi) {
    let errori = [];
  let errori = [];
    blocchi.forEach((blocco, i) => {
  blocchi.forEach((blocco, i) => {
        let err = [];
    let err = [];
        const count = (s, c) => (s.match(new RegExp(`\\${c}`, 'g')) || []).length;
    const count = (s, c) => (s.match(new RegExp(`\\${c}`, 'g')) || []).length;
        const parentesi = [["[", "]"], ["{", "}"], ["<", ">"]];
    const parentesi = [["[", "]"], ["{", "}"], ["<", ">"]];
        parentesi.forEach(([open, close]) => {
    parentesi.forEach(([open, close]) => {
            let openCount = count(blocco, open);
      let openCount = count(blocco, open);
            let closeCount = count(blocco, close);
      let closeCount = count(blocco, close);
            if (openCount !== closeCount) {
      if (openCount !== closeCount) {
                err.push(`Parentesi ${open}${close} non bilanciate: ${openCount} ${open}, ${closeCount} ${close}`);
        err.push(`Parentesi ${open}${close} non bilanciate: ${openCount} ${open}, ${closeCount} ${close}`);
            }
      }
        });
        if (err.length > 0) {
            errori.push({ index: i + 1, dettagli: err });
        }
     });
     });
     return errori;
     if (err.length > 0) {
      errori.push({ index: i + 1, dettagli: err });
    }
  });
  return errori;
}
}


function sostituisciTestoSegmentato(blocchi, errori) {
function sostituisciTestoSegmentato(blocchi, errori) {
    const area = document.getElementById("wpTextbox1");
  const area = document.getElementById("wpTextbox1");
    if (!area) {
  if (!area) {
        console.warn("⚠️ Campo wpTextbox1 non trovato per sostituzione.");
    console.warn("⚠️ Campo wpTextbox1 non trovato per sostituzione.");
        return;
    return;
    }
  }
    const blocchiSegnalati = blocchi.map((b, i) => {
  const blocchiSegnalati = blocchi.map((b, i) => {
        const err = errori.find(e => e.index === i + 1);
    const err = errori.find(e => e.index === i + 1);
        const erroreText = err ? `⚠️ ERRORI:\n- ${err.dettagli.join("\n- ")}\n\n` : "";
    const erroreText = err ? `⚠️ ERRORI:\n- ${err.dettagli.join("\n- ")}\n\n` : "";
        return `${erroreText}🔹 BLOCCO ${i + 1}\n` + b;
    return `${erroreText}🔹 BLOCCO ${i + 1}\n` + b;
    });
  });
    area.value = blocchiSegnalati.join("\n\n==============================\n\n");
  area.value = blocchiSegnalati.join("\n\n==============================\n\n");
    console.log("✍️ Testo segmentato sostituito nel campo wpTextbox1");
  console.log("✍️ Testo segmentato sostituito nel campo wpTextbox1");
}
}


function mostraPopupConferma(blocchi, errori, lingueDaTradurre, tutto) {
function mostraPopupConferma(blocchi, errori, lingueDaTradurre, tutto) {
    const popup = document.createElement("div");
  const popup = document.createElement("div");
    popup.id = "popup-conferma-traduzione";
  popup.id = "popup-conferma-traduzione";
    popup.style = `
  popup.style = `
        position: fixed; bottom: 20px; right: 20px;
    position: fixed; bottom: 20px; right: 20px;
        background: white; padding: 15px; border: 2px solid #444;
    background: white; padding: 15px; border: 2px solid #444;
        box-shadow: 4px 4px 10px rgba(0,0,0,0.3); z-index: 9999;
    box-shadow: 4px 4px 10px rgba(0,0,0,0.3); z-index: 9999;
        resize: both; overflow: auto; cursor: move;
    resize: both; overflow: auto; cursor: move;
    `;
  `;
    popup.innerHTML = `
  popup.innerHTML = `
        <b>✅ Segmentazione completata</b><br>
    <b>✅ Segmentazione completata</b><br>
        🧠 Token stimati: ~${blocchi.length * 3000}<br>
    🧠 Token stimati: ~${blocchi.length * 3000}<br>
        💰 Costo approssimativo: ~$${(blocchi.length * 3000 * 0.00002).toFixed(2)}<br>
    💰 Costo approssimativo: ~$${(blocchi.length * 3000 * 0.00002).toFixed(2)}<br>
        ${errori.length > 0 ? `❗ <span style='color:red;'>${errori.length} errori rilevati. Procedere comunque?</span><br>` : `<span style='color:green;'>✅ Nessun errore rilevato</span><br>`}
    ${errori.length > 0 ? `❗ <span style='color:red;'>${errori.length} errori rilevati. Procedere comunque?</span><br>` : `<span style='color:green;'>✅ Nessun errore rilevato</span><br>`}
        <button id="btn-invia-traduzione">✅ Invia</button>
    <button id="btn-invia-traduzione">✅ Invia</button>
        <button onclick="this.parentNode.remove()">❌ Annulla</button>
    <button onclick="this.parentNode.remove()">❌ Annulla</button>
    `;
  `;
    document.body.appendChild(popup);
  document.body.appendChild(popup);


    dragElement(popup);
  dragElement(popup);


    document.getElementById("btn-invia-traduzione").onclick = () => {
  document.getElementById("btn-invia-traduzione").onclick = async () => {
        popup.remove();
    popup.remove();
        alert("Preparazione invio a OpenAI... (non ancora attivo)");
    console.log("📤 Invio confermato: avvio traduzione…");
        inviaTraduzione(blocchi, lingueDaTradurre[0]);
    try {
     };
      await inviaTraduzione(blocchi, lingueDaTradurre[0], tutto);
    } catch (e) {
      console.error("❌ Errore nell'invio della traduzione:", e);
      alert("Errore durante l'invio a OpenAI (via proxy):\n" + e.message);
     }
  };
}
}


function dragElement(elmnt) {
function dragElement(elmnt) {
    let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    elmnt.onmousedown = dragMouseDown;
  elmnt.onmousedown = dragMouseDown;
    function dragMouseDown(e) {
  function dragMouseDown(e) {
        e = e || window.event;
    e = e || window.event; e.preventDefault();
        e.preventDefault();
    pos3 = e.clientX; pos4 = e.clientY;
        pos3 = e.clientX;
    document.onmouseup = closeDragElement;
        pos4 = e.clientY;
    document.onmousemove = elementDrag;
        document.onmouseup = closeDragElement;
  }
        document.onmousemove = elementDrag;
  function elementDrag(e) {
    }
    e = e || window.event; e.preventDefault();
    function elementDrag(e) {
    pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY;
        e = e || window.event;
    pos3 = e.clientX; pos4 = e.clientY;
        e.preventDefault();
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        pos1 = pos3 - e.clientX;
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
        pos2 = pos4 - e.clientY;
  }
        pos3 = e.clientX;
  function closeDragElement() {
        pos4 = e.clientY;
    document.onmouseup = null;
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    document.onmousemove = null;
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }
    }
    function closeDragElement() {
        document.onmouseup = null;
        document.onmousemove = null;
    }
}
}
// ✅ Traduzione parziale o totale
 
/* ======================= Invio traduzione (usa il CAMERIERE) ======================= */
async function inviaTraduzione(blocchi, lingua, tutto = true) {
async function inviaTraduzione(blocchi, lingua, tutto = true) {
   const model = window.openaiModel || "gpt-4o-2024-05-13";
   const model = window.openaiModel || "gpt-4o";
   let testoTradotto = "";
   let testoTradotto = "";


   console.log("🧪 Avvio inviaTraduzione()");
   console.log("🧪 Avvio inviaTraduzione() via proxy");
   console.log("📦 Blocchi ricevuti:", blocchi);
   console.log("📦 Blocchi ricevuti:", blocchi.length, "| 🌍 Lingua:", lingua);
  console.log("🌍 Lingua richiesta:", lingua);


   for (let i = 0; i < blocchi.length; i++) {
   for (let i = 0; i < blocchi.length; i++) {
     console.log(`🚀 Invio blocco ${i + 1}/${blocchi.length}...`);
     console.log(`🚀 Invio blocco ${i + 1}/${blocchi.length}`);
     let tradotto = await traduciBlocco(blocchi[i], lingua);
     let tradotto = await traduciBloccoProxy(blocchi[i], lingua, model);
     testoTradotto += tradotto + "\n\n";
     testoTradotto += (tradotto || "[Errore Traduzione]") + "\n\n";
   }
   }


   const area = document.getElementById("wpTextbox1");
   const area = document.getElementById("wpTextbox1");
   if (!area) {
   if (!area) { console.warn("❌ Campo wpTextbox1 non trovato!"); return ""; }
    console.warn("❌ Campo wpTextbox1 non trovato!");
    return;
  }


   const start = area.selectionStart;
   const start = area.selectionStart;
   const end = area.selectionEnd;
   const end   = area.selectionEnd;


   if (tutto) {
   if (tutto) {
Riga 221: Riga 217:
   } else {
   } else {
     const prima = area.value.slice(0, start);
     const prima = area.value.slice(0, start);
     const dopo = area.value.slice(end);
     const dopo = area.value.slice(end);
     area.value = prima + testoTradotto.trim() + dopo;
     area.value = prima + testoTradotto.trim() + dopo;
     area.selectionStart = start;
     area.selectionStart = start;
     area.selectionEnd = start + testoTradotto.trim().length;
     area.selectionEnd   = start + testoTradotto.trim().length;
   }
   }


Riga 234: Riga 230:
}
}


/* ======================= Traduzione BLOCCO → via proxy ======================= */
async function traduciBloccoProxy(blocco, lingua, model) {
  try {
    const istruzioni = [
      "You are a professional MediaWiki translator.",
      "Translate the text preserving templates, links, headings, lists and any wiki syntax.",
      "Do not add comments or explanations.",
      `Source language: ${window.linguaOrigine}. Target language: ${lingua}.`
    ].join(" ");


    const prompt = `${istruzioni}\n\n--- TEXT START ---\n${blocco}\n--- TEXT END ---`;


// ✅  Traduzione  blocco
     const res = await fetch(window.OPENAI_PROXY_URL, {
async function traduciBlocco(blocco, lingua) {
      method: "POST",
     try {
      headers: { "Content-Type": "application/json" },
        let response = await fetch("https://api.openai.com/v1/chat/completions", {
      body: JSON.stringify({ prompt, model })
            method: "POST",
    });
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${window.apiKey}`
            },
            body: JSON.stringify({
                model: window.openaiModel,
                messages: [
                    { role: "system", content: "You are a professional MediaWiki translator. Preserve all formatting, templates, and syntax." },
                    { role: "user", content: `Translate this text into ${lingua}:\n\n` + blocco }
                ],
                temperature: 0
            })
        });


        let data = await response.json();
    const data = await res.json().catch(() => ({}));
        if (!response.ok) {
    if (!res.ok || data.status === "error") {
            throw new Error(data.error?.message || "Errore API generico");
      const msg = data?.error || `HTTP ${res.status}`;
        }
      console.error("❌ Errore da proxy:", msg);
        return data.choices[0].message.content;
      return "[Errore Traduzione]";
    } catch (error) {
        console.error("❌ Errore durante traduzione:", error);
        return "[Errore Traduzione]";
     }
     }
    return data.result || "";
  } catch (err) {
    console.error("❌ Errore durante traduzione (proxy):", err);
    return "[Errore Traduzione]";
  }
}
}


// ✅ Aggiungi pulsante per avviare
/* ======================= Pulsante sotto editor ======================= */
$(function () {
$(function () {
    $("#wpTextbox1").after('<button id="pulsanteTraduci" class="btn">🧠 Traduci contenuto</button>');
  if (!document.getElementById("wpTextbox1")) return;
    $("#pulsanteTraduci").on("click", traduciTesto);
  if (document.getElementById("pulsanteTraduci")) return;
 
  $("#wpTextbox1").after('<button id="pulsanteTraduci" class="btn">🧠 Traduci contenuto</button>');
  $("#pulsanteTraduci").on("click", traduciTesto);
});
});

Versione attuale delle 11:54, 6 dic 2025

/* ======================= CommonTranslate.js (versione con proxy, stesso flusso) ======================= */
console.log("🔄 Caricamento CommonTranslate.js...");

// ✅ Evita ricaricamento multiplo
if (window.CommonTranslateLoaded) {
    console.warn("⚠️ CommonTranslate.js è già stato caricato.");
} else {
    window.CommonTranslateLoaded = true;

    // ✅ Lingua origine (fallback su html lang o en)
    window.linguaOrigine = document.documentElement.lang || "en";

    // ❌ Niente API key nel browser
    // ✅ Definisci solo il modello (verrà usato dal proxy; se vuoto userà il default server)
    window.openaiModel = window.openaiModel || "gpt-4o";

    // ✅ Endpoint proxy sul server (cameriere)
    window.OPENAI_PROXY_URL = "/dashboard/api/openai_project_gpt.php";

    console.log("✅ CommonTranslate.js caricato correttamente (via proxy).");
}

/* ======================= Funzione principale ======================= */
async function traduciTesto() {
  const area = document.getElementById("wpTextbox1");
  if (!area) { alert("❌ Editor non trovato."); return; }

  const start = area.selectionStart;
  const end   = area.selectionEnd;
  const testoSelezionato = area.value.slice(start, end).trim();
  const tutto = !testoSelezionato;

  // ✅ Chiedi cosa tradurre
  const conferma = confirm("📝 Vuoi tradurre SOLO il testo selezionato?\n\n✅ OK = solo selezione\n❌ Annulla = tutto il testo");
  if (conferma && !testoSelezionato) {
    alert("⚠️ Nessuna parte selezionata. Se vuoi tradurre tutto, premi Annulla.");
    return;
  }

  const testo = tutto ? area.value : testoSelezionato;
  if (!testo.trim()) { alert("⚠️ Niente da tradurre."); return; }

  // ✅ STEP 1: Lingua
  const lingueDisponibili = ["it", "en", "fr", "es", "de"];
  let linguaScelta = prompt(
    "🌍 Scegli la lingua di traduzione:\n\nit = Italiano\nen = Inglese\nfr = Francese\nes = Spagnolo\nde = Tedesco",
    "it"
  );
  if (!linguaScelta) {
    console.warn("⚠️ Nessuna lingua selezionata.");
    return;
  }

  // ✅ STEP 2: Segmentazione
  const blocchi = segmentaTesto(testo);
  console.log(`🧩 Segmentazione: ${blocchi.length} blocchi trovati`);

  if (tutto) {
    // 🔍 STEP 3: Analisi segmentazione + popup
    const errori = analizzaErroriSegmentazione(blocchi);
    sostituisciTestoSegmentato(blocchi, errori);
    mostraPopupConferma(blocchi, errori, [linguaScelta], tutto);
    return; // ⛔️ blocco qui: la traduzione partirà dal popup
  }

  // ✅ STEP 3: Traduzione (passa il parametro `tutto`)
  const tradotto = await inviaTraduzione(blocchi, linguaScelta, tutto);

  // ✅ STEP 4: Inserimento nel campo editor
  if (tutto) {
    area.value = tradotto;
  } else {
    const prima = area.value.slice(0, start);
    const dopo  = area.value.slice(end);
    area.value = prima + tradotto + dopo;
    area.selectionStart = start;
    area.selectionEnd   = start + tradotto.length;
  }

  // ✅ STEP 5: Notifica
  area.dispatchEvent(new Event("input", { bubbles: true }));
  area.dispatchEvent(new Event("change", { bubbles: true }));

  console.log("✅ Traduzione completata e inserita correttamente.");
}

/* ======================= Funzioni di supporto ======================= */
function ottieniTestoDaEditor() {
  const area = document.getElementById("wpTextbox1");
  return area ? area.value.trim() : null;
}

function ottieniTestoSelezionato() {
  const area = document.getElementById("wpTextbox1");
  if (!area) return null;
  return area.value.substring(area.selectionStart, area.selectionEnd).trim() || null;
}

function segmentaTesto(testo, maxToken = 3000) {
  console.log("📌 Segmentazione in corso con max", maxToken, "tokens...");
  const blocchi = testo.match(new RegExp(`.{1,${maxToken}}(?=\\s|$)`, "gs")) || [];
  return blocchi;
}

function analizzaErroriSegmentazione(blocchi) {
  let errori = [];
  blocchi.forEach((blocco, i) => {
    let err = [];
    const count = (s, c) => (s.match(new RegExp(`\\${c}`, 'g')) || []).length;
    const parentesi = [["[", "]"], ["{", "}"], ["<", ">"]];
    parentesi.forEach(([open, close]) => {
      let openCount = count(blocco, open);
      let closeCount = count(blocco, close);
      if (openCount !== closeCount) {
        err.push(`Parentesi ${open}${close} non bilanciate: ${openCount} ${open}, ${closeCount} ${close}`);
      }
    });
    if (err.length > 0) {
      errori.push({ index: i + 1, dettagli: err });
    }
  });
  return errori;
}

function sostituisciTestoSegmentato(blocchi, errori) {
  const area = document.getElementById("wpTextbox1");
  if (!area) {
    console.warn("⚠️ Campo wpTextbox1 non trovato per sostituzione.");
    return;
  }
  const blocchiSegnalati = blocchi.map((b, i) => {
    const err = errori.find(e => e.index === i + 1);
    const erroreText = err ? `⚠️ ERRORI:\n- ${err.dettagli.join("\n- ")}\n\n` : "";
    return `${erroreText}🔹 BLOCCO ${i + 1}\n` + b;
  });
  area.value = blocchiSegnalati.join("\n\n==============================\n\n");
  console.log("✍️ Testo segmentato sostituito nel campo wpTextbox1");
}

function mostraPopupConferma(blocchi, errori, lingueDaTradurre, tutto) {
  const popup = document.createElement("div");
  popup.id = "popup-conferma-traduzione";
  popup.style = `
    position: fixed; bottom: 20px; right: 20px;
    background: white; padding: 15px; border: 2px solid #444;
    box-shadow: 4px 4px 10px rgba(0,0,0,0.3); z-index: 9999;
    resize: both; overflow: auto; cursor: move;
  `;
  popup.innerHTML = `
    <b>✅ Segmentazione completata</b><br>
    🧠 Token stimati: ~${blocchi.length * 3000}<br>
    💰 Costo approssimativo: ~$${(blocchi.length * 3000 * 0.00002).toFixed(2)}<br>
    ${errori.length > 0 ? `❗ <span style='color:red;'>${errori.length} errori rilevati. Procedere comunque?</span><br>` : `<span style='color:green;'>✅ Nessun errore rilevato</span><br>`}
    <button id="btn-invia-traduzione">✅ Invia</button>
    <button onclick="this.parentNode.remove()">❌ Annulla</button>
  `;
  document.body.appendChild(popup);

  dragElement(popup);

  document.getElementById("btn-invia-traduzione").onclick = async () => {
    popup.remove();
    console.log("📤 Invio confermato: avvio traduzione…");
    try {
      await inviaTraduzione(blocchi, lingueDaTradurre[0], tutto);
    } catch (e) {
      console.error("❌ Errore nell'invio della traduzione:", e);
      alert("Errore durante l'invio a OpenAI (via proxy):\n" + e.message);
    }
  };
}

function dragElement(elmnt) {
  let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  elmnt.onmousedown = dragMouseDown;
  function dragMouseDown(e) {
    e = e || window.event; e.preventDefault();
    pos3 = e.clientX; pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }
  function elementDrag(e) {
    e = e || window.event; e.preventDefault();
    pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY;
    pos3 = e.clientX; pos4 = e.clientY;
    elmnt.style.top  = (elmnt.offsetTop  - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }
  function closeDragElement() {
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

/* ======================= Invio traduzione (usa il CAMERIERE) ======================= */
async function inviaTraduzione(blocchi, lingua, tutto = true) {
  const model = window.openaiModel || "gpt-4o";
  let testoTradotto = "";

  console.log("🧪 Avvio inviaTraduzione() via proxy");
  console.log("📦 Blocchi ricevuti:", blocchi.length, "| 🌍 Lingua:", lingua);

  for (let i = 0; i < blocchi.length; i++) {
    console.log(`🚀 Invio blocco ${i + 1}/${blocchi.length}…`);
    let tradotto = await traduciBloccoProxy(blocchi[i], lingua, model);
    testoTradotto += (tradotto || "[Errore Traduzione]") + "\n\n";
  }

  const area = document.getElementById("wpTextbox1");
  if (!area) { console.warn("❌ Campo wpTextbox1 non trovato!"); return ""; }

  const start = area.selectionStart;
  const end   = area.selectionEnd;

  if (tutto) {
    area.value = testoTradotto.trim();
  } else {
    const prima = area.value.slice(0, start);
    const dopo  = area.value.slice(end);
    area.value = prima + testoTradotto.trim() + dopo;
    area.selectionStart = start;
    area.selectionEnd   = start + testoTradotto.trim().length;
  }

  area.dispatchEvent(new Event("input", { bubbles: true }));
  area.dispatchEvent(new Event("change", { bubbles: true }));

  console.log("✅ Traduzione completata.");
  return testoTradotto.trim();
}

/* ======================= Traduzione BLOCCO → via proxy ======================= */
async function traduciBloccoProxy(blocco, lingua, model) {
  try {
    const istruzioni = [
      "You are a professional MediaWiki translator.",
      "Translate the text preserving templates, links, headings, lists and any wiki syntax.",
      "Do not add comments or explanations.",
      `Source language: ${window.linguaOrigine}. Target language: ${lingua}.`
    ].join(" ");

    const prompt = `${istruzioni}\n\n--- TEXT START ---\n${blocco}\n--- TEXT END ---`;

    const res = await fetch(window.OPENAI_PROXY_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ prompt, model })
    });

    const data = await res.json().catch(() => ({}));
    if (!res.ok || data.status === "error") {
      const msg = data?.error || `HTTP ${res.status}`;
      console.error("❌ Errore da proxy:", msg);
      return "[Errore Traduzione]";
    }
    return data.result || "";
  } catch (err) {
    console.error("❌ Errore durante traduzione (proxy):", err);
    return "[Errore Traduzione]";
  }
}

/* ======================= Pulsante sotto editor ======================= */
$(function () {
  if (!document.getElementById("wpTextbox1")) return;
  if (document.getElementById("pulsanteTraduci")) return;

  $("#wpTextbox1").after('<button id="pulsanteTraduci" class="btn">🧠 Traduci contenuto</button>');
  $("#pulsanteTraduci").on("click", traduciTesto);
});