Nessun oggetto della modifica
Etichetta: Annullato
Nessun oggetto della modifica
Etichetta: Annullato
Riga 384: Riga 384:
   });
   });
})();
})();


// === ChatGPT plus esteso (UI + Salva + Explorer) ===
// === ChatGPT plus esteso (UI + Salva + Explorer) ===
(function(){
  const $ = s => document.querySelector(s);
  const panel = $('#chatgpt-plus');
  if (!panel) return;


  const projectSel = $('#mpChatProject');
  const modeSel    = $('#mpChatMode');
  const fileInput  = $('#mpChatFile');
  const drop      = $('#mpChatDrop');
  const filesBox  = $('#mpChatFiles');
  const promptEl  = $('#mpChatPrompt');
  const sendBtn    = $('#mpChatSend');
  const ansBox    = $('#mpChatAnswer');
  const clearBtn  = $('#mpChatClear');
  const copyBtn    = $('#mpChatCopy');
  const saveBtn    = $('#mpChatSave');


   // Explorer
mw.loader.using([], function () {
   const refreshBtn = $('#mpChatRefresh');
   // Esegui solo sulla Dashboard
  const savedList  = $('#mpSavedList');
   if (mw.config.get('wgPageName') !== 'Dashboard_Masticationpedia') return;


   let attached = [];
   console.log('[CommonDashboard.js] caricato'); // segnale in console


   function renderFiles(){
   (function(){
     filesBox.innerHTML = attached.map(n =>
     const $ = s => document.querySelector(s);
      `<span style="border:1px solid #eee; border-radius:6px; padding:4px 6px; background:#fafafa; font-size:12px;">${n}</span>`
    const panel = $('#chatgpt-plus');
    ).join('');
    if (!panel) { console.warn('[CommonDashboard.js] #chatgpt-plus non trovato'); return; }
  }
  function addFiles(list){ for (const f of list) attached.push(f.name); renderFiles(); }


  fileInput?.addEventListener('change', () => {
    const projectSel = $('#mpChatProject');
     if (fileInput.files?.length) addFiles(fileInput.files);
     const modeSel    = $('#mpChatMode');
     fileInput.value = '';
     const fileInput = $('#mpChatFile');
  });
    const drop      = $('#mpChatDrop');
   ['dragenter','dragover','dragleave','drop'].forEach(evt=>{
    const filesBox   = $('#mpChatFiles');
     drop?.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); });
     const promptEl  = $('#mpChatPrompt');
  });
    const sendBtn    = $('#mpChatSend');
   drop?.addEventListener('drop', e => {
    const ansBox    = $('#mpChatAnswer');
     const dt = e.dataTransfer;
    const clearBtn   = $('#mpChatClear');
     if (dt?.files?.length) addFiles(dt.files);
     const copyBtn    = $('#mpChatCopy');
  });
     const saveBtn    = $('#mpChatSave');


  sendBtn?.addEventListener('click', () => {
     const refreshBtn = $('#mpChatRefresh');
     const q = (promptEl.value||'').trim();
     const savedList  = $('#mpSavedList');
    const project = projectSel?.value || 'Generazione_capitoli';
     const mode = modeSel?.value || 'analysis';
    if (!q) { ansBox.textContent = 'Scrivi la domanda nel box sopra.'; return; }
    ansBox.textContent =
      `✅ Pannello pronto\n\n` +
      `• Progetto: ${project}\n` +
      `• Modalità: ${mode}\n` +
      `• Domanda:\n${q}\n\n` +
      `• Allegati (solo elenco, non inviati):\n` +
      (attached.length ? ('- ' + attached.join('\n- ')) : '(nessuno)');
  });


  clearBtn?.addEventListener('click', () => { ansBox.textContent = ''; });
     let attached = [];
  copyBtn?.addEventListener('click', async () => {
     const txt = ansBox.textContent || '';
    if (!txt.trim()) return;
    try { await navigator.clipboard.writeText(txt); copyBtn.textContent='Copiato!'; setTimeout(()=>copyBtn.textContent='Copia risposta',1200); }
    catch { alert('Impossibile copiare negli appunti.'); }
  });


  saveBtn?.addEventListener('click', async () => {
    function renderFiles(){
    const project = projectSel?.value || 'Generazione_capitoli';
      if (!filesBox) return;
    const content = ansBox.textContent || '';
       filesBox.innerHTML = attached.map(n =>
    if (!content.trim()){ alert('Nessuna risposta da salvare.'); return; }
         `<span style="border:1px solid #eee; border-radius:6px; padding:4px 6px; background:#fafafa; font-size:12px;">${n}</span>`
    try {
       ).join('');
       const r = await fetch('/dashboard/api/save_output.php', {
         method:'POST',
        headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ project, content })
      });
      const j = await r.json();
      if (!j.ok) throw new Error(j.error||'Errore salvataggio');
      alert('Risposta salvata: ' + j.file);
       await refreshList(); // aggiorna elenco dopo salvataggio
    } catch (e){
      alert('Salvataggio non ancora configurato (manca save_output.php).');
     }
     }
  });
    function addFiles(list){ for (const f of list) attached.push(f.name); renderFiles(); }
 
    fileInput?.addEventListener('change', () => {
      if (fileInput.files?.length) addFiles(fileInput.files);
      fileInput.value = '';
    });
    ['dragenter','dragover','dragleave','drop'].forEach(evt=>{
      drop?.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); });
    });
    drop?.addEventListener('drop', e => {
      const dt = e.dataTransfer;
      if (dt?.files?.length) addFiles(dt.files);
    });
 
    sendBtn?.addEventListener('click', () => {
      const q = (promptEl.value||'').trim();
      const project = projectSel?.value || 'Generazione_capitoli';
      const mode = modeSel?.value || 'analysis';
      if (!q) { ansBox.textContent = 'Scrivi la domanda nel box sopra.'; return; }
      ansBox.textContent =
        `✅ Pannello pronto\n\n` +
        `• Progetto: ${project}\n` +
        `• Modalità: ${mode}\n` +
        `• Domanda:\n${q}\n\n` +
        `• Allegati (solo elenco, non inviati):\n` +
        (attached.length ? ('- ' + attached.join('\n- ')) : '(nessuno)');
    });


  // --- Explorer ---
    clearBtn?.addEventListener('click', () => { ansBox.textContent = ''; });
  async function refreshList(){
    copyBtn?.addEventListener('click', async () => {
    const project = projectSel?.value || 'Generazione_capitoli';
      const txt = ansBox.textContent || '';
    if (!savedList) return;
      if (!txt.trim()) return;
    savedList.innerHTML = '<em style="color:#777;">Aggiorno…</em>';
      try { await navigator.clipboard.writeText(txt); copyBtn.textContent='Copiato!'; setTimeout(()=>copyBtn.textContent='Copia risposta',1200); }
    try {
      catch { alert('Impossibile copiare negli appunti.'); }
      const r = await fetch('/dashboard/api/list_saved_output.php?project=' + encodeURIComponent(project) + '&sub=output');
    });
      const j = await r.json();
 
      if (!j.ok) throw new Error(j.error||'Errore lista');
    // Salvataggio su /output/
      if (!j.files.length){
    saveBtn?.addEventListener('click', async () => {
         savedList.innerHTML = '<em style="color:#777;">Nessun file salvato.</em>';
      const project = projectSel?.value || 'Generazione_capitoli';
        return;
      const content = ansBox.textContent || '';
      if (!content.trim()){ alert('Nessuna risposta da salvare.'); return; }
      try {
        const r = await fetch('/dashboard/api/save_output.php', {
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body: JSON.stringify({ project, content })
        });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error||'Errore salvataggio');
        alert('Risposta salvata: ' + j.file);
        await refreshList();
      } catch (e){
         alert('Salvataggio non ancora configurato (manca save_output.php).');
       }
       }
       savedList.innerHTML = j.files.map(f=>{
    });
        const d = new Date(f.mtime*1000).toLocaleString();
 
        return `<div class="mp-saved-item" data-name="${f.name}" style="display:flex; gap:8px; align-items:center; justify-content:space-between; border-bottom:1px dashed #eee; padding:4px 0;">
    // ---- Explorer output/ ----
          <span><a href="#" class="open" data-name="${f.name}">${f.name}</a> <span style="color:#888;">(${f.size} B, ${d})</span></span>
    async function refreshList(){
          <button class="open" data-name="${f.name}" title="Apri nel box Risposta">Apri</button>
       const project = projectSel?.value || 'Generazione_capitoli';
        </div>`;
      if (!savedList) return;
      }).join('');
      savedList.innerHTML = '<em style="color:#777;">Aggiorno…</em>';
      savedList.querySelectorAll('.open').forEach(el=>{
      try {
        el.addEventListener('click', async (ev)=>{
        const r = await fetch('/dashboard/api/list_saved_output.php?project=' + encodeURIComponent(project) + '&sub=output');
          ev.preventDefault();
        const j = await r.json();
          await openFile(el.getAttribute('data-name'));
        if (!j.ok) throw new Error(j.error||'Errore lista');
        if (!j.files.length){
          savedList.innerHTML = '<em style="color:#777;">Nessun file salvato.</em>';
          return;
        }
        savedList.innerHTML = j.files.map(f=>{
          const d = new Date(f.mtime*1000).toLocaleString();
          return `<div class="mp-saved-item" data-name="${f.name}" style="display:flex; gap:8px; align-items:center; justify-content:space-between; border-bottom:1px dashed #eee; padding:4px 0;">
            <span><a href="#" class="open" data-name="${f.name}">${f.name}</a> <span style="color:#888;">(${f.size} B, ${d})</span></span>
            <button class="open" data-name="${f.name}" title="Apri nel box Risposta">Apri</button>
          </div>`;
        }).join('');
        savedList.querySelectorAll('.open').forEach(el=>{
          el.addEventListener('click', async (ev)=>{
            ev.preventDefault();
            await openFile(el.getAttribute('data-name'));
          });
         });
         });
       });
       } catch(e){
    } catch(e){
        savedList.innerHTML = '<span style="color:#c00;">Errore: '+e.message+'</span>';
      savedList.innerHTML = '<span style="color:#c00;">Errore: '+e.message+'</span>';
      }
     }
     }
  }
    async function openFile(name){
  async function openFile(name){
      const project = projectSel?.value || 'Generazione_capitoli';
    const project = projectSel?.value || 'Generazione_capitoli';
      try{
    try{
        const r = await fetch('/dashboard/api/read_saved_output.php', {
      const r = await fetch('/dashboard/api/read_saved_output.php', {
          method:'POST',
        method:'POST',
          headers:{'Content-Type':'application/json'},
        headers:{'Content-Type':'application/json'},
          body: JSON.stringify({ project, file: name })
        body: JSON.stringify({ project, file: name })
        });
      });
        const j = await r.json();
      const j = await r.json();
        if (!j.ok) throw new Error(j.error||'Errore lettura');
      if (!j.ok) throw new Error(j.error||'Errore lettura');
        ansBox.textContent = j.content || '';
      ansBox.textContent = j.content || '';
      } catch(e){
    } catch(e){
        alert('Errore apertura file: ' + e.message);
      alert('Errore apertura file: ' + e.message);
      }
     }
     }
  }
  // aggancia il bottone Aggiorna
  if (refreshBtn){
    refreshBtn.addEventListener('click', refreshList);
    console.log('mpChatRefresh agganciato');
  }
  // esponi per debug dalla console
  window.mpRefresh = refreshList;
  // aggiorna quando il pannello viene aperto (se usi toggleDashboardBox)
  const toggle = window.toggleDashboardBox;
  if (typeof toggle === 'function'){
    window.toggleDashboardBox = function(id){
      const res = toggle.apply(this, arguments);
      if (id === 'chatgpt-plus' && panel.style.display !== 'none'){
        refreshList();
      }
      return res;
    };
  }


  // fallback: al caricamento pagina
    // Bottone Aggiorna + primo popolamento
  document.addEventListener('DOMContentLoaded', refreshList);
    refreshBtn?.addEventListener('click', refreshList);
})();
    mw.hook('wikipage.content').add(refreshList);
  })();
});

