<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="manifest" href="/manifest.json">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="theme-color" content="#0d0d0d">
<title>$name_esc — clipbox</title>
<link rel="stylesheet" href="/static/common.css">
<link rel="stylesheet" href="/static/editor.css">
</head>
<body>
$tabs

<header>
  <div class="left">
    <h1><a href="/">clipbox</a> / <span class="buf" id="buf-name" onclick="startRename()">$name_esc</span></h1>
    <span class="status" id="status"></span>
  </div>
  <div class="actions">
    <button id="copy-btn" title="Copy to clipboard">Copy</button>
    <button id="del-btn" title="Delete buffer">Delete</button>
  </div>
</header>

<div class="editor-wrap">
  <textarea id="editor" placeholder="Type or paste here..." spellcheck="false">$content_esc</textarea>
</div>

<script>
(function() {
  const editor = document.getElementById("editor");
  const status = document.getElementById("status");
  const copyBtn = document.getElementById("copy-btn");
  const bufName = $name_json;

  let saveTimer = null;
  let lastSaved = editor.value;

  function setStatus(text, cls) {
    status.textContent = text;
    status.className = "status " + (cls || "");
  }

  async function save() {
    const content = editor.value;
    if (content === lastSaved) return;
    setStatus("Saving...", "saving");
    try {
      const res = await fetch("/" + encodeURIComponent(bufName), {
        method: "PUT",
        headers: { "Content-Type": "text/plain" },
        body: content
      });
      if (res.ok) {
        lastSaved = content;
        setStatus("Saved", "saved");
      } else {
        setStatus("Error saving", "error");
      }
    } catch (e) {
      setStatus("Connection lost", "error");
    }
  }

  editor.addEventListener("input", function() {
    clearTimeout(saveTimer);
    setStatus("Editing...", "");
    saveTimer = setTimeout(save, 400);
  });

  editor.addEventListener("blur", save);
  document.addEventListener("visibilitychange", function() {
    if (document.visibilityState === "hidden") save();
  });

  copyBtn.addEventListener("click", async function() {
    try {
      await navigator.clipboard.writeText(editor.value);
    } catch (e) {
      var ta = document.createElement("textarea");
      ta.value = editor.value;
      ta.style.position = "fixed";
      ta.style.opacity = "0";
      document.body.appendChild(ta);
      ta.focus();
      ta.select();
      document.execCommand("copy");
      document.body.removeChild(ta);
    }
    copyBtn.textContent = "Copied!";
    copyBtn.classList.add("copy-ok");
    setTimeout(() => {
      copyBtn.textContent = "Copy";
      copyBtn.classList.remove("copy-ok");
    }, 1500);
  });

  document.getElementById("del-btn").addEventListener("click", async function() {
    if (!confirm("Delete buffer '" + bufName + "'?")) return;
    const res = await fetch("/" + encodeURIComponent(bufName), { method: "DELETE" });
    if (res.ok) window.location.href = "/";
  });

  window.startRename = function() {
    var span = document.getElementById("buf-name");
    var input = document.createElement("input");
    input.type = "text";
    input.className = "buf-input";
    input.value = bufName;
    input.size = Math.max(bufName.length, 6);
    span.replaceWith(input);
    input.focus();
    input.select();
    async function doRename() {
      var newName = input.value.replace(/[^a-zA-Z0-9_\\-]/g, "").trim();
      if (!newName || newName === bufName) {
        location.reload();
        return;
      }
      var res = await fetch("/api/rename", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ old_name: bufName, new_name: newName })
      });
      if (res.ok) {
        window.location.href = "/" + encodeURIComponent(newName);
      } else {
        alert("Rename failed");
        location.reload();
      }
    }
    input.addEventListener("blur", doRename);
    input.addEventListener("keydown", function(e) {
      if (e.key === "Enter") { e.preventDefault(); input.blur(); }
      if (e.key === "Escape") { location.reload(); }
    });
  };

  if (editor.value.length > 0) setStatus("Saved", "saved");
})();
</script>
</body>
</html>
