/* Persistent store — multiple trees, in localStorage */

const STORAGE_KEY = "tree-view.workspace.v1";

const uid = (prefix = "id") =>
  `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;

function makeNode(overrides = {}) {
  return {
    id: uid("n"),
    title: "Untitled",
    notes: "",
    shape: "circle", // circle | rect | card
    emoji: "",
    tags: [],
    checks: [], // { id, text, done }
    links: [], // node ids
    value: null, // numeric (money) value or null
    valueCurrency: "$",
    valueSuffix: "", // e.g. "/mo"
    status: null, // null | "red" | "yellow" | "green"
    x: 0,
    y: 0,
    collapsed: false,
    ...overrides,
  };
}

function makeTree(name = "Untitled tree") {
  const n1 = makeNode({ title: "Subscriptions", x: 600, y: 150, shape: "circle" });
  const n2 = makeNode({ title: "Notion", x: 380, y: 320, shape: "circle" });
  const n3 = makeNode({ title: "Claude", x: 820, y: 320, shape: "circle" });
  const n4 = makeNode({
    title: "Tasks",
    x: 200, y: 510, shape: "card",
    checks: [
      { id: uid("c"), text: "Example one", done: false },
      { id: uid("c"), text: "Example two", done: false },
    ],
    tags: ["work"],
  });
  const n5 = makeNode({ title: "Ideas", x: 560, y: 510, shape: "card",
    notes: "Place to brainstorm — open the inspector to add notes, checklists and tags.",
    tags: ["thinking"],
  });
  // Demo: assign values to subscriptions
  n2.value = 10; n2.valueSuffix = "/mo";
  n3.value = 20; n3.valueSuffix = "/mo";
  return {
    id: uid("t"),
    name,
    createdAt: Date.now(),
    updatedAt: Date.now(),
    nodes: { [n1.id]: n1, [n2.id]: n2, [n3.id]: n3, [n4.id]: n4, [n5.id]: n5 },
    edges: [
      { id: uid("e"), from: n1.id, to: n2.id },
      { id: uid("e"), from: n1.id, to: n3.id },
      { id: uid("e"), from: n2.id, to: n4.id },
      { id: uid("e"), from: n2.id, to: n5.id },
    ],
    view: { x: 0, y: 0, zoom: 1 },
  };
}

function emptyTree(name = "New tree") {
  const root = makeNode({ title: "Root", x: 600, y: 280, shape: "circle" });
  return {
    id: uid("t"),
    name,
    createdAt: Date.now(),
    updatedAt: Date.now(),
    nodes: { [root.id]: root },
    edges: [],
    view: { x: 0, y: 0, zoom: 1 },
  };
}

function loadWorkspace() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      const parsed = JSON.parse(raw);
      if (parsed && Array.isArray(parsed.trees) && parsed.trees.length) {
        return parsed;
      }
    }
  } catch (e) { /* ignore */ }
  const first = makeTree("Welcome");
  return { trees: [first], activeId: first.id };
}

function saveWorkspace(ws) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(ws));
  } catch (e) { /* ignore */ }
}

window.TVStore = { uid, makeNode, makeTree, emptyTree, loadWorkspace, saveWorkspace, STORAGE_KEY };