Versione delle 08:58, 7 set 2025

// ============================================
// 🔧 CommonDashboard.js – versione SOLO server-proxy (no API key lato client)
// ============================================

// 📘 INTRODUZIONE
window.toggleDashboardBox = function (id) {
  const box = document.getElementById(id);
  if (box) box.style.display = box.style.display === "block" ? "none" : "block";
};

// ⚙️ CONNESSIONE API (via proxy server)
window.testAPIConnection = async function () {
  const prompt = (document.getElementById("test-prompt")?.value || "").trim();
  const output = document.getElementById("api-result");
  const model =
    document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";

  if (!prompt) {
    output.innerText = "⚠️ Inserisci un prompt di test.";
    return;
  }

  output.innerText = "⏳ Contatto il proxy sul server...";
  logActivity(`🚀 Test API via proxy – Modello: <strong>${model}</strong>`);

  try {
    const res = await fetch("/dashboard/api/openai_project_gpt.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ prompt, model })
    });

    const data = await res.json();

    if (data.status === "ok" && data.result) {
      output.innerText = "✅ Risposta: " + data.result;
      logActivity(`✅ Proxy OK – Modello: <strong>${model}</strong>`);
    } else {
      output.innerText = "❌ Errore: " + (data.error || "Risposta vuota");
      logActivity(`❌ Errore proxy: ${data.error || "risposta vuota"}`);
    }
  } catch (e) {
    output.innerText = "🚫 Errore di rete: " + e.message;
    logActivity(`❌ Errore rete: ${e.message}`);
  }
};

