Code viewer for World: New World
// === Robust Ancient Brain JS UI (no AB.* calls) ===
// Paste this into the Ancient Brain world JS editor (Hidden URL ON).
// It will create the UI on document.body and print helpful console errors if something fails.

(function () {
  try {
    // wipe body (safe in a controlled world)
    document.body.innerHTML = "";

    // container
    const container = document.createElement("div");
    container.style.fontFamily = "system-ui, sans-serif";
    container.style.margin = "18px";
    container.style.maxWidth = "980px";

    container.innerHTML = `
      <h2>Riddle Accuracy — Cohere vs Hugging Face</h2>
      <p>Enter your keys (used locally) and click "Run one riddle (debug)". If the page stays blank, open the browser console (F12) and look for errors.</p>

      <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; align-items:start; margin-bottom:10px;">
        <div>
          <label style="font-weight:600">Cohere API key</label><br>
          <input type="password" id="cohereKey" placeholder="Cohere API Key" style="width:100%"><br>
          <label style="font-weight:600">Model (Cohere)</label><br>
          <input type="text" id="cohereModel" value="command-r-plus" style="width:100%">
        </div>
        <div>
          <label style="font-weight:600">Hugging Face API key</label><br>
          <input type="password" id="hfKey" placeholder="Hugging Face Token" style="width:100%"><br>
          <label style="font-weight:600">Model (HF)</label><br>
          <input type="text" id="hfModel" value="google/flan-t5-base" style="width:100%">
        </div>
      </div>

      <div style="margin-bottom:8px;">
        <button id="runBtn" style="padding:8px 12px">Run one riddle (debug)</button>
        <span style="margin-left:12px">Delay(ms): <input id="delay" value="400" style="width:70px"></span>
      </div>

      <div id="status" style="margin-bottom:8px; color:#666"></div>

      <pre id="output" style="background:#f6f6f6;padding:12px;border-radius:6px; max-height:420px; overflow:auto;"></pre>
    `;

    document.body.appendChild(container);

    // small helper: safe fetch implementations remain same as before
    async function callCohere(apiKey, model, prompt) {
      try {
        const res = await fetch("https://api.cohere.ai/v1/chat", {
          method: "POST",
          headers: {
            "Authorization": `Bearer ${apiKey}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            model: model || "command-r-plus",
            messages: [{ role: "user", content: prompt }],
          }),
        });
        if (!res.ok) {
          const txt = await res.text();
          throw new Error(`Cohere API error: ${res.status} ${txt}`);
        }
        const j = await res.json();
        const text = j.text || j.message?.content?.[0]?.text || j.message?.content?.text || "";
        return text.trim() || "(no text returned)";
      } catch (e) {
        console.error("callCohere error:", e);
        return `ERROR: ${e.message}`;
      }
    }

    async function callHF(apiKey, model, prompt) {
      try {
        const res = await fetch(`https://api-inference.huggingface.co/models/${model}`, {
          method: "POST",
          headers: {
            "Authorization": `Bearer ${apiKey}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ inputs: prompt }),
        });
        if (!res.ok) {
          const txt = await res.text();
          throw new Error(`Hugging Face API error: ${res.status} ${txt}`);
        }
        const j = await res.json();
        if (Array.isArray(j) && j[0]?.generated_text) return j[0].generated_text.trim();
        if (j.generated_text) return j.generated_text.trim();
        return JSON.stringify(j);
      } catch (e) {
        console.error("callHF error:", e);
        return `ERROR: ${e.message}`;
      }
    }

    // simple riddle set (debug)
    const riddle = "What has to be broken before you can use it?";
    const gold = "egg";

    // run function
    async function runOneRiddle() {
      const output = document.getElementById("output");
      const status = document.getElementById("status");
      output.textContent = "";
      status.textContent = "Running... (check console if this stalls)";

      const cohereKey = document.getElementById("cohereKey").value.trim();
      const cohereModel = document.getElementById("cohereModel").value.trim() || "command-r-plus";
      const hfKey = document.getElementById("hfKey").value.trim();
      const hfModel = document.getElementById("hfModel").value.trim() || "google/flan-t5-base";

      try {
        // quick local validation
        if (!cohereKey) { status.textContent = "Enter Cohere key."; return; }
        if (!hfKey) { status.textContent = "Enter Hugging Face key."; return; }

        output.textContent += `Riddle: ${riddle} (gold: ${gold})\n\n`;

        // call both in parallel but catch individually
        const [a, b] = await Promise.all([
          callCohere(cohereKey, cohereModel, riddle),
          callHF(hfKey, hfModel, riddle),
        ]);

        output.textContent += `[Cohere] → ${a}\n\n`;
        output.textContent += `[Hugging Face] → ${b}\n\n`;
        status.textContent = "Done.";
      } catch (err) {
        console.error("runOneRiddle top error:", err);
        status.textContent = "Error running request — see console for details.";
        output.textContent += "Top-level error: " + (err && err.message ? err.message : String(err));
      }
    }

    // attach handler
    document.getElementById("runBtn").addEventListener("click", runOneRiddle);

    // debug signal
    console.log("Riddle UI created successfully.");
    document.getElementById("status").textContent = "Ready. Enter keys and click Run.";

  } catch (err) {
    // if UI build fails, show error plainly
    console.error("UI build failed:", err);
    document.body.innerHTML = "<h2>UI build failed</h2><pre>" + String(err) + "</pre>";
  }
})();