import { useSessions } from "./useSessions";
import { useNotice } from "./useNotice";

function bytesToBase64(buffer) {
  const bytes = new Uint8Array(buffer);
  const chunkSize = 0x8000;
  let binary = "";
  for (let i = 0; i < bytes.length; i += chunkSize) {
    binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
  }
  return btoa(binary);
}

function chunkBase64(text, size = 76) {
  const chunks = [];
  for (let i = 0; i < text.length; i += size) chunks.push(text.slice(i, i + size));
  return chunks.join("\n");
}

function safeFilename(name) { return name.replace(/[^a-zA-Z0-9._-]/g, "-"); }

function formatTimestamp(date = new Date()) {
  const pad = (v) => String(v).padStart(2, "0");
  return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
}

function isEditableTarget(target) {
  if (!target || typeof target !== "object") return false;
  const tag = target.tagName?.toLowerCase();
  if (tag === "input" || tag === "textarea") return true;
  return !!target.isContentEditable;
}

function sendImageToTerminal(file) {
  const { sessions, activeId } = useSessions();
  const { showNotice } = useNotice();
  const session = sessions.value.find((s) => s.id === activeId.value);

  if (!session?.ws || session.ws.readyState !== WebSocket.OPEN) {
    showNotice("已识别剪贴板图片，但当前没有可用终端连接", "warning");
    return;
  }
  const maxBytes = 2 * 1024 * 1024;
  if (file.size > maxBytes) { showNotice("图片过大，已取消粘贴（限制 2MB）", "warning"); return; }

  const ext = (file.type || "image/png").split("/")[1] || "png";
  const filename = safeFilename(`clipboard-${formatTimestamp()}.${ext}`);
  const reader = new FileReader();
  reader.onload = () => {
    try {
      const base64 = bytesToBase64(reader.result);
      const marker = `__MENGYA_CLIP_${Date.now()}__`;
      const script = `cat <<'${marker}' | base64 -d > ${filename}\n${chunkBase64(base64)}\n${marker}\n`;
      session.ws.send(JSON.stringify({ type: "input", data: script }));
      session.term?.writeln(`\r\n\x1b[90m[已接收剪贴板图片，保存为 ${filename}]\x1b[0m`);
      showNotice(`已发送图片到终端：${filename}`, "success");
    } catch {
      showNotice("图片粘贴失败，请重试", "error");
    }
  };
  reader.onerror = () => showNotice("读取剪贴板图片失败", "error");
  reader.readAsArrayBuffer(file);
}

function handlePaste(event) {
  if (!event?.clipboardData) return;
  if (isEditableTarget(event.target)) return;
  const text = event.clipboardData.getData("text/plain");
  if (text) return;
  const items = Array.from(event.clipboardData.items || []);
  const imageItem = items.find((item) => item.type?.startsWith("image/"));
  if (!imageItem) return;
  const file = imageItem.getAsFile();
  if (!file) return;
  event.preventDefault();
  event.stopPropagation();
  sendImageToTerminal(file);
}

function setupClipboard() { document.addEventListener("paste", handlePaste); }
function teardownClipboard() { document.removeEventListener("paste", handlePaste); }

export function useClipboard() {
  return { setupClipboard, teardownClipboard };
}