// 🎯 Analizza progetto con GPT (sempre via proxy)
window.analyzeProjectWithGPT = async function (title, notes) {
  try {
    const model =
      document.getElementById("model-select")?.value || "gpt-4o-2024-05-13";
    const prompt = `📌 Analizza questo progetto:\nTitolo: ${title}\nNote: ${notes}\n\nFornisci valutazione sintetica e suggerimenti operativi.`;
    logActivity(`🤖 Analisi GPT via proxy – <strong>${title}</strong>`);

    const res = await fetch("/dashboard/api/openai_project_gpt.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ prompt, model })
    });

    const data = await res.json();
    if (data.status === "ok" && data.result) {
      document.getElementById("response").value = data.result;
      logActivity(`✅ Analisi completata – <strong>${title}</strong>`);
    } else {
      alert("Errore GPT: " + (data.error || "Risposta vuota"));
      logActivity(`❌ Errore GPT: ${data.error || "risposta vuota"}`);
    }
  } catch (err) {
    console.error("❌ Errore completo GPT:", err);
    alert("Errore durante la richiesta a GPT:\n" + err.message);
    logActivity(`❌ Errore richiesta GPT: ${err.message}`);
  }
};

// 📊 SEZIONE: STATO PROGETTI
window.addNewProject = function () {
  const title = document.getElementById("newProjectTitle").value.trim();
  const notes = document.getElementById("newProjectNotes").value.trim();
  if (!title) {
    alert("Inserisci un titolo per il progetto!");
    return;
  }

  const table = document.getElementById("projectRows");
  const newRow = document.createElement("tr");
  newRow.innerHTML = `
    <td style="padding:0.5rem; border:1px solid #ccc;">${title}</td>
    <td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td>
    <td style="padding:0.5rem; border:1px solid #ccc;">${new Date().toLocaleDateString("it-IT")}</td>
    <td style="padding:0.5rem; border:1px solid #ccc;">${notes || "–"}</td>
    <td style="padding:0.5rem; border:1px solid #ccc;">
      <button onclick="analyzeProjectWithGPT('${title}', \`${notes || "–"}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
    </td>
  `;
  table.appendChild(newRow);
  window.closeProjectDialog();
  logActivity(`📌 Progetto aggiunto: <strong>${title}</strong> – ${notes}`);

  const payload = { title, notes, date: new Date().toLocaleDateString("it-IT") };
  fetch("/dashboard/api/write_project.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
    credentials: "include"
  })
    .then((r) => r.json())
    .then((data) => {
      if (!data.success) {
        alert("⚠️ Errore salvataggio su server: " + data.error);
        logActivity(`❌ Errore salvataggio progetto: ${data.error}`);
      } else {
        logActivity(`✅ Progetto salvato su server: <strong>${title}</strong>`);
      }
    })
    .catch((err) => {
      alert("❌ Errore rete salvataggio progetto.");
      console.error("Errore invio progetto:", err);
      logActivity("❌ Errore rete durante salvataggio progetto.");
    });
};

