import { ref } from "vue";
import { useSessions } from "./useSessions";

const shiftPending = ref(false);
const ctrlPending = ref(false);

function sendQuickKey(type) {
  const { sessions, activeId } = useSessions();
  const session = sessions.value.find((s) => s.id === activeId.value);
  if (!session?.ws || session.ws.readyState !== WebSocket.OPEN) return;

  if (type === "shift") { shiftPending.value = !shiftPending.value; return; }
  if (type === "ctrl") { ctrlPending.value = !ctrlPending.value; return; }

  let data = "";
  switch (type) {
    case "ctrl_c": data = "\x03"; break;
    case "ctrl_z": data = "\x1a"; break;
    case "ctrl_d": data = "\x04"; break;
    case "ctrl_l": data = "\x0c"; break;
    case "esc":    data = "\x1b"; break;
    case "tab":    data = "\t";   break;
    case "slash":  data = "/";    break;
    case "minus":  data = "-";    break;
    case "dot":    data = ".";    break;
    case "hash":   data = "#";    break;
    case "amp":    data = "&";    break;
    case "up":     data = "\x1b[A"; break;
    case "down":   data = "\x1b[B"; break;
    case "right":  data = "\x1b[C"; break;
    case "left":   data = "\x1b[D"; break;
    case "enter":  data = "\r";   break;
    default: return;
  }

  if (shiftPending.value) {
    if (data === "\t") data = "\x1b[Z";
    else if (data === "/") data = "?";
    else if (data === "-") data = "_";
    else if (data === ".") data = ">";
    else if (data === "\x1b[A") data = "\x1b[1;2A";
    else if (data === "\x1b[B") data = "\x1b[1;2B";
    else if (data === "\x1b[C") data = "\x1b[1;2C";
    else if (data === "\x1b[D") data = "\x1b[1;2D";
    else if (data.length === 1) data = data.toUpperCase();
  }

  if (ctrlPending.value) {
    if (data === "\x1b[A") data = "\x1b[1;5A";
    else if (data === "\x1b[B") data = "\x1b[1;5B";
    else if (data === "\x1b[C") data = "\x1b[1;5C";
    else if (data === "\x1b[D") data = "\x1b[1;5D";
    else if (data.length === 1) {
      const ch = data.toLowerCase();
      if (ch >= "a" && ch <= "z") data = String.fromCharCode(ch.charCodeAt(0) - 96);
      else if (ch === "/") data = "\x1f";
    }
  }

  session.ws.send(JSON.stringify({ type: "input", data }));
  shiftPending.value = false;
  ctrlPending.value = false;
}

export function useQuickKeys() {
  return { shiftPending, ctrlPending, sendQuickKey };
}
