const STORAGE_KEY = "trainingMapDots.v1";

let state = {
  zoom: 1,
  mode: "add",
  dots: [],
  selectedId: null
};

const stage = document.getElementById("stage");
const mapImg = document.getElementById("mapImg");

const titleEl = document.getElementById("title");
const notesEl = document.getElementById("notes");

function save() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(state.dots));
}

function load() {
  const data = localStorage.getItem(STORAGE_KEY);
  if (data) state.dots = JSON.parse(data);
}

function render() {
  document.querySelectorAll(".dot").forEach(e => e.remove());

  state.dots.forEach(d => {
    const el = document.createElement("div");
    el.className = "dot";
    el.style.left = d.x + "px";
    el.style.top = d.y + "px";

    if (d.id === state.selectedId) el.classList.add("selected");

    el.onclick = () => selectDot(d.id);

    stage.appendChild(el);
  });

  document.getElementById("dotCount").textContent = state.dots.length;
}

function selectDot(id) {
  state.selectedId = id;
  const d = state.dots.find(x => x.id === id);

  if (!d) return;

  titleEl.value = d.title;
  notesEl.value = d.notes;

  render();
}

stage.addEventListener("click", (e) => {
  if (state.mode !== "add") return;

  const rect = mapImg.getBoundingClientRect();

  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  const dot = {
    id: Date.now().toString(),
    x,
    y,
    title: "New",
    notes: ""
  };

  state.dots.push(dot);
  save();
  render();
});

document.getElementById("saveBtn").onclick = () => {
  const d = state.dots.find(x => x.id === state.selectedId);
  if (!d) return;

  d.title = titleEl.value;
  d.notes = notesEl.value;

  save();
  render();
};

document.getElementById("deleteBtn").onclick = () => {
  state.dots = state.dots.filter(d => d.id !== state.selectedId);
  state.selectedId = null;

  save();
  render();
};

document.getElementById("modeAdd").onclick = () => state.mode = "add";
document.getElementById("modeSelect").onclick = () => state.mode = "select";

document.getElementById("exportBtn").onclick = () => {
  const blob = new Blob([JSON.stringify(state.dots)], { type: "application/json" });
  const a = document.createElement("a");
  a.href = URL.createObjectURL(blob);
  a.download = "dots.json";
  a.click();
};

document.getElementById("importBtn").onclick = () => {
  document.getElementById("importFile").click();
};

document.getElementById("importFile").onchange = async (e) => {
  const file = e.target.files[0];
  const text = await file.text();
  state.dots = JSON.parse(text);
  save();
  render();
};

document.getElementById("wipeBtn").onclick = () => {
  if (prompt("Type WIPE") === "WIPE") {
    state.dots = [];
    save();
    render();
  }
};

load();
render();