window.openProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "block";
};
window.closeProjectDialog = function () {
  document.getElementById("newProjectDialog").style.display = "none";
};

// 📥 Carica/Salva prompt.txt
window.loadPrompt = function () {
  fetch("/dashboard/api/read_file.php?projectName=global&subfolder=&filename=prompt.txt", {
    credentials: "include"
  })
    .then((r) => r.json())
    .then((data) => {
      if (data.status === "ok") {
        document.getElementById("promptArea").value = data.content;
        logActivity("📥 Caricato prompt.txt nella textarea.");
      } else {
        alert("Errore: " + data.error);
        logActivity("❌ Errore nel caricamento: " + data.error);
      }
    })
    .catch((e) => {
      alert("Errore nel caricamento: " + e);
      logActivity("❌ Errore nel caricamento di prompt.txt.");
    });
};

window.savePrompt = function () {
  const content = document.getElementById("promptArea").value;
  fetch("/dashboard/api/write_prompt.php", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    credentials: "include",
    body: "text=" + encodeURIComponent(content)
  })
    .then((r) => {
      if (!r.ok) throw new Error("Errore nel salvataggio");
      return r.text();
    })
    .then(() => {
      logActivity("💾 Salvato prompt.txt dal form.");
      alert("Prompt salvato con successo.");
    })
    .catch((e) => {
      alert("Errore nel salvataggio: " + e);
      logActivity("❌ Errore nel salvataggio di prompt.txt.");
    });
};

// 💾 Salva risposta GPT in file
window.salvaFileDaTextarea = function () {
  const content = document.getElementById("gpt-response-area").value;
  const filename = document.getElementById("gpt-filename").value.trim();
  const subfolder = document.getElementById("gpt-subfolder").value;
  const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";

  if (!filename || !content) {
    alert("Inserisci un nome file e assicurati che il contenuto non sia vuoto.");
    return;
  }

  fetch("/dashboard/api/write_file.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify({ projectName: project, subfolder, filename, content })
  })
    .then((r) => r.json())
    .then((data) => {
      if (data.status === "ok") {
        document.getElementById("gpt-response-area").value = data.content;
        logActivity(`💾 Salvato <strong>${filename}</strong> in progetto <strong>${project}</strong>.`);
        alert("File salvato con successo in: " + data.path);
      } else {
        alert("Errore: " + data.error);
        logActivity(`❌ Errore salvataggio ${filename}: ${data.error}`);
      }
    })
    .catch((e) => {
      console.error("❌ Errore:", e);
      alert("Errore durante il salvataggio.");
    });
};

// 📂 Carica file salvato in textarea GPT
window.caricaFileGPT = function () {
  const filename = document.getElementById("gpt-filename").value.trim();
  const subfolder = document.getElementById("gpt-subfolder").value;
  const project = document.getElementById("newProjectTitle").value.trim() || "SSO_LinkedIn";

  if (!filename) {
    alert("Inserisci il nome del file da caricare.");
    return;
  }

  fetch(
    `/dashboard/api/read_file.php?projectName=${encodeURIComponent(project)}&subfolder=${encodeURIComponent(
      subfolder
    )}&filename=${encodeURIComponent(filename)}`,
    { credentials: "include" }
  )
    .then((r) => r.json())
    .then((data) => {
      if (data.status === "ok") {
        document.getElementById("gpt-response-area").value = data.content;
        logActivity(`📂 Caricato <strong>${filename}</strong> da progetto <strong>${project}</strong>.`);
      } else {
        alert("Errore: " + data.error);
        logActivity(`❌ Errore nel caricamento di ${filename}: ${data.error}`);
      }
    })
    .catch((e) => {
      console.error("Errore:", e);
      alert("Errore durante il caricamento del file.");
    });
};

// 🚀 Carica automaticamente i progetti
window.loadAllProjects = function () {
  fetch("/dashboard/api/read_all_projects.php", { credentials: "include" })
    .then((r) => r.json())
    .then((data) => {
      if (!Array.isArray(data)) {
        logActivity("❌ Errore: formato dati inatteso dalla lista progetti.");
        return;
      }
      const table = document.getElementById("projectRows");
      table.innerHTML = "";
      data.forEach((project) => {
        const row = document.createElement("tr");
        row.innerHTML = `
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.title}</td>
          <td style="padding:0.5rem; border:1px solid #ccc; color:green; font-weight:bold;">✅ Completato</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.date}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">${project.notes || "–"}</td>
          <td style="padding:0.5rem; border:1px solid #ccc;">
            <button onclick="analyzeProjectWithGPT('${project.title}', \`${project.notes || "–"}\`)" style="padding: 0.3rem 0.6rem;">🤖 GPT</button>
          </td>`;
        table.appendChild(row);
        logActivity(`📌 Caricato progetto: <strong>${project.title}</strong>`);
      });
    })
    .catch((e) => {
      console.error("Errore nel caricamento progetti:", e);
      alert("Errore nel caricamento dei progetti.");
      logActivity("❌ Errore nel caricamento progetti.");
    });
};

// 📂 Importa file dal server (preset directory)
window.importServerFileFromPresetDir = function () {
  const baseDir = document.getElementById("baseDirSelect").value;
  const fileName = document.getElementById("fileNameInput").value.trim();
  const destFolder = document.getElementById("destinationPath").value.trim();

  if (!fileName || !destFolder) {
    alert("❌ Inserisci sia il nome file che la destinazione.");
    return;
  }

  const fullSourcePath = baseDir + fileName;

  fetch("/dashboard/api/copy_file_from_path.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify({ source: fullSourcePath, destination: destFolder })
  })
    .then((r) => r.json())
    .then((data) => {
      if (data.success) {
        alert("✅ File copiato: " + (data.path || destFolder));
        logActivity(`📁 Copiato: <code>${fullSourcePath}</code> → <strong>${destFolder}</strong>`);
      } else {
        alert("❌ Errore: " + data.error);
        logActivity(`❌ Errore copia file: ${data.error}`);
      }
    })
    .catch((e) => {
      alert("Errore di rete: " + e.message);
      console.error(e);
    });
};

// ✅ Onload
window.addEventListener("load", function () {
  loadAllProjects();
});

// 🧾 REGISTRO ATTIVITÀ
window.logActivity = function (messaggio) {
  const contenitore = document.getElementById("activityLogContent") || document.getElementById("activityLog");
  if (!contenitore) return;
  const ora = new Date().toLocaleTimeString("it-IT");
  const entry = document.createElement("div");
  entry.innerHTML = `<span style="color:gray;">[${ora}]</span> ${messaggio}`;
  contenitore.prepend(entry);
};
window.clearActivityLog = function () {
  const contenitore = document.getElementById("activityLogContent");
  if (contenitore) {
    contenitore.innerHTML = "<em>Registro svuotato.</em><br>";
    logActivity("🧹 Log svuotato manualmente.");
  }
};

// === ChatGPT plus (solo UI) ===

(function(){
  const $ = s => document.querySelector(s);
  const fileInput = $('#mpChatFile');
  const drop      = $('#mpChatDrop');
  const filesBox  = $('#mpChatFiles');
  const promptEl  = $('#mpChatPrompt');
  const sendBtn   = $('#mpChatSend');
  const answerBox = $('#mpChatAnswer');
  const clearBtn  = $('#mpChatClear');
  const copyBtn   = $('#mpChatCopy');

  if (!fileInput || !drop || !filesBox || !promptEl || !sendBtn || !answerBox) return;

  let attached = [];

  function renderFiles(){
    filesBox.innerHTML = attached.map(n => (
      `<span style="border:1px solid #eee; border-radius:6px; padding:4px 6px; background:#fafafa; font-size:12px;">${n}</span>`
    )).join('');
  }
  function addFiles(list){ for (const f of list) attached.push(f.name); renderFiles(); }

  fileInput.addEventListener('change', () => {
    if (fileInput.files?.length) addFiles(fileInput.files);
    fileInput.value = '';
  });
  ['dragenter','dragover','dragleave','drop'].forEach(evt=>{
    drop.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); });
  });
  drop.addEventListener('drop', e => {
    const dt = e.dataTransfer;
    if (dt?.files?.length) addFiles(dt.files);
  });

  sendBtn.addEventListener('click', () => {
    const q = (promptEl.value||'').trim();
    if (!q) { answerBox.textContent = 'Scrivi la domanda nel box sopra.'; return; }
    answerBox.textContent =
      '✅ Pannello ChatGPT plus pronto.\n\n' +
      '• Domanda:\n' + q + '\n\n' +
      '• Allegati (solo elenco, non inviati):\n' + (attached.length ? ('- ' + attached.join('\n- ')) : '(nessuno)');
  });

  clearBtn?.addEventListener('click', () => { answerBox.textContent = ''; });
  copyBtn?.addEventListener('click', async () => {
    const txt = answerBox.textContent || '';
    if (!txt.trim()) return;
    try { await navigator.clipboard.writeText(txt); copyBtn.textContent = 'Copiato!'; setTimeout(()=>copyBtn.textContent='Copia risposta',1200); }
    catch { alert('Impossibile copiare negli appunti.'); }
  });
})();


// === ChatGPT plus esteso (UI + Salva + Explorer) ===


mw.loader.using([], function () {
  // Esegui solo sulla Dashboard
  if (mw.config.get('wgPageName') !== 'Dashboard_Masticationpedia') return;

  console.log('[CommonDashboard.js] caricato'); // segnale in console

  (function(){
    const $ = s => document.querySelector(s);
    const panel = $('#chatgpt-plus');
    if (!panel) { console.warn('[CommonDashboard.js] #chatgpt-plus non trovato'); return; }

    const projectSel = $('#mpChatProject');
    const modeSel    = $('#mpChatMode');
    const fileInput  = $('#mpChatFile');
    const drop       = $('#mpChatDrop');
    const filesBox   = $('#mpChatFiles');
    const promptEl   = $('#mpChatPrompt');
    const sendBtn    = $('#mpChatSend');
    const ansBox     = $('#mpChatAnswer');
    const clearBtn   = $('#mpChatClear');
    const copyBtn    = $('#mpChatCopy');
    const saveBtn    = $('#mpChatSave');

    const refreshBtn = $('#mpChatRefresh');
    const savedList  = $('#mpSavedList');

    let attached = [];

    function renderFiles(){
      if (!filesBox) return;
      filesBox.innerHTML = attached.map(n =>
        `<span style="border:1px solid #eee; border-radius:6px; padding:4px 6px; background:#fafafa; font-size:12px;">${n}</span>`
      ).join('');
    }
    function addFiles(list){ for (const f of list) attached.push(f.name); renderFiles(); }

    fileInput?.addEventListener('change', () => {
      if (fileInput.files?.length) addFiles(fileInput.files);
      fileInput.value = '';
    });
    ['dragenter','dragover','dragleave','drop'].forEach(evt=>{
      drop?.addEventListener(evt, e => { e.preventDefault(); e.stopPropagation(); });
    });
    drop?.addEventListener('drop', e => {
      const dt = e.dataTransfer;
      if (dt?.files?.length) addFiles(dt.files);
    });

    sendBtn?.addEventListener('click', () => {
      const q = (promptEl.value||'').trim();
      const project = projectSel?.value || 'Generazione_capitoli';
      const mode = modeSel?.value || 'analysis';
      if (!q) { ansBox.textContent = 'Scrivi la domanda nel box sopra.'; return; }
      ansBox.textContent =
        `✅ Pannello pronto\n\n` +
        `• Progetto: ${project}\n` +
        `• Modalità: ${mode}\n` +
        `• Domanda:\n${q}\n\n` +
        `• Allegati (solo elenco, non inviati):\n` +
        (attached.length ? ('- ' + attached.join('\n- ')) : '(nessuno)');
    });

    clearBtn?.addEventListener('click', () => { ansBox.textContent = ''; });
    copyBtn?.addEventListener('click', async () => {
      const txt = ansBox.textContent || '';
      if (!txt.trim()) return;
      try { await navigator.clipboard.writeText(txt); copyBtn.textContent='Copiato!'; setTimeout(()=>copyBtn.textContent='Copia risposta',1200); }
      catch { alert('Impossibile copiare negli appunti.'); }
    });

    // Salvataggio su /output/
    saveBtn?.addEventListener('click', async () => {
      const project = projectSel?.value || 'Generazione_capitoli';
      const content = ansBox.textContent || '';
      if (!content.trim()){ alert('Nessuna risposta da salvare.'); return; }
      try {
        const r = await fetch('/dashboard/api/save_output.php', {
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body: JSON.stringify({ project, content })
        });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error||'Errore salvataggio');
        alert('Risposta salvata: ' + j.file);
        await refreshList();
      } catch (e){
        alert('Salvataggio non ancora configurato (manca save_output.php).');
      }
    });

    // ---- Explorer output/ ----
    async function refreshList(){
      const project = projectSel?.value || 'Generazione_capitoli';
      if (!savedList) return;
      savedList.innerHTML = '<em style="color:#777;">Aggiorno…</em>';
      try {
        const r = await fetch('/dashboard/api/list_saved_output.php?project=' + encodeURIComponent(project) + '&sub=output');
        const j = await r.json();
        if (!j.ok) throw new Error(j.error||'Errore lista');
        if (!j.files.length){
          savedList.innerHTML = '<em style="color:#777;">Nessun file salvato.</em>';
          return;
        }
        savedList.innerHTML = j.files.map(f=>{
          const d = new Date(f.mtime*1000).toLocaleString();
          return `<div class="mp-saved-item" data-name="${f.name}" style="display:flex; gap:8px; align-items:center; justify-content:space-between; border-bottom:1px dashed #eee; padding:4px 0;">
            <span><a href="#" class="open" data-name="${f.name}">${f.name}</a> <span style="color:#888;">(${f.size} B, ${d})</span></span>
            <button class="open" data-name="${f.name}" title="Apri nel box Risposta">Apri</button>
          </div>`;
        }).join('');
        savedList.querySelectorAll('.open').forEach(el=>{
          el.addEventListener('click', async (ev)=>{
            ev.preventDefault();
            await openFile(el.getAttribute('data-name'));
          });
        });
      } catch(e){
        savedList.innerHTML = '<span style="color:#c00;">Errore: '+e.message+'</span>';
      }
    }
    async function openFile(name){
      const project = projectSel?.value || 'Generazione_capitoli';
      try{
        const r = await fetch('/dashboard/api/read_saved_output.php', {
          method:'POST',
          headers:{'Content-Type':'application/json'},
          body: JSON.stringify({ project, file: name })
        });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error||'Errore lettura');
        ansBox.textContent = j.content || '';
      } catch(e){
        alert('Errore apertura file: ' + e.message);
      }
    }

    // Bottone Aggiorna + primo popolamento
    refreshBtn?.addEventListener('click', refreshList);
    mw.hook('wikipage.content').add(refreshList);
  })();
});